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
901d627bcb173f79a097bc2c39735109d4fa4ff1
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/default.lean
ec86e1ba394168793f7433d1caad747266954f3c
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
567
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.core init.logic init.category init.data.basic import init.propext init.cc_lemmas init.funext init.category.combinators init.function init.classical import init.util init.coe init.wf init.meta init.algebra init.data import init.native def debugger.attr : user_attribute := { name := `breakpoint, descr := "breakpoint for debugger" } run_command attribute.register `debugger.attr
5873c306ad7222588e571966e59ac1c9900292ed
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_2430.lean
516b3caa82c3278e012aa579ae6af0c946ce67d7
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
686
lean
import data.real.basic def converges_to (s : ℕ → ℝ) (a : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, abs (s n - a) < ε variables {s t : ℕ → ℝ} {a : ℝ} theorem exists_abs_le_of_converges_to (cs : converges_to s a) : ∃ N b, ∀ n, N ≤ n → abs (s n) < b := sorry -- BEGIN lemma aux (cs : converges_to s a) (ct : converges_to t 0) : converges_to (λ n, s n * t n) 0 := begin intros ε εpos, dsimp, rcases exists_abs_le_of_converges_to cs with ⟨N₀, B, h₀⟩, have Bpos : 0 < B, from lt_of_le_of_lt (abs_nonneg _) (h₀ N₀ (le_refl _)), have pos₀ : ε / B > 0, from div_pos εpos Bpos, cases ct _ pos₀ with N₁ h₁, sorry end -- END
bd1ab17537e3bebe9ff9365fa5215cb5619c3133
c8d830ce6c7de4840cf0c892d8b58e7e8df97e37
/src/common_meta.lean
eef54827d3e5412c443f600938806c43fd18947e
[]
no_license
loganrjmurphy/lean-strategies
4b8dd54771bb421c929a8bcb93a528ce6c1a70f1
020e2a65dc2ab475696dfea5ad8935a0a4085918
refs/heads/main
1,682,732,168,860
1,614,820,630,000
1,614,820,630,000
278,458,841
3
0
null
1,613,755,728,000
1,594,324,763,000
Lean
UTF-8
Lean
false
false
6,962
lean
import system.io tactic justification LTS property_catalogue.LTL.patterns open io list lean.parser tactic interactive.types open lean.parser (ident) variable {α : Type} meta structure PROOF_STATE (α : Type) := (init_goal : expr := default expr) (input : property.input α := default (property.input α)) (input_string : string := string.empty) (strat_expr : expr := default expr) (solved : bool := ff) (originals : list (string × expr) := []) (total : list expr := []) (used : list string := []) (PROPS : expr := default expr) (tscript : list string := []) (hints : list string := []) (unused : string := string.empty) meta def originals_aux : expr → list expr | `(list.cons %%h %%t) := match h with | `(λ x, x ⊨ %%prop) := do [prop] ++ originals_aux t | _ := originals_aux t end | _ := [] meta def get_originals (ps : PROOF_STATE α) : (PROOF_STATE α) := let l := originals_aux ps.PROPS in let l':= (list.range l.length).map (λ i, ("P" ++ to_string (i+1) : string)) in {originals := list.zip l' l ..ps} namespace PROOF_STATE meta def log (ps : PROOF_STATE α) (s : string) : tactic (PROOF_STATE α):= return { tscript := ps.tscript ++ [s] ..ps} meta def fill_props : list expr → tactic (list expr) | [] := return [] | (h::t) := do h_t ← infer_type h, match h_t with | `(sat %%foo %%bar) := do et ← fill_props t, return ([h] ++ et) | _ := fill_props t end end PROOF_STATE def tscript_string : list string → string | [] := string.empty | [x] := x ++ "," | (h::t) := h ++ ", \n " ++ tscript_string t def unused_string : list string → string | [] := string.empty | (h::t) :="\n-- " ++ h ++ unused_string t def hints_string : list string → string | [] := string.empty | (h::t) := "\n--HINT " ++ h ++ hints_string t meta def foo : list string → list (string × expr) → list expr | [] _ := [] | _ [] := [] | (a::s) (b::t) := if (a = b.1) then [b.2] ++ (foo s t) else if (a ∈ (b::t).unzip.1) then foo (a::s) (t) else foo s (b::t) meta def stringify : list expr → tactic string | [] := return string.empty | (h::t) := do h ← tactic_format_expr h, return ("--" ++ h.to_string ++"\n") meta def get_unused (ps : PROOF_STATE α) : tactic string := let l := foo ps.used ps.originals in stringify (list.diff ps.originals.unzip.2 l) meta def read {α : Type} (f : string) (p : lean.parser α) : lean.parser α := do buf ← unsafe_run_io (io.fs.read_file f), (a, s) ← with_input p buf.to_string, return a meta def set_goal (goal : expr) : tactic unit := do v <- mk_meta_var goal, set_goals (list.cons v nil), return () meta def is_solved : tactic bool := done >> return tt <|> return ff meta def try_tactic_on_goal (tac: tactic unit) (goal : expr) : tactic bool := set_goal goal >> tac >> is_solved meta def convert_to_premises (n : ℕ) : tactic unit := do (list.range n).mmap (λ i, do let h : name := ("P" ++ to_string (i+1) : string), tactic.interactive.«have» h none ```(H ⟨%%(reflect i), dec_trivial⟩)), `[clear H, try {dsimp at *}] meta def load_properties : list expr → tactic (list expr) | [] := return [] | (a::l) := do t ← infer_type a, let b : bool := (t.list_local_consts = []), if !b then do ls ← load_properties l, return (a::ls) else load_properties l meta def analyze (ps : PROOF_STATE α) : tactic (PROOF_STATE α) := do tactic.interactive.apply ``(property.deductive_of_justfd _), `[rw property.justified], `[rw set.Inter], x ← get_unused_name `x, H ← get_unused_name `H, intro x, intro H, `[simp at *], convert_to_premises ps.input.length, `[repeat {rw sat at *}], try `[simp at *], return ps meta def base_case (ps : PROOF_STATE α) (tgt : expr) : list expr → tactic (PROOF_STATE α) | [] := return ps | (h::t) := do h_t ← infer_type h, (unify h_t tgt) >> (do `[exact %%h], h' ← tactic_format_expr h, ps ← ps.log $ "base_case " ++ h'.to_string, return { used := ps.used ++ [h'.to_string] ..ps}) <|> base_case t meta def Inductive_hyp (tgt : expr) : list expr → tactic unit | [] := return () | (h::t) := do h_t ← infer_type h, (unify h_t tgt) >> (do `[exact %%h], return ()) <|> Inductive_hyp t meta def get_index_expr : list expr → tactic expr | [] := failed | (h::t) := do h_t ← infer_type h, nnat ← to_expr ``(ℕ), unify nnat h_t >> return h <|> get_index_expr t meta def inductive_case (ps : PROOF_STATE α) : list expr → tactic (PROOF_STATE α) | [] := return ps | (h ::t) := do h_t ← infer_type h, match h_t with | `(∀ i : ℕ, %%body) := (do ii ← local_context >>= get_index_expr, let e := expr.mk_app h [ii], `[apply %%e], h' ← tactic_format_expr h, ps ← ps.log $ "inductive_case " ++ h'.to_string, return {used := ps.used ++ [h'.to_string] ..ps}) <|> inductive_case t | _ := inductive_case t end meta def by_induction (ps : PROOF_STATE α) : tactic (PROOF_STATE α) := do analyze ps, l ← local_context >>= load_properties, let ps := {total := l ..ps}, `[repeat {rw sat at *}], i ← get_unused_name `i, IH ← get_unused_name `IH, intro i, `[induction i with i IH], -- fix this, logan! ps ← ps.log "by_induction", tgt ← target, p₁ ← local_context >>= base_case ps tgt, p₂ ← local_context >>= inductive_case p₁, tgt ← target, local_context >>= Inductive_hyp tgt , `[repeat {rw sat at *}], return p₂ meta def match_premises : tactic unit := do repeat1 (applyc `and.intro), `[repeat {assumption}] open interactive (parse) meta def tactic.interactive.analyze (n : ℕ) : tactic unit := do tactic.interactive.apply ``(property.deductive_of_justfd _), `[rw property.justified], `[rw set.Inter], x ← get_unused_name `x, H ← get_unused_name `H, intro x, intro H, `[simp at *], convert_to_premises n, `[repeat {rw sat at *}], try `[simp at *] meta def tactic.interactive.base_case (H : parse ident) : tactic unit := do e ← get_local H, tactic.exact e meta def tactic.interactive.inductive_case (H : parse ident) : tactic unit := do e ← get_local H, ii ← local_context >>= get_index_expr, let e := expr.mk_app e [ii], `[apply %%e], `[assumption] meta def tactic.interactive.by_induction : tactic unit := do tactic.interactive.analyze 2, i ← get_unused_name `i, IH ← get_unused_name `IH, `[repeat {rw sat at *}], try `[simp at *], intro i, `[induction i with i IH] -- fix this, logan!
bf5db9f867a1f2a618b7b47417ed7c2bde7790c3
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/geometry/manifold/mfderiv.lean
5c960d714bba7be4c1ee09caece77c4b2b6b6cc3
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
64,899
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 geometry.manifold.basic_smooth_bundle /-! # The derivative of functions between smooth manifolds Let `M` and `M'` be two smooth manifolds with corners over a field `𝕜` (with respective models with corners `I` on `(E, H)` and `I'` on `(E', H')`), and let `f : M → M'`. We define the derivative of the function at a point, within a set or along the whole space, mimicking the API for (Fréchet) derivatives. It is denoted by `mfderiv I I' f x`, where "m" stands for "manifold" and "f" for "Fréchet" (as in the usual derivative `fderiv 𝕜 f x`). ## Main definitions * `unique_mdiff_on I s` : predicate saying that, at each point of the set `s`, a function can have at most one derivative. This technical condition is important when we define `mfderiv_within` below, as otherwise there is an arbitrary choice in the derivative, and many properties will fail (for instance the chain rule). This is analogous to `unique_diff_on 𝕜 s` in a vector space. Let `f` be a map between smooth manifolds. The following definitions follow the `fderiv` API. * `mfderiv I I' f x` : the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable, this is `0`. * `mfderiv_within I I' f s x` : the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable within `s`, this is `0`. * `mdifferentiable_at I I' f x` : Prop expressing whether `f` is differentiable at `x`. * `mdifferentiable_within_at 𝕜 f s x` : Prop expressing whether `f` is differentiable within `s` at `x`. * `has_mfderiv_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative at `x`. * `has_mfderiv_within_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative within `s` at `x`. * `mdifferentiable_on I I' f s` : Prop expressing that `f` is differentiable on the set `s`. * `mdifferentiable I I' f` : Prop expressing that `f` is differentiable everywhere. * `tangent_map I I' f` : the derivative of `f`, as a map from the tangent bundle of `M` to the tangent bundle of `M'`. We also establish results on the differential of the identity, constant functions, charts, extended charts. For functions between vector spaces, we show that the usual notions and the manifold notions coincide. ## Implementation notes The tangent bundle is constructed using the machinery of topological fiber bundles, for which one can define bundled morphisms and construct canonically maps from the total space of one bundle to the total space of another one. One could use this mechanism to construct directly the derivative of a smooth map. However, we want to define the derivative of any map (and let it be zero if the map is not differentiable) to avoid proof arguments everywhere. This means we have to go back to the details of the definition of the total space of a fiber bundle constructed from core, to cook up a suitable definition of the derivative. It is the following: at each point, we have a preferred chart (used to identify the fiber above the point with the model vector space in fiber bundles). Then one should read the function using these preferred charts at `x` and `f x`, and take the derivative of `f` in these charts. Due to the fact that we are working in a model with corners, with an additional embedding `I` of the model space `H` in the model vector space `E`, the charts taking values in `E` are not the original charts of the manifold, but those ones composed with `I`, called extended charts. We define `written_in_ext_chart I I' x f` for the function `f` written in the preferred extended charts. Then the manifold derivative of `f`, at `x`, is just the usual derivative of `written_in_ext_chart I I' x f`, at the point `(ext_chart_at I x) x`. There is a subtelty with respect to continuity: if the function is not continuous, then the image of a small open set around `x` will not be contained in the source of the preferred chart around `f x`, which means that when reading `f` in the chart one is losing some information. To avoid this, we include continuity in the definition of differentiablity (which is reasonable since with any definition, differentiability implies continuity). *Warning*: the derivative (even within a subset) is a linear map on the whole tangent space. Suppose that one is given a smooth submanifold `N`, and a function which is smooth on `N` (i.e., its restriction to the subtype `N` is smooth). Then, in the whole manifold `M`, the property `mdifferentiable_on I I' f N` holds. However, `mfderiv_within I I' f N` is not uniquely defined (what values would one choose for vectors that are transverse to `N`?), which can create issues down the road. The problem here is that knowing the value of `f` along `N` does not determine the differential of `f` in all directions. This is in contrast to the case where `N` would be an open subset, or a submanifold with boundary of maximal dimension, where this issue does not appear. The predicate `unique_mdiff_on I N` indicates that the derivative along `N` is unique if it exists, and is an assumption in most statements requiring a form of uniqueness. On a vector space, the manifold derivative and the usual derivative are equal. This means in particular that they live on the same space, i.e., the tangent space is defeq to the original vector space. To get this property is a motivation for our definition of the tangent space as a single copy of the vector space, instead of more usual definitions such as the space of derivations, or the space of equivalence classes of smooth curves in the manifold. ## Tags Derivative, manifold -/ noncomputable theory open_locale classical topological_space manifold open set universe u section derivatives_definitions /-! ### Derivative of maps between manifolds The derivative of a smooth map `f` between smooth manifold `M` and `M'` at `x` is a bounded linear map from the tangent space to `M` at `x`, to the tangent space to `M'` at `f x`. Since we defined the tangent space using one specific chart, the formula for the derivative is written in terms of this specific chart. We use the names `mdifferentiable` and `mfderiv`, where the prefix letter `m` means "manifold". -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] /-- Predicate ensuring that, at a point and within a set, a function can have at most one derivative. This is expressed using the preferred chart at the considered point. -/ def unique_mdiff_within_at (s : set M) (x : M) := unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- Predicate ensuring that, at all points of a set, a function can have at most one derivative. -/ def unique_mdiff_on (s : set M) := ∀x∈s, unique_mdiff_within_at I s x /-- Conjugating a function to write it in the preferred charts around `x`. The manifold derivative of `f` will just be the derivative of this conjugated function. -/ @[simp, mfld_simps] def written_in_ext_chart_at (x : M) (f : M → M') : E → E' := (ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm /-- `mdifferentiable_within_at I I' f s x` indicates that the function `f` between manifolds has a derivative at the point `x` within the set `s`. This is a generalization of `differentiable_within_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_within_at (f : M → M') (s : set M) (x : M) := continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `mdifferentiable_at I I' f x` indicates that the function `f` between manifolds has a derivative at the point `x`. This is a generalization of `differentiable_at` to manifolds. We require continuity in the definition, as otherwise points close to `x` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def mdifferentiable_at (f : M → M') (x : M) := continuous_at f x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) (range I) ((ext_chart_at I x) x) /-- `mdifferentiable_on I I' f s` indicates that the function `f` between manifolds has a derivative within `s` at all points of `s`. This is a generalization of `differentiable_on` to manifolds. -/ def mdifferentiable_on (f : M → M') (s : set M) := ∀x ∈ s, mdifferentiable_within_at I I' f s x /-- `mdifferentiable I I' f` indicates that the function `f` between manifolds has a derivative everywhere. This is a generalization of `differentiable` to manifolds. -/ def mdifferentiable (f : M → M') := ∀x, mdifferentiable_at I I' f x /-- Prop registering if a local homeomorphism is a local diffeomorphism on its source -/ def local_homeomorph.mdifferentiable (f : local_homeomorph M M') := (mdifferentiable_on I I' f f.source) ∧ (mdifferentiable_on I' I f.symm f.target) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] /-- `has_mfderiv_within_at I I' f s x f'` indicates that the function `f` between manifolds has, at the point `x` and within the set `s`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. This is a generalization of `has_fderiv_within_at` to manifolds (as indicated by the prefix `m`). The order of arguments is changed as the type of the derivative `f'` depends on the choice of `x`. We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_within_at (f : M → M') (s : set M) (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_within_at f s x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) /-- `has_mfderiv_at I I' f x f'` indicates that the function `f` between manifolds has, at the point `x`, the derivative `f'`. Here, `f'` is a continuous linear map from the tangent space at `x` to the tangent space at `f x`. We require continuity in the definition, as otherwise points close to `x` `s` could be sent by `f` outside of the chart domain around `f x`. Then the chart could do anything to the image points, and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while this would not mean anything relevant. -/ def has_mfderiv_at (f : M → M') (x : M) (f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) := continuous_at f x ∧ has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' (range I) ((ext_chart_at I x) x) /-- Let `f` be a function between two smooth manifolds. Then `mfderiv_within I I' f s x` is the derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv_within (f : M → M') (s : set M) (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_within_at I I' f s x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) : _) else 0 /-- Let `f` be a function between two smooth manifolds. Then `mfderiv I I' f x` is the derivative of `f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at `f x`. -/ def mfderiv (f : M → M') (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) := if h : mdifferentiable_at I I' f x then (fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : E → E') (range I) ((ext_chart_at I x) x) : _) else 0 /-- The derivative within a set, as a map between the tangent bundles -/ def tangent_map_within (f : M → M') (s : set M) : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv_within I I' f s p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ /-- The derivative, as a map between the tangent bundles -/ def tangent_map (f : M → M') : tangent_bundle I M → tangent_bundle I' M' := λp, ⟨f p.1, (mfderiv I I' f p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩ end derivatives_definitions section derivatives_properties /-! ### Unique differentiability sets in manifolds -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] -- {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {f f₀ f₁ : M → M'} {x : M} {s t : set M} {g : M' → M''} {u : set M'} lemma unique_mdiff_within_at_univ : unique_mdiff_within_at I univ x := begin unfold unique_mdiff_within_at, simp only [preimage_univ, univ_inter], exact I.unique_diff _ (mem_range_self _) end variable {I} lemma unique_mdiff_within_at_iff {s : set M} {x : M} : unique_mdiff_within_at I s x ↔ unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ (ext_chart_at I x).target) ((ext_chart_at I x) x) := begin apply unique_diff_within_at_congr, rw [nhds_within_inter, nhds_within_inter, nhds_within_ext_chart_target_eq] end lemma unique_mdiff_within_at.mono (h : unique_mdiff_within_at I s x) (st : s ⊆ t) : unique_mdiff_within_at I t x := unique_diff_within_at.mono h $ inter_subset_inter (preimage_mono st) (subset.refl _) lemma unique_mdiff_within_at.inter' (hs : unique_mdiff_within_at I s x) (ht : t ∈ nhds_within x s) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter' hs (ext_chart_preimage_mem_nhds_within I x ht) end lemma unique_mdiff_within_at.inter (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝 x) : unique_mdiff_within_at I (s ∩ t) x := begin rw [unique_mdiff_within_at, ext_chart_preimage_inter_eq], exact unique_diff_within_at.inter hs (ext_chart_preimage_mem_nhds I x ht) end lemma is_open.unique_mdiff_within_at (xs : x ∈ s) (hs : is_open s) : unique_mdiff_within_at I s x := begin have := unique_mdiff_within_at.inter (unique_mdiff_within_at_univ I) (mem_nhds_sets hs xs), rwa univ_inter at this end lemma unique_mdiff_on.inter (hs : unique_mdiff_on I s) (ht : is_open t) : unique_mdiff_on I (s ∩ t) := λx hx, unique_mdiff_within_at.inter (hs _ hx.1) (mem_nhds_sets ht hx.2) lemma is_open.unique_mdiff_on (hs : is_open s) : unique_mdiff_on I s := λx hx, is_open.unique_mdiff_within_at hx hs lemma unique_mdiff_on_univ : unique_mdiff_on I (univ : set M) := is_open_univ.unique_mdiff_on /- We name the typeclass variables related to `smooth_manifold_with_corners` structure as they are necessary in lemmas mentioning the derivative, but not in lemmas about differentiability, so we want to include them or omit them when necessary. -/ variables [Is : smooth_manifold_with_corners I M] [I's : smooth_manifold_with_corners I' M'] [I''s : smooth_manifold_with_corners I'' M''] {f' f₀' f₁' : tangent_space I x →L[𝕜] tangent_space I' (f x)} {g' : tangent_space I' (f x) →L[𝕜] tangent_space I'' (g (f x))} /-- `unique_mdiff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_mdiff_within_at.eq (U : unique_mdiff_within_at I s x) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := U.eq h.2 h₁.2 theorem unique_mdiff_on.eq (U : unique_mdiff_on I s) (hx : x ∈ s) (h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') : f' = f₁' := unique_mdiff_within_at.eq (U _ hx) h h₁ /-! ### General lemmas on derivatives of functions between manifolds We mimick the API for functions between vector spaces -/ lemma mdifferentiable_within_at_iff {f : M → M'} {s : set M} {x : M} : mdifferentiable_within_at I I' f s x ↔ continuous_within_at f s x ∧ differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' s) ((ext_chart_at I x) x) := begin refine and_congr iff.rfl (exists_congr $ λ f', _), rw [inter_comm], simp only [has_fderiv_within_at, nhds_within_inter, nhds_within_ext_chart_target_eq] end include Is I's lemma mfderiv_within_zero_of_not_mdifferentiable_within_at (h : ¬ mdifferentiable_within_at I I' f s x) : mfderiv_within I I' f s x = 0 := by simp [mfderiv_within, h] lemma mfderiv_zero_of_not_mdifferentiable_at (h : ¬ mdifferentiable_at I I' f x) : mfderiv I I' f x = 0 := by simp [mfderiv, h] theorem has_mfderiv_within_at.mono (h : has_mfderiv_within_at I I' f t x f') (hst : s ⊆ t) : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_within_at.mono h.1 hst, has_fderiv_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ theorem has_mfderiv_at.has_mfderiv_within_at (h : has_mfderiv_at I I' f x f') : has_mfderiv_within_at I I' f s x f' := ⟨ continuous_at.continuous_within_at h.1, has_fderiv_within_at.mono h.2 (inter_subset_right _ _) ⟩ lemma has_mfderiv_within_at.mdifferentiable_within_at (h : has_mfderiv_within_at I I' f s x f') : mdifferentiable_within_at I I' f s x := ⟨h.1, ⟨f', h.2⟩⟩ lemma has_mfderiv_at.mdifferentiable_at (h : has_mfderiv_at I I' f x f') : mdifferentiable_at I I' f x := ⟨h.1, ⟨f', h.2⟩⟩ @[simp, mfld_simps] lemma has_mfderiv_within_at_univ : has_mfderiv_within_at I I' f univ x f' ↔ has_mfderiv_at I I' f x f' := by simp [has_mfderiv_within_at, has_mfderiv_at, continuous_within_at_univ] theorem has_mfderiv_at_unique (h₀ : has_mfderiv_at I I' f x f₀') (h₁ : has_mfderiv_at I I' f x f₁') : f₀' = f₁' := begin rw ← has_mfderiv_within_at_univ at h₀ h₁, exact (unique_mdiff_within_at_univ I).eq h₀ h₁ end lemma has_mfderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter', continuous_within_at_inter' h], exact ext_chart_preimage_mem_nhds_within I x h, end lemma has_mfderiv_within_at_inter (h : t ∈ 𝓝 x) : has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' := begin rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_preimage_inter_eq, has_fderiv_within_at_inter, continuous_within_at_inter h], exact ext_chart_preimage_mem_nhds I x h, end lemma has_mfderiv_within_at.union (hs : has_mfderiv_within_at I I' f s x f') (ht : has_mfderiv_within_at I I' f t x f') : has_mfderiv_within_at I I' f (s ∪ t) x f' := begin split, { exact continuous_within_at.union hs.1 ht.1 }, { convert has_fderiv_within_at.union hs.2 ht.2, simp [union_inter_distrib_right] } end lemma has_mfderiv_within_at.nhds_within (h : has_mfderiv_within_at I I' f s x f') (ht : s ∈ nhds_within x t) : has_mfderiv_within_at I I' f t x f' := (has_mfderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_mfderiv_within_at.has_mfderiv_at (h : has_mfderiv_within_at I I' f s x f') (hs : s ∈ 𝓝 x) : has_mfderiv_at I I' f x f' := by rwa [← univ_inter s, has_mfderiv_within_at_inter hs, has_mfderiv_within_at_univ] at h lemma mdifferentiable_within_at.has_mfderiv_within_at (h : mdifferentiable_within_at I I' f s x) : has_mfderiv_within_at I I' f s x (mfderiv_within I I' f s x) := begin refine ⟨h.1, _⟩, simp only [mfderiv_within, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_within_at.mfderiv_within (h : mdifferentiable_within_at I I' f s x) : (mfderiv_within I I' f s x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x) := by simp [mfderiv_within, h] lemma mdifferentiable_at.has_mfderiv_at (h : mdifferentiable_at I I' f x) : has_mfderiv_at I I' f x (mfderiv I I' f x) := begin refine ⟨h.1, _⟩, simp only [mfderiv, h, dif_pos] with mfld_simps, exact differentiable_within_at.has_fderiv_within_at h.2 end lemma mdifferentiable_at.mfderiv (h : mdifferentiable_at I I' f x) : (mfderiv I I' f x) = fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) (range I) ((ext_chart_at I x) x) := by simp [mfderiv, h] lemma has_mfderiv_at.mfderiv (h : has_mfderiv_at I I' f x f') : mfderiv I I' f x = f' := by { ext, rw has_mfderiv_at_unique h h.mdifferentiable_at.has_mfderiv_at } lemma has_mfderiv_within_at.mfderiv_within (h : has_mfderiv_within_at I I' f s x f') (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = f' := by { ext, rw hxs.eq h h.mdifferentiable_within_at.has_mfderiv_within_at } lemma mdifferentiable.mfderiv_within (h : mdifferentiable_at I I' f x) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' f s x = mfderiv I I' f x := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact h.has_mfderiv_at.has_mfderiv_within_at end lemma mfderiv_within_subset (st : s ⊆ t) (hs : unique_mdiff_within_at I s x) (h : mdifferentiable_within_at I I' f t x) : mfderiv_within I I' f s x = mfderiv_within I I' f t x := ((mdifferentiable_within_at.has_mfderiv_within_at h).mono st).mfderiv_within hs omit Is I's lemma mdifferentiable_within_at.mono (hst : s ⊆ t) (h : mdifferentiable_within_at I I' f t x) : mdifferentiable_within_at I I' f s x := ⟨ continuous_within_at.mono h.1 hst, differentiable_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩ lemma mdifferentiable_within_at_univ : mdifferentiable_within_at I I' f univ x ↔ mdifferentiable_at I I' f x := by simp [mdifferentiable_within_at, mdifferentiable_at, continuous_within_at_univ] lemma mdifferentiable_within_at_inter (ht : t ∈ 𝓝 x) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter, continuous_within_at_inter ht], exact ext_chart_preimage_mem_nhds I x ht end lemma mdifferentiable_within_at_inter' (ht : t ∈ nhds_within x s) : mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x := begin rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_preimage_inter_eq, differentiable_within_at_inter', continuous_within_at_inter' ht], exact ext_chart_preimage_mem_nhds_within I x ht end lemma mdifferentiable_at.mdifferentiable_within_at (h : mdifferentiable_at I I' f x) : mdifferentiable_within_at I I' f s x := mdifferentiable_within_at.mono (subset_univ _) (mdifferentiable_within_at_univ.2 h) lemma mdifferentiable_within_at.mdifferentiable_at (h : mdifferentiable_within_at I I' f s x) (hs : s ∈ 𝓝 x) : mdifferentiable_at I I' f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, mdifferentiable_within_at_inter hs, mdifferentiable_within_at_univ] at h, end lemma mdifferentiable_on.mono (h : mdifferentiable_on I I' f t) (st : s ⊆ t) : mdifferentiable_on I I' f s := λx hx, (h x (st hx)).mono st lemma mdifferentiable_on_univ : mdifferentiable_on I I' f univ ↔ mdifferentiable I I' f := by { simp only [mdifferentiable_on, mdifferentiable_within_at_univ] with mfld_simps, refl } lemma mdifferentiable.mdifferentiable_on (h : mdifferentiable I I' f) : mdifferentiable_on I I' f s := (mdifferentiable_on_univ.2 h).mono (subset_univ _) lemma mdifferentiable_on_of_locally_mdifferentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ mdifferentiable_on I I' f (s ∩ u)) : mdifferentiable_on I I' f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (mdifferentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end include Is I's @[simp, mfld_simps] lemma mfderiv_within_univ : mfderiv_within I I' f univ = mfderiv I I' f := begin ext x : 1, simp only [mfderiv_within, mfderiv] with mfld_simps, rw mdifferentiable_within_at_univ end lemma mfderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_mdiff_within_at I s x) : mfderiv_within I I' f (s ∩ t) x = mfderiv_within I I' f s x := by rw [mfderiv_within, mfderiv_within, ext_chart_preimage_inter_eq, mdifferentiable_within_at_inter ht, fderiv_within_inter (ext_chart_preimage_mem_nhds I x ht) hs] omit Is I's /-! ### Deriving continuity from differentiability on manifolds -/ theorem has_mfderiv_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) : continuous_within_at f s x := h.1 theorem has_mfderiv_at.continuous_at (h : has_mfderiv_at I I' f x f') : continuous_at f x := h.1 lemma mdifferentiable_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) : continuous_within_at f s x := h.1 lemma mdifferentiable_at.continuous_at (h : mdifferentiable_at I I' f x) : continuous_at f x := h.1 lemma mdifferentiable_on.continuous_on (h : mdifferentiable_on I I' f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma mdifferentiable.continuous (h : mdifferentiable I I' f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at include Is I's lemma tangent_map_within_subset {p : tangent_bundle I M} (st : s ⊆ t) (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_within_at I I' f t p.1) : tangent_map_within I I' f s p = tangent_map_within I I' f t p := by { simp only [tangent_map_within], rw mfderiv_within_subset st hs h } lemma tangent_map_within_univ : tangent_map_within I I' f univ = tangent_map I I' f := by { ext p : 1, simp only [tangent_map_within, tangent_map] with mfld_simps } lemma tangent_map_within_eq_tangent_map {p : tangent_bundle I M} (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_at I I' f p.1) : tangent_map_within I I' f s p = tangent_map I I' f p := begin rw ← mdifferentiable_within_at_univ at h, rw ← tangent_map_within_univ, exact tangent_map_within_subset (subset_univ _) hs h, end @[simp, mfld_simps] lemma tangent_map_within_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map_within I I' f s p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_within_proj {p : tangent_bundle I M} : (tangent_map_within I I' f s p).1 = f p.1 := rfl @[simp, mfld_simps] lemma tangent_map_tangent_bundle_proj {p : tangent_bundle I M} : tangent_bundle.proj I' M' (tangent_map I I' f p) = f (tangent_bundle.proj I M p) := rfl @[simp, mfld_simps] lemma tangent_map_proj {p : tangent_bundle I M} : (tangent_map I I' f p).1 = f p.1 := rfl omit Is I's /-! ### Congruence lemmas for derivatives on manifolds -/ lemma has_mfderiv_within_at.congr_of_eventually_eq (h : has_mfderiv_within_at I I' f s x f') (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : has_mfderiv_within_at I I' f₁ s x f' := begin refine ⟨continuous_within_at.congr_of_eventually_eq h.1 h₁ hx, _⟩, apply has_fderiv_within_at.congr_of_eventually_eq h.2, { have : (ext_chart_at I x).symm ⁻¹' {y | f₁ y = f y} ∈ nhds_within ((ext_chart_at I x) x) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) := ext_chart_preimage_mem_nhds_within I x h₁, apply filter.mem_sets_of_superset this (λy, _), simp only [hx] with mfld_simps {contextual := tt} }, { simp only [hx] with mfld_simps }, end lemma has_mfderiv_within_at.congr_mono (h : has_mfderiv_within_at I I' f s x f') (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_mfderiv_within_at I I' f₁ t x f' := (h.mono h₁).congr_of_eventually_eq (filter.mem_inf_sets_of_right ht) hx lemma has_mfderiv_at.congr_of_eventually_eq (h : has_mfderiv_at I I' f x f') (h₁ : f₁ =ᶠ[𝓝 x] f) : has_mfderiv_at I I' f₁ x f' := begin rw ← has_mfderiv_within_at_univ at ⊢ h, apply h.congr_of_eventually_eq _ (mem_of_nhds h₁ : _), rwa nhds_within_univ end include Is I's lemma mdifferentiable_within_at.congr_of_eventually_eq (h : mdifferentiable_within_at I I' f s x) (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (h.has_mfderiv_within_at.congr_of_eventually_eq h₁ hx).mdifferentiable_within_at variables (I I') lemma filter.eventually_eq.mdifferentiable_within_at_iff (h₁ : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f s x ↔ mdifferentiable_within_at I I' f₁ s x := begin split, { assume h, apply h.congr_of_eventually_eq h₁ hx }, { assume h, apply h.congr_of_eventually_eq _ hx.symm, apply h₁.mono, intro y, apply eq.symm } end variables {I I'} lemma mdifferentiable_within_at.congr_mono (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_within_at I I' f₁ t x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx h₁).mdifferentiable_within_at lemma mdifferentiable_within_at.congr (h : mdifferentiable_within_at I I' f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx (subset.refl _)).mdifferentiable_within_at lemma mdifferentiable_on.congr_mono (h : mdifferentiable_on I I' f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : mdifferentiable_on I I' f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma mdifferentiable_at.congr_of_eventually_eq (h : mdifferentiable_at I I' f x) (hL : f₁ =ᶠ[𝓝 x] f) : mdifferentiable_at I I' f₁ x := ((h.has_mfderiv_at).congr_of_eventually_eq hL).mdifferentiable_at lemma mdifferentiable_within_at.mfderiv_within_congr_mono (h : mdifferentiable_within_at I I' f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_mdiff_within_at I t x) (h₁ : t ⊆ s) : mfderiv_within I I' f₁ t x = (mfderiv_within I I' f s x : _) := (has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at hs hx h₁).mfderiv_within hxt lemma filter.eventually_eq.mfderiv_within_eq (hs : unique_mdiff_within_at I s x) (hL : f₁ =ᶠ[nhds_within x s] f) (hx : f₁ x = f x) : mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) := begin by_cases h : mdifferentiable_within_at I I' f s x, { exact ((h.has_mfderiv_within_at).congr_of_eventually_eq hL hx).mfderiv_within hs }, { unfold mfderiv_within, rw [dif_neg h, dif_neg], rwa ← hL.mdifferentiable_within_at_iff I I' hx } end lemma filter.eventually_eq.mfderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : mfderiv I I' f₁ x = (mfderiv I I' f x : _) := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← mfderiv_within_univ, ← mfderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.mfderiv_within_eq (unique_mdiff_within_at_univ I) A end /-! ### Composition lemmas -/ omit Is I's lemma written_in_ext_chart_comp (h : continuous_within_at f s x) : {y | written_in_ext_chart_at I I'' x (g ∘ f) y = ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) y} ∈ nhds_within ((ext_chart_at I x) x) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) := begin apply @filter.mem_sets_of_superset _ _ ((f ∘ (ext_chart_at I x).symm)⁻¹' (ext_chart_at I' (f x)).source) _ (ext_chart_preimage_mem_nhds_within I x (h.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), assume y hy, simp only with mfld_simps, rw (chart_at H' (f x)).left_inv, simpa only [] with mfld_simps using hy end variable (x) include Is I's I''s theorem has_mfderiv_within_at.comp (hg : has_mfderiv_within_at I' I'' g u (f x) g') (hf : has_mfderiv_within_at I I' f s x f') (hst : s ⊆ f ⁻¹' u) : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin refine ⟨continuous_within_at.comp hg.1 hf.1 hst, _⟩, have A : has_fderiv_within_at ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) (continuous_linear_map.comp g' f' : E →L[𝕜] E'') ((ext_chart_at I x).symm ⁻¹' s ∩ range (I)) ((ext_chart_at I x) x), { have : (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' (f x)).source) ∈ nhds_within ((ext_chart_at I x) x) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) := (ext_chart_preimage_mem_nhds_within I x (hf.1.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))), unfold has_mfderiv_within_at at *, rw [← has_fderiv_within_at_inter' this, ← ext_chart_preimage_inter_eq] at hf ⊢, have : written_in_ext_chart_at I I' x f ((ext_chart_at I x) x) = (ext_chart_at I' (f x)) (f x), by simp only with mfld_simps, rw ← this at hg, apply has_fderiv_within_at.comp ((ext_chart_at I x) x) hg.2 hf.2 _, assume y hy, simp only with mfld_simps at hy, have : f (((chart_at H x).symm : H → M) (I.symm y)) ∈ u := hst hy.1.1, simp only [hy, this] with mfld_simps }, apply A.congr_of_eventually_eq (written_in_ext_chart_comp hf.1), simp only with mfld_simps end /-- The chain rule. -/ theorem has_mfderiv_at.comp (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_at I I' f x f') : has_mfderiv_at I I'' (g ∘ f) x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end theorem has_mfderiv_at.comp_has_mfderiv_within_at (hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_within_at I I' f s x f') : has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') := begin rw ← has_mfderiv_within_at_univ at *, exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ end lemma mdifferentiable_within_at.comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) : mdifferentiable_within_at I I'' (g ∘ f) s x := begin rcases hf.2 with ⟨f', hf'⟩, have F : has_mfderiv_within_at I I' f s x f' := ⟨hf.1, hf'⟩, rcases hg.2 with ⟨g', hg'⟩, have G : has_mfderiv_within_at I' I'' g u (f x) g' := ⟨hg.1, hg'⟩, exact (has_mfderiv_within_at.comp x G F h).mdifferentiable_within_at end lemma mdifferentiable_at.comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mdifferentiable_at I I'' (g ∘ f) x := (hg.has_mfderiv_at.comp x hf.has_mfderiv_at).mdifferentiable_at lemma mfderiv_within_comp (hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x) (h : s ⊆ f ⁻¹' u) (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I'' (g ∘ f) s x = (mfderiv_within I' I'' g u (f x)).comp (mfderiv_within I I' f s x) := begin apply has_mfderiv_within_at.mfderiv_within _ hxs, exact has_mfderiv_within_at.comp x hg.has_mfderiv_within_at hf.has_mfderiv_within_at h end lemma mfderiv_comp (hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) : mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) := begin apply has_mfderiv_at.mfderiv, exact has_mfderiv_at.comp x hg.has_mfderiv_at hf.has_mfderiv_at end lemma mdifferentiable_on.comp (hg : mdifferentiable_on I' I'' g u) (hf : mdifferentiable_on I I' f s) (st : s ⊆ f ⁻¹' u) : mdifferentiable_on I I'' (g ∘ f) s := λx hx, mdifferentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma mdifferentiable.comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : mdifferentiable I I'' (g ∘ f) := λx, mdifferentiable_at.comp x (hg (f x)) (hf x) lemma tangent_map_within_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_within_at I' I'' g u (f p.1)) (hf : mdifferentiable_within_at I I' f s p.1) (h : s ⊆ f ⁻¹' u) (hps : unique_mdiff_within_at I s p.1) : tangent_map_within I I'' (g ∘ f) s p = tangent_map_within I' I'' g u (tangent_map_within I I' f s p) := begin simp only [tangent_map_within], rw mfderiv_within_comp p.1 hg hf h hps, refl end lemma tangent_map_comp_at (p : tangent_bundle I M) (hg : mdifferentiable_at I' I'' g (f p.1)) (hf : mdifferentiable_at I I' f p.1) : tangent_map I I'' (g ∘ f) p = tangent_map I' I'' g (tangent_map I I' f p) := begin rcases p with ⟨x, v⟩, simp only [tangent_map], rw mfderiv_comp x hg hf, refl end lemma tangent_map_comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : tangent_map I I'' (g ∘ f) = (tangent_map I' I'' g) ∘ (tangent_map I I' f) := by { ext p : 1, exact tangent_map_comp_at _ (hg _) (hf _) } end derivatives_properties section specific_functions /-! ### Differentiability of specific functions -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {s : set M} {x : M} section id /-! #### Identity -/ lemma has_mfderiv_at_id (x : M) : has_mfderiv_at I I (@_root_.id M) x (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin refine ⟨continuous_id.continuous_at, _⟩, have : ∀ᶠ y in nhds_within ((ext_chart_at I x) x) (range (I)), ((ext_chart_at I x) ∘ (ext_chart_at I x).symm) y = id y, { apply filter.mem_sets_of_superset (ext_chart_at_target_mem_nhds_within I x), assume y hy, simp only [-ext_chart_at, hy] with mfld_simps }, apply has_fderiv_within_at.congr_of_eventually_eq (has_fderiv_within_at_id _ _) this, simp only with mfld_simps end theorem has_mfderiv_within_at_id (s : set M) (x : M) : has_mfderiv_within_at I I (@_root_.id M) s x (continuous_linear_map.id 𝕜 (tangent_space I x)) := (has_mfderiv_at_id I x).has_mfderiv_within_at lemma mdifferentiable_at_id : mdifferentiable_at I I (@_root_.id M) x := (has_mfderiv_at_id I x).mdifferentiable_at lemma mdifferentiable_within_at_id : mdifferentiable_within_at I I (@_root_.id M) s x := (mdifferentiable_at_id I).mdifferentiable_within_at lemma mdifferentiable_id : mdifferentiable I I (@_root_.id M) := λx, mdifferentiable_at_id I lemma mdifferentiable_on_id : mdifferentiable_on I I (@_root_.id M) s := (mdifferentiable_id I).mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_id : mfderiv I I (@_root_.id M) x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := has_mfderiv_at.mfderiv (has_mfderiv_at_id I x) lemma mfderiv_within_id (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I (@_root_.id M) s x = (continuous_linear_map.id 𝕜 (tangent_space I x)) := begin rw mdifferentiable.mfderiv_within (mdifferentiable_at_id I) hxs, exact mfderiv_id I end end id section const /-! #### Constants -/ variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M'] {c : M'} lemma has_mfderiv_at_const (c : M') (x : M) : has_mfderiv_at I I' (λy : M, c) x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := begin refine ⟨continuous_const.continuous_at, _⟩, have : (ext_chart_at I' c) ∘ (λ (y : M), c) ∘ (ext_chart_at I x).symm = (λy, (ext_chart_at I' c) c) := rfl, rw [written_in_ext_chart_at, this], apply has_fderiv_within_at_const end theorem has_mfderiv_within_at_const (c : M') (s : set M) (x : M) : has_mfderiv_within_at I I' (λy : M, c) s x (0 : tangent_space I x →L[𝕜] tangent_space I' c) := (has_mfderiv_at_const I I' c x).has_mfderiv_within_at lemma mdifferentiable_at_const : mdifferentiable_at I I' (λy : M, c) x := (has_mfderiv_at_const I I' c x).mdifferentiable_at lemma mdifferentiable_within_at_const : mdifferentiable_within_at I I' (λy : M, c) s x := (mdifferentiable_at_const I I').mdifferentiable_within_at lemma mdifferentiable_const : mdifferentiable I I' (λy : M, c) := λx, mdifferentiable_at_const I I' lemma mdifferentiable_on_const : mdifferentiable_on I I' (λy : M, c) s := (mdifferentiable_const I I').mdifferentiable_on @[simp, mfld_simps] lemma mfderiv_const : mfderiv I I' (λy : M, c) x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := has_mfderiv_at.mfderiv (has_mfderiv_at_const I I' c x) lemma mfderiv_within_const (hxs : unique_mdiff_within_at I s x) : mfderiv_within I I' (λy : M, c) s x = (0 : tangent_space I x →L[𝕜] tangent_space I' c) := begin rw mdifferentiable.mfderiv_within (mdifferentiable_at_const I I') hxs, { exact mfderiv_const I I' }, { apply_instance } end end const section model_with_corners /-! #### Model with corners -/ lemma model_with_corners.mdifferentiable : mdifferentiable I (model_with_corners_self 𝕜 E) I := begin simp only [mdifferentiable, mdifferentiable_at] with mfld_simps, assume x, refine ⟨I.continuous.continuous_at, _⟩, have : differentiable_within_at 𝕜 id (range I) (I x) := differentiable_at_id.differentiable_within_at, apply this.congr, { simp only with mfld_simps {contextual := tt} }, { simp only with mfld_simps } end lemma model_with_corners.mdifferentiable_on_symm : mdifferentiable_on (model_with_corners_self 𝕜 E) I I.symm (range I) := begin simp only [mdifferentiable_on, mdifferentiable_within_at] with mfld_simps, assume x hx, refine ⟨I.continuous_symm.continuous_at.continuous_within_at, _⟩, have : differentiable_within_at 𝕜 id (range I) x := differentiable_at_id.differentiable_within_at, apply this.congr, { simp only with mfld_simps {contextual := tt} }, { simp only [hx] with mfld_simps } end end model_with_corners section charts variable {e : local_homeomorph M H} lemma mdifferentiable_at_atlas (h : e ∈ atlas H M) {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I e x := begin refine ⟨(e.continuous_on x hx).continuous_at (mem_nhds_sets e.open_source hx), _⟩, have mem : I ((chart_at H x : M → H) x) ∈ I.symm ⁻¹' ((chart_at H x).symm ≫ₕ e).source ∩ range I, by simp only [hx] with mfld_simps, have : (chart_at H x).symm.trans e ∈ times_cont_diff_groupoid ⊤ I := has_groupoid.compatible _ (chart_mem_atlas H x) h, have A : times_cont_diff_on 𝕜 ⊤ (I ∘ ((chart_at H x).symm.trans e) ∘ I.symm) (I.symm ⁻¹' ((chart_at H x).symm.trans e).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I ((chart_at H x : M → H) x)) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only [] with mfld_simps }, { apply mem_nhds_sets (I.continuous_symm _ (local_homeomorph.open_source _)) mem.1 } end lemma mdifferentiable_on_atlas (h : e ∈ atlas H M) : mdifferentiable_on I I e e.source := λx hx, (mdifferentiable_at_atlas I h hx).mdifferentiable_within_at lemma mdifferentiable_at_atlas_symm (h : e ∈ atlas H M) {x : H} (hx : x ∈ e.target) : mdifferentiable_at I I e.symm x := begin refine ⟨(e.continuous_on_symm x hx).continuous_at (mem_nhds_sets e.open_target hx), _⟩, have mem : I x ∈ I.symm ⁻¹' (e.symm ≫ₕ chart_at H (e.symm x)).source ∩ range (I), by simp only [hx] with mfld_simps, have : e.symm.trans (chart_at H (e.symm x)) ∈ times_cont_diff_groupoid ⊤ I := has_groupoid.compatible _ h (chart_mem_atlas H _), have A : times_cont_diff_on 𝕜 ⊤ (I ∘ (e.symm.trans (chart_at H (e.symm x))) ∘ I.symm) (I.symm ⁻¹' (e.symm.trans (chart_at H (e.symm x))).source ∩ range I) := this.1, have B := A.differentiable_on le_top (I x) mem, simp only with mfld_simps at B, rw [inter_comm, differentiable_within_at_inter] at B, { simpa only [] with mfld_simps }, { apply (mem_nhds_sets (I.continuous_symm _ (local_homeomorph.open_source _)) mem.1) } end lemma mdifferentiable_on_atlas_symm (h : e ∈ atlas H M) : mdifferentiable_on I I e.symm e.target := λx hx, (mdifferentiable_at_atlas_symm I h hx).mdifferentiable_within_at lemma mdifferentiable_of_mem_atlas (h : e ∈ atlas H M) : e.mdifferentiable I I := ⟨mdifferentiable_on_atlas I h, mdifferentiable_on_atlas_symm I h⟩ lemma mdifferentiable_chart (x : M) : (chart_at H x).mdifferentiable I I := mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _) /-- The derivative of the chart at a base point is the chart of the tangent bundle. -/ lemma tangent_map_chart {p q : tangent_bundle I M} (h : q.1 ∈ (chart_at H p.1).source) : tangent_map I I (chart_at H p.1) q = (chart_at (model_prod H E) p : tangent_bundle I M → model_prod H E) q := begin dsimp [tangent_map], rw mdifferentiable_at.mfderiv, { refl }, { exact mdifferentiable_at_atlas _ (chart_mem_atlas _ _) h } end /-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the tangent bundle. -/ lemma tangent_map_chart_symm {p : tangent_bundle I M} {q : model_prod H E} (h : q.1 ∈ (chart_at H p.1).target) : tangent_map I I (chart_at H p.1).symm q = ((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I M) q := begin dsimp only [tangent_map], rw mdifferentiable_at.mfderiv (mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) h), -- a trivial instance is needed after the rewrite, handle it right now. rotate, { apply_instance }, simp only [chart_at, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, basic_smooth_bundle_core.to_topological_fiber_bundle_core, topological_fiber_bundle_core.local_triv', tangent_bundle_core, h] with mfld_simps end end charts end specific_functions section mfderiv_fderiv /-! ### Relations between vector space derivative and manifold derivative The manifold derivative `mfderiv`, when considered on the model vector space with its trivial manifold structure, coincides with the usual Frechet derivative `fderiv`. In this section, we prove this and related statements. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {f : E → E'} {s : set E} {x : E} lemma unique_mdiff_within_at_iff_unique_diff_within_at : unique_mdiff_within_at (model_with_corners_self 𝕜 E) s x ↔ unique_diff_within_at 𝕜 s x := by simp [unique_mdiff_within_at] lemma unique_mdiff_on_iff_unique_diff_on : unique_mdiff_on (model_with_corners_self 𝕜 E) s ↔ unique_diff_on 𝕜 s := by simp [unique_mdiff_on, unique_diff_on, unique_mdiff_within_at_iff_unique_diff_within_at] @[simp, mfld_simps] lemma written_in_ext_chart_model_space : written_in_ext_chart_at (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') x f = f := by { ext y, simp only with mfld_simps } /-- For maps between vector spaces, `mdifferentiable_within_at` and `fdifferentiable_within_at` coincide -/ theorem mdifferentiable_within_at_iff_differentiable_within_at : mdifferentiable_within_at (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f s x ↔ differentiable_within_at 𝕜 f s x := begin simp only [mdifferentiable_within_at] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_within_at, H⟩⟩ end /-- For maps between vector spaces, `mdifferentiable_at` and `differentiable_at` coincide -/ theorem mdifferentiable_at_iff_differentiable_at : mdifferentiable_at (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f x ↔ differentiable_at 𝕜 f x := begin simp only [mdifferentiable_at, differentiable_within_at_univ] with mfld_simps, exact ⟨λH, H.2, λH, ⟨H.continuous_at, H⟩⟩ end /-- For maps between vector spaces, `mdifferentiable_on` and `differentiable_on` coincide -/ theorem mdifferentiable_on_iff_differentiable_on : mdifferentiable_on (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f s ↔ differentiable_on 𝕜 f s := by simp only [mdifferentiable_on, differentiable_on, mdifferentiable_within_at_iff_differentiable_within_at] /-- For maps between vector spaces, `mdifferentiable` and `differentiable` coincide -/ theorem mdifferentiable_iff_differentiable : mdifferentiable (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f ↔ differentiable 𝕜 f := by simp only [mdifferentiable, differentiable, mdifferentiable_at_iff_differentiable_at] /-- For maps between vector spaces, `mfderiv_within` and `fderiv_within` coincide -/ theorem mfderiv_within_eq_fderiv_within : mfderiv_within (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f s x = fderiv_within 𝕜 f s x := begin by_cases h : mdifferentiable_within_at (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f s x, { simp only [mfderiv_within, h, dif_pos] with mfld_simps }, { simp only [mfderiv_within, h, dif_neg, not_false_iff], rw [mdifferentiable_within_at_iff_differentiable_within_at, differentiable_within_at] at h, change ¬(∃(f' : tangent_space (model_with_corners_self 𝕜 E) x →L[𝕜] tangent_space (model_with_corners_self 𝕜 E') (f x)), has_fderiv_within_at f f' s x) at h, simp only [fderiv_within, h, dif_neg, not_false_iff] } end /-- For maps between vector spaces, `mfderiv` and `fderiv` coincide -/ theorem mfderiv_eq_fderiv : mfderiv (model_with_corners_self 𝕜 E) (model_with_corners_self 𝕜 E') f x = fderiv 𝕜 f x := begin rw [← mfderiv_within_univ, ← fderiv_within_univ], exact mfderiv_within_eq_fderiv_within end end mfderiv_fderiv /-! ### Differentiable local homeomorphisms -/ namespace local_homeomorph.mdifferentiable variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] {e : local_homeomorph M M'} (he : e.mdifferentiable I I') {e' : local_homeomorph M' M''} include he lemma symm : e.symm.mdifferentiable I' I := ⟨he.2, he.1⟩ protected lemma mdifferentiable_at {x : M} (hx : x ∈ e.source) : mdifferentiable_at I I' e x := (he.1 x hx).mdifferentiable_at (mem_nhds_sets e.open_source hx) lemma mdifferentiable_at_symm {x : M'} (hx : x ∈ e.target) : mdifferentiable_at I' I e.symm x := (he.2 x hx).mdifferentiable_at (mem_nhds_sets e.open_target hx) variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M'] [smooth_manifold_with_corners I'' M''] lemma symm_comp_deriv {x : M} (hx : x ∈ e.source) : (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) = continuous_linear_map.id 𝕜 (tangent_space I x) := begin have : (mfderiv I I (e.symm ∘ e) x) = (mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) := mfderiv_comp x (he.mdifferentiable_at_symm (e.map_source hx)) (he.mdifferentiable_at hx), rw ← this, have : mfderiv I I (_root_.id : M → M) x = continuous_linear_map.id _ _ := mfderiv_id I, rw ← this, apply filter.eventually_eq.mfderiv_eq, have : e.source ∈ 𝓝 x := mem_nhds_sets e.open_source hx, apply filter.mem_sets_of_superset this, assume p hp, simp only [hp] with mfld_simps end lemma comp_symm_deriv {x : M'} (hx : x ∈ e.target) : (mfderiv I I' e (e.symm x)).comp (mfderiv I' I e.symm x) = continuous_linear_map.id 𝕜 (tangent_space I' x) := he.symm.symm_comp_deriv hx /-- The derivative of a differentiable local homeomorphism, as a continuous linear equivalence between the tangent spaces at `x` and `e x`. -/ protected def mfderiv {x : M} (hx : x ∈ e.source) : tangent_space I x ≃L[𝕜] tangent_space I' (e x) := { inv_fun := (mfderiv I' I e.symm (e x)), continuous_to_fun := (mfderiv I I' e x).cont, continuous_inv_fun := (mfderiv I' I e.symm (e x)).cont, left_inv := λy, begin have : (continuous_linear_map.id _ _ : tangent_space I x →L[𝕜] tangent_space I x) y = y := rfl, conv_rhs { rw [← this, ← he.symm_comp_deriv hx] }, refl end, right_inv := λy, begin have : (continuous_linear_map.id 𝕜 _ : tangent_space I' (e x) →L[𝕜] tangent_space I' (e x)) y = y := rfl, conv_rhs { rw [← this, ← he.comp_symm_deriv (e.map_source hx)] }, rw e.left_inv hx, refl end, .. mfderiv I I' e x } lemma range_mfderiv_eq_univ {x : M} (hx : x ∈ e.source) : range (mfderiv I I' e x) = univ := (he.mfderiv hx).to_linear_equiv.to_equiv.range_eq_univ lemma trans (he': e'.mdifferentiable I' I'') : (e.trans e').mdifferentiable I I'' := begin split, { assume x hx, simp only with mfld_simps at hx, exact ((he'.mdifferentiable_at hx.2).comp _ (he.mdifferentiable_at hx.1)).mdifferentiable_within_at }, { assume x hx, simp only with mfld_simps at hx, exact ((he.symm.mdifferentiable_at hx.2).comp _ (he'.symm.mdifferentiable_at hx.1)).mdifferentiable_within_at } end end local_homeomorph.mdifferentiable /-! ### Unique derivative sets in manifolds -/ section unique_mdiff variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} {M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] {s : set M} /-- If a set has the unique differential property, then its image under a local diffeomorphism also has the unique differential property. -/ lemma unique_mdiff_on.unique_mdiff_on_preimage [smooth_manifold_with_corners I' M'] (hs : unique_mdiff_on I s) {e : local_homeomorph M M'} (he : e.mdifferentiable I I') : unique_mdiff_on I' (e.target ∩ e.symm ⁻¹' s) := begin /- Start from a point `x` in the image, and let `z` be its preimage. Then the unique derivative property at `x` is expressed through `ext_chart_at I' x`, and the unique derivative property at `z` is expressed through `ext_chart_at I z`. We will argue that the composition of these two charts with `e` is a local diffeomorphism in vector spaces, and therefore preserves the unique differential property thanks to lemma `has_fderiv_within_at.unique_diff_within_at`, saying that a differentiable function with onto derivative preserves the unique derivative property.-/ assume x hx, let z := e.symm x, have z_source : z ∈ e.source, by simp only [hx.1] with mfld_simps, have zx : e z = x, by simp only [z, hx.1] with mfld_simps, let F := ext_chart_at I z, -- the unique derivative property at `z` is expressed through its preferred chart, that we call `F`. have B : unique_diff_within_at 𝕜 (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z), { have : unique_mdiff_within_at I s z := hs _ hx.2, have S : e.source ∩ e ⁻¹' ((ext_chart_at I' x).source) ∈ 𝓝 z, { apply mem_nhds_sets, apply e.continuous_on.preimage_open_of_open e.open_source (ext_chart_at_open_source I' x), simp only [z_source, zx] with mfld_simps }, have := this.inter S, rw [unique_mdiff_within_at_iff] at this, exact this }, -- denote by `G` the change of coordinate, i.e., the composition of the two extended charts and -- of `e` let G := F.symm ≫ e.to_local_equiv ≫ (ext_chart_at I' x), -- `G` is differentiable have Diff : ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).mdifferentiable I I', { have A := mdifferentiable_of_mem_atlas I (chart_mem_atlas H z), have B := mdifferentiable_of_mem_atlas I' (chart_mem_atlas H' x), exact A.symm.trans (he.trans B) }, have Mmem : (chart_at H z : M → H) z ∈ ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).source, by simp only [z_source, zx] with mfld_simps, have A : differentiable_within_at 𝕜 G (range I) (F z), { refine (Diff.mdifferentiable_at Mmem).2.congr (λp hp, _) _; simp only [G, F] with mfld_simps }, -- let `G'` be its derivative let G' := fderiv_within 𝕜 G (range I) (F z), have D₁ : has_fderiv_within_at G G' (range I) (F z) := A.has_fderiv_within_at, have D₂ : has_fderiv_within_at G G' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z), { apply D₁.mono, refine subset.trans (inter_subset_right _ _) _, simp only [F] with mfld_simps }, -- The derivative `G'` is onto, as it is the derivative of a local diffeomorphism, the composition -- of the two charts and of `e`. have C₁ : range (G' : E → E') = univ, { have : G' = mfderiv I I' ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)) ((chart_at H z : M → H) z), by { rw (Diff.mdifferentiable_at Mmem).mfderiv, refl }, rw this, exact Diff.range_mfderiv_eq_univ Mmem }, have C₂ : closure (range (G' : E → E')) = univ, by rw [C₁, closure_univ], -- key step: thanks to what we have proved about it, `G` preserves the unique derivative property have key : unique_diff_within_at 𝕜 (G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target)) (G (F z)) := D₂.unique_diff_within_at B C₂, have : G (F z) = (ext_chart_at I' x) x, by { dsimp [G, F], simp only [hx.1] with mfld_simps }, rw this at key, apply key.mono, show G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) ⊆ (ext_chart_at I' x).symm ⁻¹' e.target ∩ (ext_chart_at I' x).symm ⁻¹' (e.symm ⁻¹' s) ∩ range (I'), rw image_subset_iff, rintros p ⟨⟨hp₁, ⟨hp₂, hp₄⟩⟩, hp₃⟩, simp only [G, hp₂, hp₁, mem_preimage.1 hp₄, -ext_chart_at] with mfld_simps, exact mem_range_self _ end /-- If a set in a manifold has the unique derivative property, then its pullback by any extended chart, in the vector space, also has the unique derivative property. -/ lemma unique_mdiff_on.unique_diff_on (hs : unique_mdiff_on I s) (x : M) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' s)) := begin -- this is just a reformulation of `unique_mdiff_on.unique_mdiff_on_preimage`, using as `e` -- the local chart at `x`. assume z hz, simp only with mfld_simps at hz, have : (chart_at H x).mdifferentiable I I := mdifferentiable_chart _ _, have T := (hs.unique_mdiff_on_preimage this) (I.symm z), simp only [hz.left.left, hz.left.right, hz.right, unique_mdiff_within_at] with mfld_simps at ⊢ T, convert T using 1, rw @preimage_comp _ _ _ _ (chart_at H x).symm, -- it remains to show that `(a ∩ b) ∩ c` = `(b ∩ c) ∩ a`, which finish can do but very slowly ext p, split; { assume hp, simp only with mfld_simps at hp, simp only [hp] with mfld_simps } end /-- When considering functions between manifolds, this statement shows up often. It entails the unique differential of the pullback in extended charts of the set where the function can be read in the charts. -/ lemma unique_mdiff_on.unique_diff_on_inter_preimage (hs : unique_mdiff_on I s) (x : M) (y : M') {f : M → M'} (hf : continuous_on f s) : unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' (s ∩ f⁻¹' (ext_chart_at I' y).source))) := begin have : unique_mdiff_on I (s ∩ f ⁻¹' (ext_chart_at I' y).source), { assume z hz, apply (hs z hz.1).inter', apply (hf z hz.1).preimage_mem_nhds_within, exact mem_nhds_sets (ext_chart_at_open_source I' y) hz.2 }, exact this.unique_diff_on _ end variables {F : Type*} [normed_group F] [normed_space 𝕜 F] (Z : basic_smooth_bundle_core I M F) /-- In a smooth fiber bundle constructed from core, the preimage under the projection of a set with unique differential in the basis also has unique differential. -/ lemma unique_mdiff_on.smooth_bundle_preimage (hs : unique_mdiff_on I s) : unique_mdiff_on (I.prod (model_with_corners_self 𝕜 F)) (Z.to_topological_fiber_bundle_core.proj ⁻¹' s) := begin /- Using a chart (and the fact that unique differentiability is invariant under charts), we reduce the situation to the model space, where we can use the fact that products respect unique differentiability. -/ assume p hp, replace hp : p.fst ∈ s, by simpa only [] with mfld_simps using hp, let e₀ := chart_at H p.1, let e := chart_at (model_prod H F) p, -- It suffices to prove unique differentiability in a chart suffices h : unique_mdiff_on (I.prod (model_with_corners_self 𝕜 F)) (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), { have A : unique_mdiff_on (I.prod (model_with_corners_self 𝕜 F)) (e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s))), { apply h.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)).symm, apply_instance }, have : p ∈ e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (Z.to_topological_fiber_bundle_core.proj ⁻¹' s)), by simp only [e, hp] with mfld_simps, apply (A _ this).mono, assume q hq, simp only [e, local_homeomorph.left_inv _ hq.1] with mfld_simps at hq, simp only [hq] with mfld_simps }, -- rewrite the relevant set in the chart as a direct product have : (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' e.target ∩ (λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' (e.symm ⁻¹' (prod.fst ⁻¹' s)) ∩ ((range I).prod univ) = set.prod (I.symm ⁻¹' (e₀.target ∩ e₀.symm⁻¹' s) ∩ range I) univ, { ext q, split; { assume hq, simp only with mfld_simps at hq, simp only [hq] with mfld_simps } }, assume q hq, replace hq : q.1 ∈ (chart_at H p.1).target ∧ ((chart_at H p.1).symm : H → M) q.1 ∈ s, by simpa only [] with mfld_simps using hq, simp only [unique_mdiff_within_at, model_with_corners.prod, preimage_inter, this] with mfld_simps, -- apply unique differentiability of products to conclude apply unique_diff_on.prod _ unique_diff_on_univ, { simp only [hq] with mfld_simps }, { assume x hx, have A : unique_mdiff_on I (e₀.target ∩ e₀.symm⁻¹' s), { apply hs.unique_mdiff_on_preimage, exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)), apply_instance }, simp only [unique_mdiff_on, unique_mdiff_within_at, preimage_inter] with mfld_simps at A, have B := A (I.symm x) hx.1.1 hx.1.2, rwa [← preimage_inter, model_with_corners.right_inv _ hx.2] at B } end lemma unique_mdiff_on.tangent_bundle_proj_preimage (hs : unique_mdiff_on I s): unique_mdiff_on I.tangent ((tangent_bundle.proj I M) ⁻¹' s) := hs.smooth_bundle_preimage _ end unique_mdiff
f200e49142fc97a10f2ec359c8771e80ee894a39
97c8e5d8aca4afeebb5b335f26a492c53680efc8
/ground_zero/cubical/path.lean
3b6a72099b16d297eac57e6339278424b4e3a31c
[]
no_license
jfrancese/lean
cf32f0d8d5520b6f0e9d3987deb95841c553c53c
06e7efaecce4093d97fb5ecc75479df2ef1dbbdb
refs/heads/master
1,587,915,151,351
1,551,012,140,000
1,551,012,140,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,039
lean
import ground_zero.cubical.cubes open ground_zero.cubical ground_zero.types ground_zero.HITs open ground_zero.HITs.interval (i₀ i₁ seg) /- * Coercions. * Basic path lemmas: refl, symm, cong, funext... * Connections. * Singleton contractibility, J elimination rule. * PathP. -/ namespace ground_zero.cubical namespace Path universes u v def coe.forward (π : I → Sort u) (i : I) (x : π i₀) : π i := interval.ind x (equiv.subst seg x) (equiv.path_over_subst eq.rfl) i def coe.back (π : I → Sort u) (i : I) (x : π i₁) : π i := interval.ind (equiv.subst seg⁻¹ x) x (begin apply equiv.path_over_subst, transitivity, { symmetry, apply equiv.subst_comp }, transitivity, { apply eq.map (λ p, equiv.subst p x), apply eq.inv_comp }, reflexivity end) i def coe (i k : I) (π : I → Sort u) : π i → π k := coe.forward (λ i, π i → π k) i (coe.forward π k) def coe_inv (i k : I) (π : I → Sort u) : π i → π k := coe.back (λ i, π i → π k) i (coe.back π k) notation `coe⁻¹` := coe_inv @[refl] def refl {α : Sort u} (a : α) : a ⇝ a := <i> a def rfl {α : Sort u} {a : α} : a ⇝ a := <i> a @[symm] def symm {α : Sort u} {a b : α} (p : a ⇝ b) : b ⇝ a := <i> p # −i postfix `⁻¹` := symm abbreviation inv {α : Sort u} {a b : α} (p : a ⇝ b) := p⁻¹ example {α : Sort u} {a b : α} (p : a ⇝ b) : b ⇝ a := coe 1 0 (λ i, b ⇝ p # i) rfl def funext {α : Sort u} {β : α → Sort v} {f g : Π (x : α), β x} (p : Π (x : α), f x ⇝ g x) : f ⇝ g := <i> λ x, p x # i def cong {α : Sort u} {β : Sort v} {a b : α} (f : α → β) (p : a ⇝ b) : f a ⇝ f b := <i> f (p # i) def ap {α : Sort u} {β : α → Sort v} {a b : α} (f : α → β a) (p : a ⇝ b) : f a ⇝ f b := <i> f (p # i) def subst {α : Sort u} {π : α → Sort v} {a b : α} (p : a ⇝ b) (x : π a) : π b := coe 0 1 (λ i, π (p # i)) x abbreviation transport {α : Sort u} (π : α → Sort v) {a b : α} (p : a ⇝ b) : π a → π b := subst p def trans {α β : Sort u} (p : α ⇝ β) : α → β := coe 0 1 (λ i, p # i) abbreviation coerce {α β : Sort u} : (α ⇝ β) → (α → β) := trans def trans_neg {α β : Sort u} (p : α ⇝ β) : β → α := coe 1 0 (λ i, p # i) def transK {α β : Sort u} (p : α ⇝ β) (x : α) : x ⇝ trans_neg p (trans p x) := <i> coe i 0 (λ i, p # i) (coe 0 i (λ i, p # i) x) def idtoeqv {α β : Sort u} (p : α ⇝ β) : α ≃ β := trans (<i> α ≃ p # i) (equiv.id α) def test_eta {α : Sort u} {a b : α} (p : a ⇝ b) : p ⇝ p := rfl def face₀ {α : Sort u} {a b : α} (p : a ⇝ b) : α := p # 0 def face₁ {α : Sort u} {a b : α} (p : a ⇝ b) : α := p # 1 def comp_test₀ {α : Sort u} {a b : α} (p : a ⇝ b) : p # 0 ⇝ a := rfl def comp_test₁ {α : Sort u} {a b : α} (p : a ⇝ b) : p # 1 ⇝ b := rfl -- fail --def symm_test {α : Type u} {a b : α} (p : a ⇝ b) : (p⁻¹)⁻¹ ⇝ p := rfl @[trans] def composition {α : Sort u} {a b c : α} (p : a ⇝ b) (q : b ⇝ c) : a ⇝ c := subst q p infix ⬝ := composition -- this will be replaced by a more general version in future def kan {α : Sort u} {a b c d : α} (bottom : b ⇝ c) (left : b ⇝ a) (right : c ⇝ d) : a ⇝ d := left⁻¹ ⬝ bottom ⬝ right def kan_op {α : Sort u} {a b : α} (p : a ⇝ a) (q : a ⇝ b) : b ⇝ b := kan p q q def interval_contr (i : I) : i₀ ⇝ i := coe 0 i (λ i, i₀ ⇝ i) rfl def seg_path : i₀ ⇝ i₁ := interval_contr i₁ -- or too direct way example : i₀ ⇝ i₁ := <i> i def conn_and {α : Sort u} {a b : α} (p : a ⇝ b) : LineP (λ i, a ⇝ p # i) := λ i, <j> p # i ∧ j def conn_or {α : Sort u} {a b : α} (p : a ⇝ b) : LineP (λ i, p # i ⇝ b) := λ i, <j> p # i ∨ j def singl {α : Sort u} (a : α) := Σ' (x : α), a ⇝ x def eta {α : Sort u} (a : α) : singl a := ⟨a, refl a⟩ def refl_contr {α : Sort u} {a b : α} (p : a ⇝ b) : LineP (λ i, a ⇝ p # i) := interval.hrec _ (refl a) p (begin cases p with f, unfold refl, apply heq.map, funext, refine interval.prop_rec _ _ i, { reflexivity }, { apply ground_zero.support.truncation, apply eq.map, exact seg } end) /- This doesn’t pass typechecking. def J {α : Type u} {a : α} {π : Π (b : α), a ⇝ b → Type u} (h : π a (refl a)) (b : α) (p : a ⇝ b) : π b (<i> p # i) := coe (λ i, π (p # i) (conn_and p i)) h i₁ def J {α : Type u} {a : α} {π : Π (b : α), a ⇝ b → Type u} (h : π a (refl a)) (b : α) (p : a ⇝ b) : π b (<i> p # i) := transport (<i> π (p # i) (<j> p # i ∧ j)) h -/ def J {α : Sort u} {a : α} (π : Π (b : α), a ⇝ b → Sort v) (h : π a (refl a)) {b : α} (p : a ⇝ b) : π b p := trans (<i> π (p # i) (refl_contr p i)) h end Path def {u} PathP (σ : I → Sort u) (a : σ 0) (b : σ 1) := Path (equiv.subst interval.seg a) b def {u} PathP.lam (σ : I → Sort u) (f : Π i, σ i) : PathP σ (f 0) (f 1) := Path.lam (interval.rec _ _ (equiv.apd f interval.seg)) end ground_zero.cubical
88ed768ae10713610955fc168f7c8a55933469c4
9028d228ac200bbefe3a711342514dd4e4458bff
/src/linear_algebra/affine_space/basic.lean
df9454ede56490ac5fce0f4230afc941b21c93c8
[ "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
58,380
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import algebra.add_torsor import linear_algebra.tensor_product noncomputable theory open_locale big_operators open_locale classical /-! # Affine spaces This file defines affine spaces (over modules) and subspaces, affine maps, and the affine span of a set of points. For affine combinations of points, see `linear_algebra.affine_space.combination`. For affinely independent families of points, see `linear_algebra.affine_space.independent`. For some additional results relating to finite-dimensional subspaces of affine spaces, see `linear_algebra.affine_space.finite_dimensional`. ## Main definitions * `affine_space V P` is an abbreviation for `add_torsor V P` in the case of `module k V`. `P` is the type of points in the space and `V` the `k`-module of displacement vectors. Definitions and results not depending on the `module` structure appear in `algebra.add_torsor` instead of here; that includes the instance of an `add_group` as an `add_torsor` over itself, which thus gives a `module` as an `affine_space` over itself. Definitions of affine spaces vary as to whether a space with no points is permitted; here, we require a nonempty type of points (via the definition of torsors requiring a nonempty type). Affine spaces are defined over any module, with stronger type class requirements on `k` being used for individual lemmas where needed. * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Implementation notes `out_param` is used to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. TODO: Some key definitions are not yet present. * Coercions from an `affine_subspace` to the subtype of its points, and a corresponding `affine_space` instance on that subtype in the case of a nonempty subspace. * `affine_equiv` (see issue #2909). * Affine frames. An affine frame might perhaps be represented as an `affine_equiv` to a `finsupp` (in the general case) or function type (in the finite-dimensional case) that gives the coordinates, with appropriate proofs of existence when `k` is a field. * Although results on affine combinations implicitly provide barycentric frames and coordinates, there is no explicit representation of the map from a point to its coordinates. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ /- `affine_space` is an abbreviation for `add_torsor` in the case where the group is a vector space, or more generally a module. We omit the arguments `(k : Type*) [ring k] [module k V]` in the type synonym itself to simplify type class search. -/ notation `affine_space` := add_torsor section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (vsub_set s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (vsub_set s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_set_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_set_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `vsub_set` lies within the `vector_span`. -/ lemma vsub_set_subset_vector_span (s : set P) : vsub_set s ⊆ vector_span k s := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub_set hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := vsub_set (s : set P), zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub_set hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub_set _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub_set _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = vsub_set (s : set P) := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [submodule.mem_coe, ←submodule.neg_mem_iff, ←submodule.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_assoc] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw submodule.le_def at hs, rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, submodule.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_set_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono (set.inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono (set.inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw submodule.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw submodule.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ submodule.span k {p2 -ᵥ p1} := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub_set (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero_iff_eq, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_assoc] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace /-- An `affine_map k P1 P2` is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : linear_map k V1 V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 instance: has_coe_to_fun (affine_map k P1 P2) := ⟨_, to_fun⟩ /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : affine_map k P1 P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : affine_map k P1 P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : affine_map k P1 P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : affine_map k P1 P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : affine_map k P1 P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : affine_map k P1 P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : affine_map k P1 P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} instance nonempty : nonempty (affine_map k P1 P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : affine_map k P1 P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_assoc] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (affine_map k P1 V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : affine_map k P1 V2) = 0 := rfl @[simp] lemma zero_linear : (0 : affine_map k P1 V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : affine_map k P1 V2) : ⇑(f + g) = f + g := rfl @[simp] lemma add_linear (f g : affine_map k P1 V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine spaces from `P1` to the vector `V2` corresponding to `P2`. -/ instance : affine_space (affine_map k P1 V2) (affine_map k P1 P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_assoc, add_right_comm]⟩, zero_vadd' := λ f, ext $ λ p, zero_vadd _ (f p), vadd_assoc' := λ f₁ f₂ f₃, ext $ λ p, vadd_assoc (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : affine_map k P1 V2) (g : affine_map k P1 P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : affine_map k P1 P2) (p : P1) : (f -ᵥ g : affine_map k P1 V2) p = f p -ᵥ g p := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : affine_map k P1 P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (affine_map k P1 P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : affine_map k P2 P3) (g : affine_map k P1 P2) : affine_map k P1 P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : affine_map k P2 P3) (g : affine_map k P1 P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : affine_map k P2 P3) (g : affine_map k P1 P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : affine_map k P1 P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : affine_map k P1 P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : affine_map k P3 P4) (f₂₃ : affine_map k P2 P3) (f₁₂ : affine_map k P1 P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (affine_map k P1 P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : affine_map k P1 P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : affine_map k P1 P1) = _root_.id := rfl /-- The affine map from `k` to `P1` sending `0` to `p` and `1` to `v +ᵥ p`. -/ def line_map (p : P1) (v : V1) : affine_map k k P1 := { to_fun := λ c, c • v +ᵥ p, linear := linear_map.id.smul_right v, map_vadd' := λ a b, by simp [add_smul, vadd_assoc] } lemma line_map_apply (p : P1) (v : V1) (c : k) : line_map p v c = c • v +ᵥ p := rfl @[simp] lemma line_map_linear (p : P1) (v : V1) : (line_map p v : affine_map k k P1).linear = linear_map.id.smul_right v := rfl @[simp] lemma line_map_zero (p : P1) : line_map p (0:V1) = const k k p := by { ext c, simp [line_map_apply] } @[simp] lemma line_map_apply_zero (p : P1) (v : V1) : line_map p v (0:k) = p := by simp [line_map_apply] include V2 @[simp] lemma affine_apply_line_map (f : affine_map k P1 P2) (p : P1) (v : V1) (c : k) : f (line_map p v c) = line_map (f p) (f.linear v) c := by simp [line_map_apply] @[simp] lemma affine_comp_line_map (f : affine_map k P1 P2) (p : P1) (v : V1) : f.comp (line_map p v) = line_map (f p) (f.linear v) := ext $ f.affine_apply_line_map p v omit V2 lemma line_map_vadd_neg (p : P1) (v : V1) : line_map (v +ᵥ p) (-v) = (line_map p v).comp (line_map (1:k) (-1:k)) := by { rw [affine_comp_line_map], simp [line_map_apply] } /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : affine_map k V1 V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : affine_map k V1 V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] include V1 /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (affine_map k P1 V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : affine_map k P1 V2) : ⇑(c • f) = c • f := rfl /-- `homothety c r` is the homothety about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : affine_map k P1 P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_assoc] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* affine_map k P1 P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : affine_map k k (affine_map k P1 P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : affine_map k k _) = homothety c := rfl end affine_map namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : affine_map k V₁ V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map
e2eb93279c392ecb8ed32c014cfd4223ddd7a8ab
4fa161becb8ce7378a709f5992a594764699e268
/archive/imo1988_q6.lean
55853c20b6f1e7b24da16ee60507597d71d17c42
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
13,812
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.rat.basic import tactic /-! # IMO1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called “Vieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ -- open_locale classical local attribute [instance] classical.prop_decidable local attribute [simp] nat.pow_two /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developped, the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `λ a b, a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:ℤ) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `λ x y, false`. -/ lemma constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop) (H_quad : ∀ {x y}, H x y ↔ (y:ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x) (H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim) (H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y → ∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x) (H_base : ∀ {x y}, H x y → base x y → claim) : claim := begin -- First of all, we may assume that x ≤ y. -- We justify this using H_symm. wlog hxy : x ≤ y, swap, { rw H_symm at h₀, solve_by_elim }, -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag h₀}, -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y, -- Consider the upper branch of the hyperbola defined by H. let upper_branch : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2}, -- Note that the point p = (x,y) lies on the upper branch. let p : ℕ × ℕ := ⟨x,y⟩, have hp : p ∈ upper_branch := ⟨h₀, hxy⟩, -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) }, -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : set ℕ := prod.snd '' (upper_branch \ exceptional), -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.nonempty, { -- Suppose that there exists an element in the exceptional locus. simp [exceptional, -add_comm, set.nonempty] at exc, -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB, -- The first three cases are rather easy to solve. { solve_by_elim }, { rw H_symm at hH, solve_by_elim }, { solve_by_elim }, -- The final two cases are very similar. all_goals { -- Consider the quadratic equation that (a,b) satisfies. rw H_quad at hH, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩, -- By substitutions we find that b = 0 or b = a. simp [hB] at hV₁, subst hV₁, rw [← int.coe_nat_zero] at *, rw ← H_quad at h_root, -- And hence we are done by H_zero and H_diag. solve_by_elim } }, -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards dering a contradiction. rw ← set.ne_empty_iff_nonempty, assume exceptional_empty, -- Observe that S is nonempty. have S_nonempty : S.nonempty, { -- It contains the image of p. use p.2, apply set.mem_image_of_mem, -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, set.diff_empty], }, -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : ℕ := well_founded.min nat.lt_wf S S_nonempty, have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty, have m_min : ∀ k ∈ S, ¬ k < m := λ k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk, -- It suffices to show that there is point (a,b) with b ∈ S and b < m. suffices hp' : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m, { rcases hp' with ⟨p', p'_mem, p'_small⟩, solve_by_elim }, -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩, -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp [exceptional, hHm] at mx_lt_my h_base m_eq, push_neg at h_base, -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩, replace hmx : 0 < mx := nat.pos_iff_ne_zero.mpr hmx, -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm, rw H_quad at h_quad, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩, -- No we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁, rw mul_comm at hV₂, have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂, -- This means that we may assume that c ≥ 0 and c ≤ m_x. cases Hc with c_nonneg c_lt, -- In other words, c is a natural number. lift c to ℕ using c_nonneg, -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : ℕ × ℕ := ⟨c, mx⟩, use p', -- The second condition is rather easy to check, so we do that first. split, swap, { rwa m_eq at mx_lt_my }, -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply set.mem_image_of_mem, rw [exceptional_empty, set.diff_empty], -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. split; dsimp only, { -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad], simpa using h_root, }, { -- For the second condition, we note that it suffices to check that c ≠ m_x. suffices hc : c ≠ mx, { refine lt_of_le_of_ne _ hc, exact_mod_cast c_lt, }, -- However, recall that B(m_x) ≠ m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_B₂, subst c, simp [hV₁], } -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end /--Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/ lemma imo1988_q6 {a b : ℕ} (h : (a*b+1) ∣ a^2 + b^2) : ∃ d, d^2 = (a^2 + b^2)/(a*b + 1) := begin rcases h with ⟨k, hk⟩, rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))], simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x - k) (λ x y, false); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, norm_cast, simp, ring, }, { -- Show that the solution set is symmetric in a and b. intros x y, simp [add_comm (x*x), mul_comm x], }, { -- Show that the claim is true if b = 0. suffices : ∀ a, a * a = k → ∃ d, d * d = k, by simpa, rintros x rfl, use x }, { -- Show that the claim is true if a = b. intros x hx, suffices : k ≤ 1, { rw [nat.le_add_one_iff, nat.le_zero_iff] at this, rcases this with rfl|rfl, { use 0, simp }, { use 1, simp } }, contrapose! hx with k_lt_one, apply ne_of_lt, calc x*x + x*x = x*x * 2 : by rw mul_two ... ≤ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one ... < (x*x + 1) * k : by apply mul_lt_mul; linarith }, { -- Show the descent step. intros x y hx x_lt_y hxky h z h_root hV₁ hV₀, split, { dsimp [-sub_eq_add_neg] at *, have hpos : z*z + x*x > 0, { apply add_pos_of_nonneg_of_pos, { apply mul_self_nonneg }, { apply mul_pos; exact_mod_cast hx }, }, have hzx : z*z + x*x = (z * x + 1) * k, { rw [← sub_eq_zero, ← h_root], ring, }, rw hzx at hpos, replace hpos : z * x + 1 > 0 := pos_of_mul_pos_right hpos (int.coe_zero_le k), replace hpos : z * x ≥ 0 := int.le_of_lt_add_one hpos, apply nonneg_of_mul_nonneg_right hpos (by exact_mod_cast hx), }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, calc z * y > x*x : by apply mul_lt_mul'; linarith ... ≥ x*x - k : sub_le_self _ (int.coe_zero_le k) }, }, { -- There is no base case in this application of Vieta jumping. simp }, end /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : ℕ} (h : a*b ∣ a^2 + b^2 + 1) : 3*a*b = a^2 + b^2 + 1 := begin rcases h with ⟨k, hk⟩, suffices : k = 3, { simp * at *, ring, }, simp only [nat.pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x + 1) (λ x y, x ≤ 1); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, simp, ring, }, { -- Show that the solution set is symmetric in a and b. cc }, { -- Show that the claim is true if b = 0. simp }, { -- Show that the claim is true if a = b. intros x hx, have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k, rw ← hx at x_sq_dvd, obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd, obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm, simpa using hx.symm, }, { -- Show the descent step. intros x y x_lt_y hx h_base h z h_root hV₁ hV₀, split, { have zy_pos : z * y ≥ 0, { rw hV₀, exact_mod_cast (nat.zero_le _) }, apply nonneg_of_mul_nonneg_right zy_pos, linarith }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, push_neg at h_base, calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith ... ≥ x * (x + 1) : by apply mul_le_mul; linarith ... > x * x + 1 : begin rw [mul_add, mul_one], apply add_lt_add_left, assumption_mod_cast end, } }, { -- Show the base case. intros x y h h_base, obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, nat.le_zero_iff] at h_base, { simpa using h, }, { simp only [mul_one, one_mul, add_comm, zero_add] at h, have y_dvd : y ∣ y * k := dvd_mul_right y k, rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd, obtain rfl|rfl : y = 1 ∨ y = 2 := nat.prime_two.2 y y_dvd, all_goals { ring at h, omega } } } end
fbf5c0cf12fc8871b9ec9c72e28b46a47c11d3cc
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/ring_theory/ideals.lean
a91ee69eeb72b7292df6c4228f1e81c4fa0e3d90
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
14,816
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated linear_algebra.basic order.zorn universes u v variables {α : Type u} {β : Type v} [comm_ring α] {a b : α} open set function lattice local attribute [instance] classical.prop_decidable namespace ideal variable (I : ideal α) @[extensionality] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm]; refl lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.2 (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih end @[class] def zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] @[class] def is_maximal (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤ theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert'.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left hz, rw [mul_sub, mul_one, mul_comm, mul_assoc] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this) end⟩ instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, rcases submodule.mem_Sup_of_directed ((eq_top_iff_one _).1 H) I IS cC.directed_on with ⟨J, JS, J0⟩, exact SC JS ((eq_top_iff_one _).2 J0) } end def is_coprime (x y : α) : Prop := span ({x, y} : set α) = ⊤ theorem mem_span_pair {α} [comm_ring α] {x y z : α} : z ∈ span (insert y {x} : set α) ↔ ∃ a b, a * x + b * y = z := begin simp only [mem_span_insert, mem_span_singleton', exists_prop], split, { rintros ⟨a, b, ⟨c, hc⟩, h⟩, exact ⟨c, a, by simp [h, hc]⟩ }, { rintro ⟨b, c, e⟩, exact ⟨c, b * x, ⟨b, rfl⟩, by simp [e.symm]⟩ } end theorem is_coprime_def {α} [comm_ring α] {x y : α} : is_coprime x y ↔ ∀ z, ∃ a b, a * x + b * y = z := by simp [is_coprime, submodule.eq_top_iff', mem_span_pair] theorem is_coprime_self {α} [comm_ring α] (x y : α) : is_coprime x x ↔ is_unit x := by rw [← span_singleton_eq_top]; simp [is_coprime] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] end ideal def nonunits (α : Type u) [monoid α] : set α := { x | ¬is_unit x } @[simp] theorem mem_nonunits_iff {α} [comm_monoid α] {x} : x ∈ nonunits α ↔ ¬ is_unit x := iff.rfl theorem mul_mem_nonunits_right {α} [comm_monoid α] {x y : α} : y ∈ nonunits α → x * y ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left {α} [comm_monoid α] {x y : α} : x ∈ nonunits α → x * y ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits {α} [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff theorem one_not_mem_nonunits {α} [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu @[class] def is_local_ring (α : Type u) [comm_ring α] : Prop := ∃! I : ideal α, I.is_maximal @[class] def is_local_ring.zero_ne_one (h : is_local_ring α) : (0:α) ≠ 1 := let ⟨I, ⟨hI, _⟩, _⟩ := h in ideal.zero_ne_one_of_proper hI def nonunits_ideal (h : is_local_ring α) : ideal α := { carrier := nonunits α, zero := zero_mem_nonunits.2 h.zero_ne_one, add := begin rcases id h with ⟨M, mM, hM⟩, have : ∀ x ∈ nonunits α, x ∈ M, { intros x hx, rcases (ideal.span {x} : ideal α).exists_le_maximal _ with ⟨N, mN, hN⟩, { cases hM N mN, rwa [ideal.span_le, singleton_subset_iff] at hN }, { exact mt ideal.span_singleton_eq_top.1 hx } }, intros x y hx hy, exact coe_subset_nonunits mM.1 (M.add_mem (this _ hx) (this _ hy)) end, smul := λ a x, mul_mem_nonunits_right } @[simp] theorem mem_nonunits_ideal (h : is_local_ring α) {x} : x ∈ nonunits_ideal h ↔ x ∈ nonunits α := iff.rfl theorem local_of_nonunits_ideal (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : is_local_ring α := begin letI NU : ideal α := ⟨nonunits α, zero_mem_nonunits.2 hnze, h, λ a x, mul_mem_nonunits_right⟩, have NU1 := NU.ne_top_iff_one.2 one_not_mem_nonunits, exact ⟨NU, ⟨NU1, λ J hJ, not_not.1 $ λ J0, not_le_of_gt hJ (coe_subset_nonunits J0)⟩, λ J mJ, mJ.eq_of_le NU1 (coe_subset_nonunits mJ.1)⟩, end namespace ideal open ideal def quotient (I : ideal α) := I.quotient namespace quotient variables {I : ideal α} {x y : α} def mk (I : ideal α) (a : α) : I.quotient := submodule.quotient.mk a protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I instance (I : ideal α) : has_one I.quotient := ⟨mk I 1⟩ @[simp] lemma mk_one (I : ideal α) : mk I 1 = 1 := rfl instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk I (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] end⟩ @[simp] theorem mk_mul : mk I (x * y) = mk I x * mk I y := rfl instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg (mk _) (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg (mk _) (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg (mk _) (right_distrib a b c), ..submodule.quotient.add_comm_group I } instance is_ring_hom_mk (I : ideal α) : is_ring_hom (mk I) := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩ def map_mk (I J : ideal α) : ideal I.quotient := { carrier := mk I '' J, zero := ⟨0, J.zero_mem, rfl⟩, add := by rintro _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩; exact ⟨x + y, J.add_mem hx hy, rfl⟩, smul := by rintro ⟨c⟩ _ ⟨x, hx, rfl⟩; exact ⟨c * x, J.mul_mem_left hx, rfl⟩ } @[simp] lemma mk_zero (I : ideal α) : mk I 0 = 0 := rfl @[simp] lemma mk_add (I : ideal α) (a b : α) : mk I (a + b) = mk I a + mk I b := rfl @[simp] lemma mk_neg (I : ideal α) (a : α) : mk I (-a : α) = -mk I a := rfl @[simp] lemma mk_sub (I : ideal α) (a b : α) : mk I (a - b : α) = mk I a - mk I b := rfl @[simp] lemma mk_pow (I : ideal α) (a : α) (n : ℕ) : mk I (a ^ n : α) = mk I a ^ n := by induction n; simp [*, pow_succ] lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected def nonzero_comm_ring {I : ideal α} (hI : I ≠ ⊤) : nonzero_comm_ring I.quotient := { zero_ne_one := zero_ne_one_iff.2 hI, ..quotient.comm_ring I } instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), ..quotient.nonzero_comm_ring hI.1 } lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : discrete_field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_mul_cancel := λ a (ha : a ≠ 0), show dite _ _ _ * a = _, by rw [mul_comm, dif_neg ha]; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, has_decidable_eq := classical.dec_eq _, ..quotient.integral_domain I } variable [comm_ring β] def lift (S : ideal α) (f : α → β) [is_ring_hom f] (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S → β := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero (by simpa only [is_ring_hom.map_sub f] using H _ h) variables {S : ideal α} {f : α → β} [is_ring_hom f] {H : ∀ (a : α), a ∈ S → f a = 0} @[simp] lemma lift_mk : lift S f H (mk S a) = f a := rfl instance : is_ring_hom (lift S f H) := { map_one := by show lift S f H (mk S 1) = 1; simp [is_ring_hom.map_one f, - mk_one], map_add := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ $ λ a₁ a₂, begin show lift S f H (mk S a₁ + mk S a₂) = lift S f H (mk S a₁) + lift S f H (mk S a₂), have := ideal.quotient.is_ring_hom_mk S, rw ← this.map_add, show lift S f H (mk S (a₁ + a₂)) = lift S f H (mk S a₁) + lift S f H (mk S a₂), simp only [lift_mk, is_ring_hom.map_add f], end, map_mul := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ $ λ a₁ a₂, begin show lift S f H (mk S a₁ * mk S a₂) = lift S f H (mk S a₁) * lift S f H (mk S a₂), have := ideal.quotient.is_ring_hom_mk S, rw ← this.map_mul, show lift S f H (mk S (a₁ * a₂)) = lift S f H (mk S a₁) * lift S f H (mk S a₂), simp only [lift_mk, is_ring_hom.map_mul f], end } end quotient end ideal
473277ba40f533bd6af5bbf8ab788714749197e5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/lipschitz.lean
724a89cbada3361cfdcf5ad2e430f1eb010f1754
[ "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
29,136
lean
/- Copyright (c) 2018 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import logic.function.iterate import data.set.intervals.proj_Icc import topology.algebra.order.field import topology.metric_space.basic import topology.bornology.hom /-! # Lipschitz continuous functions A map `f : α → β` between two (extended) metric spaces is called *Lipschitz continuous* with constant `K ≥ 0` if for all `x, y` we have `edist (f x) (f y) ≤ K * edist x y`. For a metric space, the latter inequality is equivalent to `dist (f x) (f y) ≤ K * dist x y`. There is also a version asserting this inequality only for `x` and `y` in some set `s`. In this file we provide various ways to prove that various combinations of Lipschitz continuous functions are Lipschitz continuous. We also prove that Lipschitz continuous functions are uniformly continuous. ## Main definitions and lemmas * `lipschitz_with K f`: states that `f` is Lipschitz with constant `K : ℝ≥0` * `lipschitz_on_with K f`: states that `f` is Lipschitz with constant `K : ℝ≥0` on a set `s` * `lipschitz_with.uniform_continuous`: a Lipschitz function is uniformly continuous * `lipschitz_on_with.uniform_continuous_on`: a function which is Lipschitz on a set is uniformly continuous on that set. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ℝ≥0∞`. Constructors whose names end with `'` take `K : ℝ` as an argument, and return `lipschitz_with (real.to_nnreal K) f`. -/ universes u v w x open filter function set open_locale topological_space nnreal ennreal variables {α : Type u} {β : Type v} {γ : Type w} {ι : Type x} /-- A function `f` is Lipschitz continuous with constant `K ≥ 0` if for all `x, y` we have `dist (f x) (f y) ≤ K * dist x y` -/ def lipschitz_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) := ∀x y, edist (f x) (f y) ≤ K * edist x y lemma lipschitz_with_iff_dist_le_mul [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {f : α → β} : lipschitz_with K f ↔ ∀ x y, dist (f x) (f y) ≤ K * dist x y := by { simp only [lipschitz_with, edist_nndist, dist_nndist], norm_cast } alias lipschitz_with_iff_dist_le_mul ↔ lipschitz_with.dist_le_mul lipschitz_with.of_dist_le_mul /-- A function `f` is Lipschitz continuous with constant `K ≥ 0` on `s` if for all `x, y` in `s` we have `dist (f x) (f y) ≤ K * dist x y` -/ def lipschitz_on_with [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) (s : set α) := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), edist (f x) (f y) ≤ K * edist x y @[simp] lemma lipschitz_on_with_empty [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (f : α → β) : lipschitz_on_with K f ∅ := λ x x_in y y_in, false.elim x_in lemma lipschitz_on_with.mono [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {s t : set α} {f : α → β} (hf : lipschitz_on_with K f t) (h : s ⊆ t) : lipschitz_on_with K f s := λ x x_in y y_in, hf (h x_in) (h y_in) lemma lipschitz_on_with_iff_dist_le_mul [pseudo_metric_space α] [pseudo_metric_space β] {K : ℝ≥0} {s : set α} {f : α → β} : lipschitz_on_with K f s ↔ ∀ (x ∈ s) (y ∈ s), dist (f x) (f y) ≤ K * dist x y := by { simp only [lipschitz_on_with, edist_nndist, dist_nndist], norm_cast } alias lipschitz_on_with_iff_dist_le_mul ↔ lipschitz_on_with.dist_le_mul lipschitz_on_with.of_dist_le_mul @[simp] lemma lipschitz_on_univ [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} : lipschitz_on_with K f univ ↔ lipschitz_with K f := by simp [lipschitz_on_with, lipschitz_with] lemma lipschitz_on_with_iff_restrict [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} {s : set α} : lipschitz_on_with K f s ↔ lipschitz_with K (s.restrict f) := by simp only [lipschitz_on_with, lipschitz_with, set_coe.forall', restrict, subtype.edist_eq] alias lipschitz_on_with_iff_restrict ↔ lipschitz_on_with.to_restrict _ lemma maps_to.lipschitz_on_with_iff_restrict [pseudo_emetric_space α] [pseudo_emetric_space β] {K : ℝ≥0} {f : α → β} {s : set α} {t : set β} (h : maps_to f s t) : lipschitz_on_with K f s ↔ lipschitz_with K (h.restrict f s t) := lipschitz_on_with_iff_restrict alias maps_to.lipschitz_on_with_iff_restrict ↔ lipschitz_on_with.to_restrict_maps_to _ namespace lipschitz_with section emetric open emetric variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {f : α → β} {x y : α} {r : ℝ≥0∞} protected lemma lipschitz_on_with (h : lipschitz_with K f) (s : set α) : lipschitz_on_with K f s := λ x _ y _, h x y lemma edist_le_mul (h : lipschitz_with K f) (x y : α) : edist (f x) (f y) ≤ K * edist x y := h x y lemma edist_le_mul_of_le (h : lipschitz_with K f) (hr : edist x y ≤ r) : edist (f x) (f y) ≤ K * r := (h x y).trans $ ennreal.mul_left_mono hr lemma edist_lt_mul_of_lt (h : lipschitz_with K f) (hK : K ≠ 0) (hr : edist x y < r) : edist (f x) (f y) < K * r := (h x y).trans_lt $ (ennreal.mul_lt_mul_left (ennreal.coe_ne_zero.2 hK) ennreal.coe_ne_top).2 hr lemma maps_to_emetric_closed_ball (h : lipschitz_with K f) (x : α) (r : ℝ≥0∞) : maps_to f (closed_ball x r) (closed_ball (f x) (K * r)) := λ y hy, h.edist_le_mul_of_le hy lemma maps_to_emetric_ball (h : lipschitz_with K f) (hK : K ≠ 0) (x : α) (r : ℝ≥0∞) : maps_to f (ball x r) (ball (f x) (K * r)) := λ y hy, h.edist_lt_mul_of_lt hK hy lemma edist_lt_top (hf : lipschitz_with K f) {x y : α} (h : edist x y ≠ ⊤) : edist (f x) (f y) < ⊤ := (hf x y).trans_lt $ ennreal.mul_lt_top ennreal.coe_ne_top h lemma mul_edist_le (h : lipschitz_with K f) (x y : α) : (K⁻¹ : ℝ≥0∞) * edist (f x) (f y) ≤ edist x y := begin rw [mul_comm, ← div_eq_mul_inv], exact ennreal.div_le_of_le_mul' (h x y) end protected lemma of_edist_le (h : ∀ x y, edist (f x) (f y) ≤ edist x y) : lipschitz_with 1 f := λ x y, by simp only [ennreal.coe_one, one_mul, h] protected lemma weaken (hf : lipschitz_with K f) {K' : ℝ≥0} (h : K ≤ K') : lipschitz_with K' f := assume x y, le_trans (hf x y) $ ennreal.mul_right_mono (ennreal.coe_le_coe.2 h) lemma ediam_image_le (hf : lipschitz_with K f) (s : set α) : emetric.diam (f '' s) ≤ K * emetric.diam s := begin apply emetric.diam_le, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact hf.edist_le_mul_of_le (emetric.edist_le_diam_of_mem hx hy) end lemma edist_lt_of_edist_lt_div (hf : lipschitz_with K f) {x y : α} {d : ℝ≥0∞} (h : edist x y < d / K) : edist (f x) (f y) < d := calc edist (f x) (f y) ≤ K * edist x y : hf x y ... < d : ennreal.mul_lt_of_lt_div' h /-- A Lipschitz function is uniformly continuous -/ protected lemma uniform_continuous (hf : lipschitz_with K f) : uniform_continuous f := begin refine emetric.uniform_continuous_iff.2 (λε εpos, _), use [ε / K, ennreal.div_pos_iff.2 ⟨ne_of_gt εpos, ennreal.coe_ne_top⟩], exact λ x y, hf.edist_lt_of_edist_lt_div end /-- A Lipschitz function is continuous -/ protected lemma continuous (hf : lipschitz_with K f) : continuous f := hf.uniform_continuous.continuous protected lemma const (b : β) : lipschitz_with 0 (λa:α, b) := assume x y, by simp only [edist_self, zero_le] protected lemma id : lipschitz_with 1 (@id α) := lipschitz_with.of_edist_le $ assume x y, le_rfl protected lemma subtype_val (s : set α) : lipschitz_with 1 (subtype.val : s → α) := lipschitz_with.of_edist_le $ assume x y, le_rfl protected lemma subtype_coe (s : set α) : lipschitz_with 1 (coe : s → α) := lipschitz_with.subtype_val s lemma subtype_mk (hf : lipschitz_with K f) {p : β → Prop} (hp : ∀ x, p (f x)) : lipschitz_with K (λ x, ⟨f x, hp x⟩ : α → {y // p y}) := hf protected lemma eval {α : ι → Type u} [Π i, pseudo_emetric_space (α i)] [fintype ι] (i : ι) : lipschitz_with 1 (function.eval i : (Π i, α i) → α i) := lipschitz_with.of_edist_le $ λ f g, by convert edist_le_pi_edist f g i protected lemma restrict (hf : lipschitz_with K f) (s : set α) : lipschitz_with K (s.restrict f) := λ x y, hf x y protected lemma comp {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f ∘ g) := assume x y, calc edist (f (g x)) (f (g y)) ≤ Kf * edist (g x) (g y) : hf _ _ ... ≤ Kf * (Kg * edist x y) : ennreal.mul_left_mono (hg _ _) ... = (Kf * Kg : ℝ≥0) * edist x y : by rw [← mul_assoc, ennreal.coe_mul] lemma comp_lipschitz_on_with {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} {s : set α} (hf : lipschitz_with Kf f) (hg : lipschitz_on_with Kg g s) : lipschitz_on_with (Kf * Kg) (f ∘ g) s := lipschitz_on_with_iff_restrict.mpr $ hf.comp hg.to_restrict protected lemma prod_fst : lipschitz_with 1 (@prod.fst α β) := lipschitz_with.of_edist_le $ assume x y, le_max_left _ _ protected lemma prod_snd : lipschitz_with 1 (@prod.snd α β) := lipschitz_with.of_edist_le $ assume x y, le_max_right _ _ protected lemma prod {f : α → β} {Kf : ℝ≥0} (hf : lipschitz_with Kf f) {g : α → γ} {Kg : ℝ≥0} (hg : lipschitz_with Kg g) : lipschitz_with (max Kf Kg) (λ x, (f x, g x)) := begin assume x y, rw [ennreal.coe_mono.map_max, prod.edist_eq, ennreal.max_mul], exact max_le_max (hf x y) (hg x y) end protected lemma prod_mk_left (a : α) : lipschitz_with 1 (prod.mk a : β → α × β) := by simpa only [max_eq_right zero_le_one] using (lipschitz_with.const a).prod lipschitz_with.id protected lemma prod_mk_right (b : β) : lipschitz_with 1 (λ a : α, (a, b)) := by simpa only [max_eq_left zero_le_one] using lipschitz_with.id.prod (lipschitz_with.const b) protected lemma uncurry {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, lipschitz_with Kα (λ a, f a b)) (hβ : ∀ a, lipschitz_with Kβ (f a)) : lipschitz_with (Kα + Kβ) (function.uncurry f) := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, simp only [function.uncurry, ennreal.coe_add, add_mul], apply le_trans (edist_triangle _ (f a₂ b₁) _), exact add_le_add (le_trans (hα _ _ _) $ ennreal.mul_left_mono $ le_max_left _ _) (le_trans (hβ _ _ _) $ ennreal.mul_left_mono $ le_max_right _ _) end protected lemma iterate {f : α → α} (hf : lipschitz_with K f) : ∀n, lipschitz_with (K ^ n) (f^[n]) | 0 := lipschitz_with.id | (n + 1) := by rw [pow_succ']; exact (iterate n).comp hf lemma edist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : edist (f^[n] x) (f^[n + 1] x) ≤ edist x (f x) * K ^ n := begin rw [iterate_succ, mul_comm], simpa only [ennreal.coe_pow] using (hf.iterate n) x (f x) end protected lemma mul {f g : function.End α} {Kf Kg} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f * g : function.End α) := hf.comp hg /-- The product of a list of Lipschitz continuous endomorphisms is a Lipschitz continuous endomorphism. -/ protected lemma list_prod (f : ι → function.End α) (K : ι → ℝ≥0) (h : ∀ i, lipschitz_with (K i) (f i)) : ∀ l : list ι, lipschitz_with (l.map K).prod (l.map f).prod | [] := by simpa using lipschitz_with.id | (i :: l) := by { simp only [list.map_cons, list.prod_cons], exact (h i).mul (list_prod l) } protected lemma pow {f : function.End α} {K} (h : lipschitz_with K f) : ∀ n : ℕ, lipschitz_with (K^n) (f^n : function.End α) | 0 := lipschitz_with.id | (n + 1) := by { rw [pow_succ, pow_succ], exact h.mul (pow n) } end emetric section metric variables [pseudo_metric_space α] [pseudo_metric_space β] [pseudo_metric_space γ] {K : ℝ≥0} {f : α → β} {x y : α} {r : ℝ} protected lemma of_dist_le' {K : ℝ} (h : ∀ x y, dist (f x) (f y) ≤ K * dist x y) : lipschitz_with (real.to_nnreal K) f := of_dist_le_mul $ λ x y, le_trans (h x y) $ mul_le_mul_of_nonneg_right (real.le_coe_to_nnreal K) dist_nonneg protected lemma mk_one (h : ∀ x y, dist (f x) (f y) ≤ dist x y) : lipschitz_with 1 f := of_dist_le_mul $ by simpa only [nnreal.coe_one, one_mul] using h /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version doesn't assume `0≤K`. -/ protected lemma of_le_add_mul' {f : α → ℝ} (K : ℝ) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with (real.to_nnreal K) f := have I : ∀ x y, f x - f y ≤ K * dist x y, from assume x y, sub_le_iff_le_add'.2 (h x y), lipschitz_with.of_dist_le' $ assume x y, abs_sub_le_iff.2 ⟨I x y, dist_comm y x ▸ I y x⟩ /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version assumes `0≤K`. -/ protected lemma of_le_add_mul {f : α → ℝ} (K : ℝ≥0) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with K f := by simpa only [real.to_nnreal_coe] using lipschitz_with.of_le_add_mul' K h protected lemma of_le_add {f : α → ℝ} (h : ∀ x y, f x ≤ f y + dist x y) : lipschitz_with 1 f := lipschitz_with.of_le_add_mul 1 $ by simpa only [nnreal.coe_one, one_mul] protected lemma le_add_mul {f : α → ℝ} {K : ℝ≥0} (h : lipschitz_with K f) (x y) : f x ≤ f y + K * dist x y := sub_le_iff_le_add'.1 $ le_trans (le_abs_self _) $ h.dist_le_mul x y protected lemma iff_le_add_mul {f : α → ℝ} {K : ℝ≥0} : lipschitz_with K f ↔ ∀ x y, f x ≤ f y + K * dist x y := ⟨lipschitz_with.le_add_mul, lipschitz_with.of_le_add_mul K⟩ lemma nndist_le (hf : lipschitz_with K f) (x y : α) : nndist (f x) (f y) ≤ K * nndist x y := hf.dist_le_mul x y lemma dist_le_mul_of_le (hf : lipschitz_with K f) (hr : dist x y ≤ r) : dist (f x) (f y) ≤ K * r := (hf.dist_le_mul x y).trans $ mul_le_mul_of_nonneg_left hr K.coe_nonneg lemma maps_to_closed_ball (hf : lipschitz_with K f) (x : α) (r : ℝ) : maps_to f (metric.closed_ball x r) (metric.closed_ball (f x) (K * r)) := λ y hy, hf.dist_le_mul_of_le hy lemma dist_lt_mul_of_lt (hf : lipschitz_with K f) (hK : K ≠ 0) (hr : dist x y < r) : dist (f x) (f y) < K * r := (hf.dist_le_mul x y).trans_lt $ (mul_lt_mul_left $ nnreal.coe_pos.2 hK.bot_lt).2 hr lemma maps_to_ball (hf : lipschitz_with K f) (hK : K ≠ 0) (x : α) (r : ℝ) : maps_to f (metric.ball x r) (metric.ball (f x) (K * r)) := λ y hy, hf.dist_lt_mul_of_lt hK hy /-- A Lipschitz continuous map is a locally bounded map. -/ def to_locally_bounded_map (f : α → β) (hf : lipschitz_with K f) : locally_bounded_map α β := locally_bounded_map.of_map_bounded f $ λ s hs, let ⟨C, hC⟩ := metric.is_bounded_iff.1 hs in metric.is_bounded_iff.2 ⟨K * C, ball_image_iff.2 $ λ x hx, ball_image_iff.2 $ λ y hy, hf.dist_le_mul_of_le (hC hx hy)⟩ @[simp] lemma coe_to_locally_bounded_map (hf : lipschitz_with K f) : ⇑(hf.to_locally_bounded_map f) = f := rfl lemma comap_cobounded_le (hf : lipschitz_with K f) : comap f (bornology.cobounded β) ≤ bornology.cobounded α := (hf.to_locally_bounded_map f).2 lemma bounded_image (hf : lipschitz_with K f) {s : set α} (hs : metric.bounded s) : metric.bounded (f '' s) := metric.bounded_iff_ediam_ne_top.2 $ ne_top_of_le_ne_top (ennreal.mul_ne_top ennreal.coe_ne_top hs.ediam_ne_top) (hf.ediam_image_le s) lemma diam_image_le (hf : lipschitz_with K f) (s : set α) (hs : metric.bounded s) : metric.diam (f '' s) ≤ K * metric.diam s := metric.diam_le_of_forall_dist_le (mul_nonneg K.coe_nonneg metric.diam_nonneg) $ ball_image_iff.2 $ λ x hx, ball_image_iff.2 $ λ y hy, hf.dist_le_mul_of_le $ metric.dist_le_diam_of_mem hs hx hy protected lemma dist_left (y : α) : lipschitz_with 1 (λ x, dist x y) := lipschitz_with.of_le_add $ assume x z, by { rw [add_comm], apply dist_triangle } protected lemma dist_right (x : α) : lipschitz_with 1 (dist x) := lipschitz_with.of_le_add $ assume y z, dist_triangle_right _ _ _ protected lemma dist : lipschitz_with 2 (function.uncurry $ @dist α _) := lipschitz_with.uncurry lipschitz_with.dist_left lipschitz_with.dist_right lemma dist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : dist (f^[n] x) (f^[n + 1] x) ≤ dist x (f x) * K ^ n := begin rw [iterate_succ, mul_comm], simpa only [nnreal.coe_pow] using (hf.iterate n).dist_le_mul x (f x) end lemma _root_.lipschitz_with_max : lipschitz_with 1 (λ p : ℝ × ℝ, max p.1 p.2) := lipschitz_with.of_le_add $ λ p₁ p₂, sub_le_iff_le_add'.1 $ (le_abs_self _).trans (abs_max_sub_max_le_max _ _ _ _) lemma _root_.lipschitz_with_min : lipschitz_with 1 (λ p : ℝ × ℝ, min p.1 p.2) := lipschitz_with.of_le_add $ λ p₁ p₂, sub_le_iff_le_add'.1 $ (le_abs_self _).trans (abs_min_sub_min_le_max _ _ _ _) end metric section emetric variables {α} [pseudo_emetric_space α] {f g : α → ℝ} {Kf Kg : ℝ≥0} protected lemma max (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (max Kf Kg) (λ x, max (f x) (g x)) := by simpa only [(∘), one_mul] using lipschitz_with_max.comp (hf.prod hg) protected lemma min (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (max Kf Kg) (λ x, min (f x) (g x)) := by simpa only [(∘), one_mul] using lipschitz_with_min.comp (hf.prod hg) lemma max_const (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, max (f x) a) := by simpa only [max_eq_left (zero_le Kf)] using hf.max (lipschitz_with.const a) lemma const_max (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, max a (f x)) := by simpa only [max_comm] using hf.max_const a lemma min_const (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, min (f x) a) := by simpa only [max_eq_left (zero_le Kf)] using hf.min (lipschitz_with.const a) lemma const_min (hf : lipschitz_with Kf f) (a : ℝ) : lipschitz_with Kf (λ x, min a (f x)) := by simpa only [min_comm] using hf.min_const a end emetric protected lemma proj_Icc {a b : ℝ} (h : a ≤ b) : lipschitz_with 1 (proj_Icc a b h) := ((lipschitz_with.id.const_min _).const_max _).subtype_mk _ end lipschitz_with namespace metric variables [pseudo_metric_space α] [pseudo_metric_space β] {s : set α} {t : set β} lemma bounded.left_of_prod (h : bounded (s ×ˢ t)) (ht : t.nonempty) : bounded s := by simpa only [fst_image_prod s ht] using (@lipschitz_with.prod_fst α β _ _).bounded_image h lemma bounded.right_of_prod (h : bounded (s ×ˢ t)) (hs : s.nonempty) : bounded t := by simpa only [snd_image_prod hs t] using (@lipschitz_with.prod_snd α β _ _).bounded_image h lemma bounded_prod_of_nonempty (hs : s.nonempty) (ht : t.nonempty) : bounded (s ×ˢ t) ↔ bounded s ∧ bounded t := ⟨λ h, ⟨h.left_of_prod ht, h.right_of_prod hs⟩, λ h, h.1.prod h.2⟩ lemma bounded_prod : bounded (s ×ˢ t) ↔ s = ∅ ∨ t = ∅ ∨ bounded s ∧ bounded t := begin rcases s.eq_empty_or_nonempty with rfl|hs, { simp }, rcases t.eq_empty_or_nonempty with rfl|ht, { simp }, simp only [bounded_prod_of_nonempty hs ht, hs.ne_empty, ht.ne_empty, false_or] end end metric namespace lipschitz_on_with section emetric variables [pseudo_emetric_space α] [pseudo_emetric_space β] [pseudo_emetric_space γ] variables {K : ℝ≥0} {s : set α} {f : α → β} protected lemma uniform_continuous_on (hf : lipschitz_on_with K f s) : uniform_continuous_on f s := uniform_continuous_on_iff_restrict.mpr (lipschitz_on_with_iff_restrict.mp hf).uniform_continuous protected lemma continuous_on (hf : lipschitz_on_with K f s) : continuous_on f s := hf.uniform_continuous_on.continuous_on lemma edist_lt_of_edist_lt_div (hf : lipschitz_on_with K f s) {x y : α} (hx : x ∈ s) (hy : y ∈ s) {d : ℝ≥0∞} (hd : edist x y < d / K) : edist (f x) (f y) < d := (lipschitz_on_with_iff_restrict.mp hf).edist_lt_of_edist_lt_div $ show edist (⟨x, hx⟩ : s) ⟨y, hy⟩ < d / K, from hd protected lemma comp {g : β → γ} {t : set β} {Kg : ℝ≥0} (hg : lipschitz_on_with Kg g t) (hf : lipschitz_on_with K f s) (hmaps : maps_to f s t) : lipschitz_on_with (Kg * K) (g ∘ f) s := lipschitz_on_with_iff_restrict.mpr $ hg.to_restrict.comp (hf.to_restrict_maps_to hmaps) end emetric section metric variables [pseudo_metric_space α] [pseudo_metric_space β] [pseudo_metric_space γ] variables {K : ℝ≥0} {s : set α} {f : α → β} protected lemma of_dist_le' {K : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist (f x) (f y) ≤ K * dist x y) : lipschitz_on_with (real.to_nnreal K) f s := of_dist_le_mul $ λ x hx y hy, le_trans (h x hx y hy) $ mul_le_mul_of_nonneg_right (real.le_coe_to_nnreal K) dist_nonneg protected lemma mk_one (h : ∀ (x ∈ s) (y ∈ s), dist (f x) (f y) ≤ dist x y) : lipschitz_on_with 1 f s := of_dist_le_mul $ by simpa only [nnreal.coe_one, one_mul] using h /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version doesn't assume `0≤K`. -/ protected lemma of_le_add_mul' {f : α → ℝ} (K : ℝ) (h : ∀ (x ∈ s) (y ∈ s), f x ≤ f y + K * dist x y) : lipschitz_on_with (real.to_nnreal K) f s := have I : ∀ (x ∈ s) (y ∈ s), f x - f y ≤ K * dist x y, from assume x hx y hy, sub_le_iff_le_add'.2 (h x hx y hy), lipschitz_on_with.of_dist_le' $ assume x hx y hy, abs_sub_le_iff.2 ⟨I x hx y hy, dist_comm y x ▸ I y hy x hx⟩ /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version assumes `0≤K`. -/ protected lemma of_le_add_mul {f : α → ℝ} (K : ℝ≥0) (h : ∀ (x ∈ s) (y ∈ s), f x ≤ f y + K * dist x y) : lipschitz_on_with K f s := by simpa only [real.to_nnreal_coe] using lipschitz_on_with.of_le_add_mul' K h protected lemma of_le_add {f : α → ℝ} (h : ∀ (x ∈ s) (y ∈ s), f x ≤ f y + dist x y) : lipschitz_on_with 1 f s := lipschitz_on_with.of_le_add_mul 1 $ by simpa only [nnreal.coe_one, one_mul] protected lemma le_add_mul {f : α → ℝ} {K : ℝ≥0} (h : lipschitz_on_with K f s) {x : α} (hx : x ∈ s) {y : α} (hy : y ∈ s) : f x ≤ f y + K * dist x y := sub_le_iff_le_add'.1 $ le_trans (le_abs_self _) $ h.dist_le_mul x hx y hy protected lemma iff_le_add_mul {f : α → ℝ} {K : ℝ≥0} : lipschitz_on_with K f s ↔ ∀ (x ∈ s) (y ∈ s), f x ≤ f y + K * dist x y := ⟨lipschitz_on_with.le_add_mul, lipschitz_on_with.of_le_add_mul K⟩ end metric end lipschitz_on_with /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical fiber” `{a} × t`, `a ∈ s`, and is Lipschitz continuous on each “horizontal fiber” `s × {b}`, `b ∈ t` with the same Lipschitz constant `K`. Then it is continuous on `s × t`. The actual statement uses (Lipschitz) continuity of `λ y, f (a, y)` and `λ x, f (x, b)` instead of continuity of `f` on subsets of the product space. -/ lemma continuous_on_prod_of_continuous_on_lipschitz_on [pseudo_emetric_space α] [topological_space β] [pseudo_emetric_space γ] (f : α × β → γ) {s : set α} {t : set β} (K : ℝ≥0) (ha : ∀ a ∈ s, continuous_on (λ y, f (a, y)) t) (hb : ∀ b ∈ t, lipschitz_on_with K (λ x, f (x, b)) s) : continuous_on f (s ×ˢ t) := begin rintro ⟨x, y⟩ ⟨hx : x ∈ s, hy : y ∈ t⟩, refine emetric.tendsto_nhds.2 (λ ε (ε0 : 0 < ε), _), replace ε0 : 0 < ε / 2 := ennreal.half_pos (ne_of_gt ε0), have εK : 0 < ε / 2 / K := ennreal.div_pos_iff.2 ⟨ε0.ne', ennreal.coe_ne_top⟩, have A : s ∩ emetric.ball x (ε / 2 / K) ∈ 𝓝[s] x := inter_mem_nhds_within _ (emetric.ball_mem_nhds _ εK), have B : {b : β | b ∈ t ∧ edist (f (x, b)) (f (x, y)) < ε / 2} ∈ 𝓝[t] y := inter_mem self_mem_nhds_within (ha x hx y hy (emetric.ball_mem_nhds _ ε0)), filter_upwards [nhds_within_prod A B], rintro ⟨a, b⟩ ⟨⟨has : a ∈ s, hax : edist a x < ε / 2 / K⟩, hbt : b ∈ t, hby : edist (f (x, b)) (f (x, y)) < ε / 2⟩, calc edist (f (a, b)) (f (x, y)) ≤ edist (f (a, b)) (f (x, b)) + edist (f (x, b)) (f (x, y)) : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add ((hb _ hbt).edist_lt_of_edist_lt_div has hx hax) hby ... = ε : ennreal.add_halves ε end /-- Consider a function `f : α × β → γ`. Suppose that it is continuous on each “vertical section” `{a} × univ`, `a : α`, and is Lipschitz continuous on each “horizontal section” `univ × {b}`, `b : β` with the same Lipschitz constant `K`. Then it is continuous. The actual statement uses (Lipschitz) continuity of `λ y, f (a, y)` and `λ x, f (x, b)` instead of continuity of `f` on subsets of the product space. -/ lemma continuous_prod_of_continuous_lipschitz [pseudo_emetric_space α] [topological_space β] [pseudo_emetric_space γ] (f : α × β → γ) (K : ℝ≥0) (ha : ∀ a, continuous (λ y, f (a, y))) (hb : ∀ b, lipschitz_with K (λ x, f (x, b))) : continuous f := begin simp only [continuous_iff_continuous_on_univ, ← univ_prod_univ, ← lipschitz_on_univ] at *, exact continuous_on_prod_of_continuous_on_lipschitz_on f K (λ a _, ha a) (λ b _, hb b) end open metric /-- If a function is locally Lipschitz around a point, then it is continuous at this point. -/ lemma continuous_at_of_locally_lipschitz [pseudo_metric_space α] [pseudo_metric_space β] {f : α → β} {x : α} {r : ℝ} (hr : 0 < r) (K : ℝ) (h : ∀ y, dist y x < r → dist (f y) (f x) ≤ K * dist y x) : continuous_at f x := begin -- We use `h` to squeeze `dist (f y) (f x)` between `0` and `K * dist y x` refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero' (eventually_of_forall $ λ _, dist_nonneg) (mem_of_superset (ball_mem_nhds _ hr) h) _), -- Then show that `K * dist y x` tends to zero as `y → x` refine (continuous_const.mul (continuous_id.dist continuous_const)).tendsto' _ _ _, simp end /-- A function `f : α → ℝ` which is `K`-Lipschitz on a subset `s` admits a `K`-Lipschitz extension to the whole space. -/ lemma lipschitz_on_with.extend_real [pseudo_metric_space α] {f : α → ℝ} {s : set α} {K : ℝ≥0} (hf : lipschitz_on_with K f s) : ∃ g : α → ℝ, lipschitz_with K g ∧ eq_on f g s := begin /- An extension is given by `g y = Inf {f x + K * dist y x | x ∈ s}`. Taking `x = y`, one has `g y ≤ f y` for `y ∈ s`, and the other inequality holds because `f` is `K`-Lipschitz, so that it can not counterbalance the growth of `K * dist y x`. One readily checks from the formula that the extended function is also `K`-Lipschitz. -/ rcases eq_empty_or_nonempty s with rfl|hs, { exact ⟨λ x, 0, (lipschitz_with.const _).weaken (zero_le _), eq_on_empty _ _⟩ }, haveI : nonempty s, by simp only [hs, nonempty_coe_sort], let g := λ (y : α), infi (λ (x : s), f x + K * dist y x), have B : ∀ (y : α), bdd_below (range (λ (x : s), f x + K * dist y x)), { assume y, rcases hs with ⟨z, hz⟩, refine ⟨f z - K * dist y z, _⟩, rintros w ⟨t, rfl⟩, dsimp, rw [sub_le_iff_le_add, add_assoc, ← mul_add, add_comm (dist y t)], calc f z ≤ f t + K * dist z t : hf.le_add_mul hz t.2 ... ≤ f t + K * (dist y z + dist y t) : add_le_add_left (mul_le_mul_of_nonneg_left (dist_triangle_left _ _ _) K.2) _ }, have E : eq_on f g s, { assume x hx, refine le_antisymm (le_cinfi (λ y, hf.le_add_mul hx y.2)) _, simpa only [add_zero, subtype.coe_mk, mul_zero, dist_self] using cinfi_le (B x) ⟨x, hx⟩ }, refine ⟨g, lipschitz_with.of_le_add_mul K (λ x y, _), E⟩, rw ← sub_le_iff_le_add, refine le_cinfi (λ z, _), rw sub_le_iff_le_add, calc g x ≤ f z + K * dist x z : cinfi_le (B x) _ ... ≤ f z + K * dist y z + K * dist x y : begin rw [add_assoc, ← mul_add, add_comm (dist y z)], exact add_le_add_left (mul_le_mul_of_nonneg_left (dist_triangle _ _ _) K.2) _, end end /-- A function `f : α → (ι → ℝ)` which is `K`-Lipschitz on a subset `s` admits a `K`-Lipschitz extension to the whole space. TODO: state the same result (with the same proof) for the space `ℓ^∞ (ι, ℝ)` over a possibly infinite type `ι`. -/ lemma lipschitz_on_with.extend_pi [pseudo_metric_space α] [fintype ι] {f : α → (ι → ℝ)} {s : set α} {K : ℝ≥0} (hf : lipschitz_on_with K f s) : ∃ g : α → (ι → ℝ), lipschitz_with K g ∧ eq_on f g s := begin have : ∀ i, ∃ g : α → ℝ, lipschitz_with K g ∧ eq_on (λ x, f x i) g s, { assume i, have : lipschitz_on_with K (λ (x : α), f x i) s, { apply lipschitz_on_with.of_dist_le_mul (λ x hx y hy, _), exact (dist_le_pi_dist _ _ i).trans (hf.dist_le_mul x hx y hy) }, exact this.extend_real }, choose g hg using this, refine ⟨λ x i, g i x, lipschitz_with.of_dist_le_mul (λ x y, _), _⟩, { exact (dist_pi_le_iff (mul_nonneg K.2 dist_nonneg)).2 (λ i, (hg i).1.dist_le_mul x y) }, { assume x hx, ext1 i, exact (hg i).2 hx } end
f93f76c43b1e5302ec011c7713256951abeee09c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/interactive_expr.lean
e4fd02b995688fe2ab6c0e6727eb3120093342e1
[ "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
17,544
lean
/- Copyright (c) 2020 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ /-! # Widgets used for tactic state and term-mode goal display The vscode extension supports the display of interactive widgets. Default implementation of these widgets are included in the core library. We override them here using `vm_override` so that we can change them quickly without waiting for the next Lean release. The function `widget_override.interactive_expression.mk` renders a single expression as a widget component. Each goal in a tactic state is rendered using the `widget_override.tactic_view_goal` function, a complete tactic state is rendered using `widget_override.tactic_view_component`. Lean itself calls the `widget_override.term_goal_widget` function to render term-mode goals and `widget_override.tactic_state_widget` to render the tactic state in a tactic proof. -/ namespace widget_override open widget open tagged_format open widget.html widget.attr namespace interactive_expression meta instance : has_mem expr.coord expr.address := list.has_mem /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf | highlight : format.color → sf → sf | block : ℕ → sf → sf /-- Prints a debugging representation of an `sf` object. -/ meta def sf.repr : sf → format | (sf.tag_expr addr e a) := format.group $ format.nest 2 $ "(tag_expr " ++ to_fmt addr ++ format.line ++ "`(" ++ to_fmt e ++ ")" ++ format.line ++ a.repr ++ ")" | (sf.compose a b) := a.repr ++ format.line ++ b.repr | (sf.of_string s) := repr s | (sf.block i a) := "(block " ++ to_fmt i ++ format.line ++ a.repr ++ ")" | (sf.highlight c a) := "(highlight " ++ c.to_string ++ a.repr ++ ")" meta instance : has_to_format sf := ⟨sf.repr⟩ meta instance : has_to_string sf := ⟨λ s, s.repr.to_string⟩ meta instance : has_repr sf := ⟨λ s, s.repr.to_string⟩ /-- Constructs an `sf` from an `eformat` by forgetting grouping, nesting, etc. -/ meta def sf.of_eformat : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ sf.of_eformat m | (group m) := sf.block 0 $ sf.of_eformat m | (nest i m) := sf.block i $ sf.of_eformat m | (highlight c m) := sf.highlight c $ sf.of_eformat m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (sf.of_eformat x) (sf.of_eformat y) /-- Flattens an `sf`, i.e. merges adjacent `of_string` constructors. -/ meta def sf.flatten : sf → sf | (sf.tag_expr ea e m) := (sf.tag_expr ea e $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := -- replace newline by space sf.of_string (s.to_list.map (λ c, if c = '\n' then ' ' else c)).as_string | (sf.block i (sf.block j a)) := (sf.block (i+j) a).flatten | (sf.block i a) := sf.block i a.flatten | (sf.highlight i a) := sf.highlight i a.flatten private meta def elim_part_apps : sf → expr.address → sf | (sf.tag_expr ea e m) acc := if ∀ c ∈ ea, c = expr.coord.app_fn then elim_part_apps m (acc ++ ea) else sf.tag_expr (acc ++ ea) e (elim_part_apps m []) | (sf.compose a b) acc := (elim_part_apps a acc).compose (elim_part_apps b acc) | (sf.of_string s) _ := sf.of_string s | (sf.block i a) acc := sf.block i $ elim_part_apps a acc | (sf.highlight c a) acc := sf.highlight c $ elim_part_apps a acc /-- Post-process an `sf` object to eliminate tags for partial applications by pushing the `app_fn` as far into the expression as possible. The effect is that clicking on a sub-expression always includes the full argument list in the popup. Consider the expression `id id 0`. We push the `app_fn` for the partial application `id id` inwards and eliminate it. Before: ``` (tag_expr [app_fn] `(id.{1} (nat -> nat) (id.{1} nat)) (tag_expr [app_fn] `(id.{1} (nat -> nat)) "id") "\n" (tag_expr [app_arg] `(id.{1} nat) "id")) "\n" (tag_expr [app_arg] `(has_zero.zero.{0} nat nat.has_zero) "0") ``` After: ``` "id" "\n" (tag_expr [app_fn, app_arg] `(id.{1} nat) "id") "\n" (tag_expr [app_arg] `(has_zero.zero.{0} nat nat.has_zero) "0") ``` -/ meta def sf.elim_part_apps (s : sf) : sf := elim_part_apps s [] /-- The actions accepted by an expression widget. -/ meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action | effect : widget.effect → action /-- Render a 'go to definition' button for a given expression. If there is no definition available, then returns an empty list. -/ meta def goto_def_button {γ} : expr → tactic (list (html (action γ))) | e := (do (expr.const n _) ← pure $ expr.get_app_fn e, env ← tactic.get_env, let file := environment.decl_olean env n, pos ← environment.decl_pos env n, pure $ [h "button" [ cn "pointer ba br3 mr1", on_click (λ _, action.effect $ widget.effect.reveal_position file pos), attr.val "title" "go to definition"] ["↪"]] ) <|> pure [] /-- Due to a bug in the webview browser, we have to reduce the number of spans in the expression. To do this, we collect the attributes from `sf.block` and `sf.highlight` after an expression boundary. -/ meta def get_block_attrs {γ}: sf → tactic (sf × list (attr γ)) | (sf.block i a) := do let s : attr (γ) := style [ ("display", "inline-block"), ("padding-left", "1ch"), ("text-indent", "-1ch"), ("white-space", "pre-wrap"), ("vertical-align", "top") ], (a,rest) ← get_block_attrs a, pure (a, s :: rest) | (sf.highlight c a) := do (a, rest) ← get_block_attrs a, pure (a, (cn c.to_string) :: rest) | a := pure (a,[]) /-- Renders a subexpression as a list of html elements. -/ meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), efmt : string ← format.to_string <$> tactic.pp e, gd_btn ← goto_def_button e, pure [tooltip $ h "div" [] [ h "div" [cn "fr"] (gd_btn ++ [ h "button" [cn "pointer ba br3 mr1", on_click (λ _, action.effect $ widget.effect.copy_text efmt), attr.val "title" "copy expression to clipboard"] ["📋"], h "button" [cn "pointer ba br3", on_click (λ _, action.on_close_tooltip), attr.val "title" "close"] ["×"] ]), content ]] else pure [], (m, block_attrs) ← get_block_attrs m, let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs ++ block_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] | ca b@(sf.block _ _) := do (a, attrs) ← get_block_attrs b, inner ← view ca a, pure [h "span" attrs inner] | ca b@(sf.highlight _ _) := do (a, attrs) ← get_block_attrs b, inner ← view ca a, pure [h "span" attrs inner] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_should_update (λ (x y : tactic_state × expr × expr.address), x.2.2 ≠ y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in component.filter_map_action (λ _ (a : γ ⊕ widget.effect), sum.cases_on a some (λ _, none)) $ component.with_effects (λ _ (a : γ ⊕ widget.effect), match a with | (sum.inl g) := [] | (sum.inr s) := [s] end ) $ tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some $ sum.inl g) | (action.on_close_tooltip) := ((none, sa), none) | (action.effect e) := ((ca,sa), some $ sum.inr $ e) end ) (λ e ⟨ca, sa⟩, do m ← sf.of_eformat <$> tactic.pp_tagged e, let m := m.elim_part_apps, let m := m.flatten, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. let m := m.tag_expr [] e, v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [style [("display", "flex"), ("flexWrap", "wrap"), ("alignItems", "baseline")]] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) /-- Component for the type tooltip. -/ meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [style [ ("minWidth", "8rem"), -- [note]: textIndent is inherited, and we might -- be in an expression here where textIndent is set ("textIndent", "0")] ] [ h "div" [cn "pl1"] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression /-- Supported tactic state filters. -/ @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props /-- Filters a local constant using the given filter. -/ meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t /-- Component for the filter dropdown. -/ meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) /-- Converts a name into an html element. -/ meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic /-- Component that shows a type. -/ meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) (value : option expr) /-- Converts a single local constant into a (singleton) `local_collection` -/ meta def to_local_collection (l : expr) : tactic local_collection := tactic.unsafe.type_context.run $ do lctx ← tactic.unsafe.type_context.get_local_context, some ldecl ← pure $ lctx.get_local_decl l.local_uniq_name, pure { key := l.local_uniq_name.repr, locals := [l], type := ldecl.type, value := ldecl.value } /-- Groups consecutive local collections by type -/ meta def group_local_collection : list local_collection → list local_collection | (a :: b :: rest) := if a.type = b.type ∧ a.value = b.value then group_local_collection $ { locals := a.locals ++ b.locals, ..a } :: rest else a :: group_local_collection (b :: rest) | ls := ls /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, t ← get_tag g, let case_tag : list (html γ) := match interactive.case_tag.parse t with | some t := [h "li" [key "_case"] $ [h "span" [cn "goal-case b"] ["case"]] ++ (t.case_names.bind $ λ n, [" ", n])] | none := [] end, lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← lcs.mmap $ to_local_collection, let lcs := group_local_collection lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, let ns : list (html γ) := lc.locals.map $ λ n, h "span" [cn "goal-hyp b pr2", key n.local_uniq_name] [html.of_name n.local_pp_name], pure $ h "li" [key lc.key] (ns ++ [": ", h "span" [cn "goal-hyp-type", key "type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ case_tag ++ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] /-- Actions accepted by the `tactic_view_component`. -/ meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- The "goals accomplished 🎉" HTML widget. This can be overridden using: ```lean meta def my_new_msg {α : Type} : widget.html α := "my message" attribute [vm_override my_new_msg] widget_override.goals_accomplished_message ``` -/ meta def goals_accomplished_message {α} : html α := h "div" [cn "f5"] ["goals accomplished 🎉"] /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message : html γ := if gs.length = 0 then goals_accomplished_message else if gs.length = 1 then "1 goal" else html.of_string $ to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, h "li" [className $ "lh-copy mt2", key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] /-- Component showing a local collection. -/ meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, match lc.value with | some v := do v ← interactive_expression.mk interactive_expression.type_tooltip v, pure [c, " := ", v] | none := pure [c] end) /-- Renders the current tactic state. -/ meta def tactic_render : tc unit empty := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component /-- Component showing the current tactic state. -/ meta def tactic_state_widget : component tactic_state empty := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state empty := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget_override attribute [vm_override widget_override.term_goal_widget] widget.term_goal_widget attribute [vm_override widget_override.tactic_state_widget] widget.tactic_state_widget
85a169af7dbe4c9a9937ca51bcc7a7de99d93f0c
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/group_theory/order_of_element.lean
ed564113349b50a5391d88d90ad28660f5bb9aa9
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,808
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import group_theory.coset import data.nat.totient import data.set.finite open function variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset lemma conj_inj [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := λ a b h, by simpa [mul_left_inj, mul_right_inj] using h lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α} (h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ is_subgroup.normalizer s := by haveI := classical.prop_decidable; haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_inj), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj hy.2 ▸ hy.1⟩ section order_of variable [group α] open quotient_group set @[simp] lemma card_trivial [fintype (is_subgroup.trivial α)] : fintype.card (is_subgroup.trivial α) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : α), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ variables [fintype α] [dec : decidable_eq α] instance quotient_group.fintype (s : set α) [is_subgroup s] [d : decidable_pred s] : fintype (quotient s) := @quotient.fintype _ _ (left_rel s) (λ _ _, d _) lemma card_eq_card_quotient_mul_card_subgroup (s : set α) [hs : is_subgroup s] [fintype s] [decidable_pred s] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (is_subgroup.group_equiv_quotient_times_subgroup hs) lemma card_subgroup_dvd_card (s : set α) [is_subgroup s] [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card (s : set α) [is_subgroup s] [decidable_pred s] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi:ℤ, a ^ i), from not_injective_infinite_fintype _, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [sub_eq_add_neg, gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end include dec /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : 0 < order_of a := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of a ∣ n ↔ a ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = _ : (finset.card_bind (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext.2 (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma order_of_one : order_of (1 : α) = 1 := by rw [order_eq_card_gpowers, fintype.card_eq_one_iff]; exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩ @[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 := ⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩ lemma order_of_eq_prime {p : ℕ} [hp : fact p.prime] (hg : a^p = 1) (hg1 : a ≠ 1) : order_of a = p := (hp.2 _ (order_of_dvd_of_pow_eq_one hg)).resolve_left (mt order_of_eq_one_iff.1 hg1) section classical open_locale classical open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] omit dec @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) end classical open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma image_range_order_of (a : α) : finset.image (λ i, a ^ i) (finset.range (order_of a)) = (gpowers a).to_finset := by { ext x, rw [set.mem_to_finset, mem_gpowers_iff_mem_range_order_of] } omit dec open_locale classical lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype class is_cyclic (α : Type*) [group α] : Prop := (exists_generator [] : ∃ g : α, ∀ x, x ∈ gpowers g) def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_left H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← fintype.card_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end section variables [group α] [fintype α] [decidable_eq α] lemma is_cyclic.image_range_order_of (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (order_of a)) = univ := begin simp only [image_range_order_of, set.eq_univ_iff_forall.mpr ha], convert set.to_finset_univ end lemma is_cyclic.image_range_card (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (fintype.card α)) = univ := by rw [← order_of_eq_card_of_forall_mem_gpowers ha, is_cyclic.image_range_order_of ha] end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (fintype.of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _) open_locale nat -- use φ for nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in absurd (mem_filter.1 ha).2 $ ne_of_gt $ order_of_pos a | (d+1) := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) = ((range d.succ).filter (∣ d.succ)).sum φ, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 ⟨a ^ (d.succ / m), mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩⟩)), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext.2 $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ]) (by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [mem_range, zero_le_one, le_succ], (add_right_inj (((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card))).1 (calc _ = (insert d.succ (filter (∣ d.succ) (range d.succ))).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ])) ... = ((range d.succ.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ((range d.succ.succ).filter (∣ d.succ)).sum φ : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext, c] ... = ((range c.succ).filter (∣ c)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = (((range c.succ).filter (∣ c)).erase d).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext] at *; exact h0)) ... ≤ (((range c.succ).filter (∣ c)).erase d).sum φ : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (by { intro h, rw h, apply le_refl })) ... < φ d + (((range c.succ).filter (∣ c)).erase d).sum φ : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = (insert d (((range c.succ).filter (∣ c)).erase d)).sum φ : eq.symm (sum_insert (by simp)) ... = ((range c.succ).filter (∣ c)).sum φ : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty, from (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic
feeec80214b340edc269f5f71f2a9fa17f23c32a
4727251e0cd73359b15b664c3170e5d754078599
/src/computability/halting.lean
0f0f670810b6666220055c8ed12ebc2cbf03ef66
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,250
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 computability.partrec_code /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable part theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin obtain ⟨cf, rfl⟩ := code.exists_code.1 hf, obtain ⟨cg, rfl⟩ := code.exists_code.1 hg, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp only [dom_iff_mem, code.evaln_complete, option.mem_def] at h, obtain ⟨x, k, e⟩ | ⟨x, k, e⟩ := h, { refine ⟨k, x, _⟩, simp only [e, option.some_orelse, option.mem_def] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp only [e, option.mem_def, option.none_orelse]⟩ }, { exact ⟨y, by simp only [option.some_orelse, option.mem_def]⟩ } } }, intros x h, obtain ⟨k, e⟩ := nat.rfind_opt_spec h, revert e, simp only [option.mem_def]; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable part nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode₂_iff.1 hf) (bind_decode₂_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw bind_dom, have hk : (k (encode a)).dom := (H _).2.2 (by simpa only [encodek₂, bind_some, coe_some] using h), existsi hk, simp only [exists_prop, mem_map_iff, mem_coe, mem_bind_iff, option.mem_def] at H, obtain ⟨a', ha', y, hy, e⟩ | ⟨a', ha', y, hy, e⟩ := (H _).1 _ ⟨hk, rfl⟩; { simp only [e.symm, encodek] } }, intros x h', simp only [k', exists_prop, mem_coe, mem_bind_iff, option.mem_def] at h', obtain ⟨n, hn, hx⟩ := h', have := (H _).1 _ hn, simp [mem_decode₂, encode_injective.eq_iff] at this, obtain ⟨a', ha, rfl⟩ | ⟨a', ha, rfl⟩ := this; simp only [encodek] at hx; rw hx at ha, { exact or.inl ha }, exact or.inr ha end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp only [bool.cond_tt, bool.cond_ff] end partrec /-- A computable predicate is one whose indicator function is computable. -/ def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, part.assert (p a) (λ _, part.some ())) theorem re_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : re_pred p) (H : ∀ a, p a ↔ q a) : re_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp theorem partrec.dom_re {α β} [primcodable α] [primcodable β] {f : α →. β} (h : partrec f) : re_pred (λ a, (f a).dom) := (h.map (computable.const ()).to₂).of_eq $ λ n, part.ext $ λ _, by simp [part.dom_iff_mem] theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp, unfold re_pred, refine (partrec.cond hf (decidable.partrec.const' (part.some ())) partrec.none).of_eq (λ n, part.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, obtain ⟨c, e⟩ := fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂, simp at e, by_cases H : eval c ∈ C, { simp only [H, if_true] at e, rwa ← e }, { simp only [H, if_false] at e, rw e at H, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by classical; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by obtain rfl | rfl := h; simp [computable_pred, set.mem_empty_eq]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem_re (n) : re_pred (λ c, (eval c n).dom) := (eval_part.comp computable.id (computable.const _)).dom_re theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin obtain ⟨k, pk, hk⟩ := partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _, { refine partrec.of_eq pk (λ n, part.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ theorem computable_iff_re_compl_re' {p : α → Prop} : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := by classical; exact computable_iff_re_compl_re theorem halting_problem_not_re (n) : ¬ re_pred (λ c, ¬ (eval c n).dom) | h := halting_problem _ $ computable_iff_re_compl_re'.2 ⟨halting_problem_re _, h⟩ end computable_pred namespace nat open vector part /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n ::ᵥ v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.partrec₂, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a ::ᵥ v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, part.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a ::ᵥ v))) := by simp [(part.bind_some_eq_map _ _).symm]; exact hf.bind hg local attribute [-instance] part.has_zero /-- Analogous to `nat.partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions.-/ def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v ::ᵥ g v) := λ i, fin.cases (by simp *) (λ i, by simp only [hg i, nth_cons_succ]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a ::ᵥ v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, part.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, part.ext $ λ b, begin simp only [nat.rfind_opt, exists_prop, tsub_eq_zero_iff_le, pfun.coe_val, part.mem_bind_iff, part.mem_some_iff, option.mem_def, part.mem_coe], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr, funext n, simp only [part.some_inj, pfun.coe_val], cases f (n ::ᵥ v); simp [nat.succ_le_succ]; refl }, { have := nat.rfind_spec h, simp only [pfun.coe_val, part.mem_some_iff] at this, cases f (a ::ᵥ v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp only [g]; simp [encodek, part.map_id']), end, λ f hf, begin obtain ⟨c, rfl⟩ := exists_code.1 hf, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp only [id.def, head_of_fn]), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp only [cons_head, cons_tail]), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa only [of_fn_nth] using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
1a8c930704ac4536b2d2de9c054dfae98bb7b012
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/congruence.lean
865204133e71c651e1439854065b7614570d1c05
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,889
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.group_ring_action.basic import algebra.hom.ring import algebra.ring.inj_surj import group_theory.congruence /-! # Congruence relations on rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines congruence relations on rings, which extend `con` and `add_con` on monoids and additive monoids. Most of the time you likely want to use the `ideal.quotient` API that is built on top of this. ## Main Definitions * `ring_con R`: the type of congruence relations respecting `+` and `*`. * `ring_con_gen r`: the inductively defined smallest ring congruence relation containing a given binary relation. ## TODO * Use this for `ring_quot` too. * Copy across more API from `con` and `add_con` in `group_theory/congruence.lean`, such as: * The `complete_lattice` structure. * The `con_gen_eq` lemma, stating that `ring_con_gen r = Inf {s : ring_con M | ∀ x y, r x y → s x y}`. -/ /-- A congruence relation on a type with an addition and multiplication is an equivalence relation which preserves both. -/ /- Note: we can't extend both `add_con R` and `mul_con R` in Lean 3 due to interactions between old- and new-style structures. We can revisit this in Lean 4. (After and not during the port!) -/ structure ring_con (R : Type*) [has_add R] [has_mul R] extends setoid R := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) variables {α R : Type*} /-- The inductively defined smallest ring congruence relation containing a given binary relation. -/ inductive ring_con_gen.rel [has_add R] [has_mul R] (r : R → R → Prop) : R → R → Prop | of : Π x y, r x y → ring_con_gen.rel x y | refl : Π x, ring_con_gen.rel x x | symm : Π {x y}, ring_con_gen.rel x y → ring_con_gen.rel y x | trans : Π {x y z}, ring_con_gen.rel x y → ring_con_gen.rel y z → ring_con_gen.rel x z | add : Π {w x y z}, ring_con_gen.rel w x → ring_con_gen.rel y z → ring_con_gen.rel (w + y) (x + z) | mul : Π {w x y z}, ring_con_gen.rel w x → ring_con_gen.rel y z → ring_con_gen.rel (w * y) (x * z) /-- The inductively defined smallest ring congruence relation containing a given binary relation. -/ def ring_con_gen [has_add R] [has_mul R] (r : R → R → Prop) : ring_con R := { r := ring_con_gen.rel r, iseqv := ⟨ring_con_gen.rel.refl, @ring_con_gen.rel.symm _ _ _ _, @ring_con_gen.rel.trans _ _ _ _⟩, add' := λ _ _ _ _, ring_con_gen.rel.add, mul' := λ _ _ _ _, ring_con_gen.rel.mul } namespace ring_con section basic variables [has_add R] [has_mul R] (c : ring_con R) /-- Every `ring_con` is also an `add_con` -/ def to_add_con : add_con R := { ..c } /-- Every `ring_con` is also a `con` -/ def to_con : con R := { ..c } /-- A coercion from a congruence relation to its underlying binary relation. -/ instance : has_coe_to_fun (ring_con R) (λ _, R → R → Prop) := ⟨λ c, c.r⟩ @[simp] lemma rel_eq_coe : c.r = c := rfl protected lemma refl (x) : c x x := c.refl' x protected lemma symm {x y} : c x y → c y x := c.symm' protected lemma trans {x y z} : c x y → c y z → c x z := c.trans' protected lemma add {w x y z} : c w x → c y z → c (w + y) (x + z) := c.add' protected lemma mul {w x y z} : c w x → c y z → c (w * y) (x * z) := c.mul' @[simp] lemma rel_mk {s : setoid R} {ha hm a b} : ring_con.mk s ha hm a b ↔ setoid.r a b := iff.rfl instance : inhabited (ring_con R) := ⟨ring_con_gen empty_relation⟩ end basic section quotient section basic variables [has_add R] [has_mul R] (c : ring_con R) /-- Defining the quotient by a congruence relation of a type with addition and multiplication. -/ protected def quotient := quotient c.to_setoid /-- Coercion from a type with addition and multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ instance : has_coe_t R c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient by a decidable congruence relation has decidable equality. -/ -- Lower the priority since it unifies with any quotient type. @[priority 500] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq R c.to_setoid d @[simp] lemma quot_mk_eq_coe (x : R) : quot.mk c x = (x : c.quotient) := rfl /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp] protected lemma eq {a b : R} : (a : c.quotient) = b ↔ c a b := quotient.eq' end basic /-! ### Basic notation The basic algebraic notation, `0`, `1`, `+`, `*`, `-`, `^`, descend naturally under the quotient -/ section data section add_mul variables [has_add R] [has_mul R] (c : ring_con R) instance : has_add c.quotient := c.to_add_con.has_add @[simp, norm_cast] lemma coe_add (x y : R) : (↑(x + y) : c.quotient) = ↑x + ↑y := rfl instance : has_mul c.quotient := c.to_con.has_mul @[simp, norm_cast] lemma coe_mul (x y : R) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl end add_mul section zero variables [add_zero_class R] [has_mul R] (c : ring_con R) instance : has_zero c.quotient := c.to_add_con^.quotient.has_zero @[simp, norm_cast] lemma coe_zero : (↑(0 : R) : c.quotient) = 0 := rfl end zero section one variables [has_add R] [mul_one_class R] (c : ring_con R) instance : has_one c.quotient := c.to_con^.quotient.has_one @[simp, norm_cast] lemma coe_one : (↑(1 : R) : c.quotient) = 1 := rfl end one section smul variables [has_add R] [mul_one_class R] [has_smul α R] [is_scalar_tower α R R] (c : ring_con R) instance : has_smul α c.quotient := c.to_con.has_smul @[simp, norm_cast] lemma coe_smul (a : α) (x : R) : (↑(a • x) : c.quotient) = a • x := rfl end smul section neg_sub_zsmul variables [add_group R] [has_mul R] (c : ring_con R) instance : has_neg c.quotient := c.to_add_con^.has_neg @[simp, norm_cast] lemma coe_neg (x : R) : (↑(-x) : c.quotient) = -x := rfl instance : has_sub c.quotient := c.to_add_con^.has_sub @[simp, norm_cast] lemma coe_sub (x y : R) : (↑(x - y) : c.quotient) = x - y := rfl instance has_zsmul : has_smul ℤ c.quotient := c.to_add_con^.quotient.has_zsmul @[simp, norm_cast] lemma coe_zsmul (z : ℤ) (x : R) : (↑(z • x) : c.quotient) = z • x := rfl end neg_sub_zsmul section nsmul variables [add_monoid R] [has_mul R] (c : ring_con R) instance has_nsmul : has_smul ℕ c.quotient := c.to_add_con^.quotient.has_nsmul @[simp, norm_cast] lemma coe_nsmul (n : ℕ) (x : R) : (↑(n • x) : c.quotient) = n • x := rfl end nsmul section pow variables [has_add R] [monoid R] (c : ring_con R) instance : has_pow c.quotient ℕ := c.to_con^.nat.has_pow @[simp, norm_cast] lemma coe_pow (x : R) (n : ℕ) : (↑(x ^ n) : c.quotient) = x ^ n := rfl end pow section nat_cast variables [add_monoid_with_one R] [has_mul R] (c : ring_con R) instance : has_nat_cast c.quotient := ⟨λ n, ↑(n : R)⟩ @[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : (↑(n : R) : c.quotient) = n := rfl end nat_cast section int_cast variables [add_group_with_one R] [has_mul R] (c : ring_con R) instance : has_int_cast c.quotient := ⟨λ z, ↑(z : R)⟩ @[simp, norm_cast] lemma coe_int_cast (n : ℕ) : (↑(n : R) : c.quotient) = n := rfl end int_cast instance [inhabited R] [has_add R] [has_mul R] (c : ring_con R) : inhabited c.quotient := ⟨↑(default : R)⟩ end data /-! ### Algebraic structure The operations above on the quotient by `c : ring_con R` preseverse the algebraic structure of `R`. -/ section algebraic instance [non_unital_non_assoc_semiring R] (c : ring_con R) : non_unital_non_assoc_semiring c.quotient := function.surjective.non_unital_non_assoc_semiring _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [non_assoc_semiring R] (c : ring_con R) : non_assoc_semiring c.quotient := function.surjective.non_assoc_semiring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance [non_unital_semiring R] (c : ring_con R) : non_unital_semiring c.quotient := function.surjective.non_unital_semiring _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [semiring R] (c : ring_con R) : semiring c.quotient := function.surjective.semiring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance [comm_semiring R] (c : ring_con R) : comm_semiring c.quotient := function.surjective.comm_semiring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance [non_unital_non_assoc_ring R] (c : ring_con R) : non_unital_non_assoc_ring c.quotient := function.surjective.non_unital_non_assoc_ring _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [non_assoc_ring R] (c : ring_con R) : non_assoc_ring c.quotient := function.surjective.non_assoc_ring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) instance [non_unital_ring R] (c : ring_con R) : non_unital_ring c.quotient := function.surjective.non_unital_ring _ quotient.surjective_quotient_mk' rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance [ring R] (c : ring_con R) : ring c.quotient := function.surjective.ring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) instance [comm_ring R] (c : ring_con R) : comm_ring c.quotient := function.surjective.comm_ring _ quotient.surjective_quotient_mk' rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) instance is_scalar_tower_right [has_add R] [mul_one_class R] [has_smul α R] [is_scalar_tower α R R] (c : ring_con R) : is_scalar_tower α c.quotient c.quotient := { smul_assoc := λ a, quotient.ind₂' $ by exact λ m₁ m₂, congr_arg quotient.mk' $ smul_mul_assoc _ _ _ } instance smul_comm_class [has_add R] [mul_one_class R] [has_smul α R] [is_scalar_tower α R R] [smul_comm_class α R R] (c : ring_con R) : smul_comm_class α c.quotient c.quotient := { smul_comm := λ a, quotient.ind₂' $ by exact λ m₁ m₂, congr_arg quotient.mk' $ (mul_smul_comm _ _ _).symm } instance smul_comm_class' [has_add R] [mul_one_class R] [has_smul α R] [is_scalar_tower α R R] [smul_comm_class R α R] (c : ring_con R) : smul_comm_class c.quotient α c.quotient := by haveI := smul_comm_class.symm R α R; exact smul_comm_class.symm _ _ _ instance [monoid α] [non_assoc_semiring R] [distrib_mul_action α R] [is_scalar_tower α R R] (c : ring_con R) : distrib_mul_action α c.quotient := { smul := (•), smul_zero := λ r, congr_arg quotient.mk' $ smul_zero _, smul_add := λ r, quotient.ind₂' $ by exact λ m₁ m₂, congr_arg quotient.mk' $ smul_add _ _ _, .. c.to_con.mul_action } instance [monoid α] [semiring R] [mul_semiring_action α R] [is_scalar_tower α R R] (c : ring_con R) : mul_semiring_action α c.quotient := { smul := (•), .. c^.quotient.distrib_mul_action, .. c.to_con.mul_distrib_mul_action } end algebraic /-- The natural homomorphism from a ring to its quotient by a congruence relation. -/ def mk' [non_assoc_semiring R] (c : ring_con R) : R →+* c.quotient := { to_fun := quotient.mk', map_zero' := rfl, map_one' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl } end quotient end ring_con
a3c0faadbf78c8a12de3199be3e934419ccc81e4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/groupoid/vertex_group.lean
d4bbadc7c56150077d3f1ef4f3c2b2171498098e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,811
lean
/- Copyright (c) 2022 Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémi Bottinelli -/ import category_theory.groupoid import category_theory.path_category import algebra.group.defs import algebra.hom.group import algebra.hom.equiv.basic import combinatorics.quiver.path /-! # Vertex group > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the vertex group (*aka* isotropy group) of a groupoid at a vertex. ## Implementation notes * The instance is defined "manually", instead of relying on `category_theory.Aut.group` or using `category_theory.inv`. * The multiplication order therefore matches the categorical one : `x * y = x ≫ y`. * The inverse is directly defined in terms of the groupoidal inverse : `x ⁻¹ = groupoid.inv x`. ## Tags isotropy, vertex group, groupoid -/ namespace category_theory namespace groupoid universes u v variables {C : Type u} [groupoid C] /-- The vertex group at `c`. -/ @[simps] instance vertex_group (c : C): group (c ⟶ c) := { mul := λ (x y : c ⟶ c), x ≫ y, mul_assoc := category.assoc, one := 𝟙 c, one_mul := category.id_comp, mul_one := category.comp_id, inv := groupoid.inv, mul_left_inv := inv_comp } /-- The inverse in the group is equal to the inverse given by `category_theory.inv`. -/ lemma vertex_group.inv_eq_inv (c : C) (γ : c ⟶ c) : γ ⁻¹ = category_theory.inv γ := groupoid.inv_eq_inv γ /-- An arrow in the groupoid defines, by conjugation, an isomorphism of groups between its endpoints. -/ @[simps] def vertex_group_isom_of_map {c d : C} (f : c ⟶ d) : (c ⟶ c) ≃* (d ⟶ d) := { to_fun := λ γ, inv f ≫ γ ≫ f, inv_fun := λ δ, f ≫ δ ≫ inv f, left_inv := λ γ, by simp_rw [category.assoc, comp_inv, category.comp_id, ←category.assoc, comp_inv, category.id_comp], right_inv := λ δ, by simp_rw [category.assoc, inv_comp, ←category.assoc, inv_comp, category.id_comp, category.comp_id], map_mul' := λ γ₁ γ₂, by simp only [vertex_group_mul, inv_eq_inv, category.assoc, is_iso.hom_inv_id_assoc] } /-- A path in the groupoid defines an isomorphism between its endpoints. -/ def vertex_group_isom_of_path {c d : C} (p : quiver.path c d) : (c ⟶ c) ≃* (d ⟶ d) := vertex_group_isom_of_map (compose_path p) /-- A functor defines a morphism of vertex group. -/ @[simps] def _root_.category_theory.functor.map_vertex_group {D : Type v} [groupoid D] (φ : C ⥤ D) (c : C) : (c ⟶ c) →* (φ.obj c ⟶ φ.obj c) := { to_fun := φ.map, map_one' := φ.map_id c, map_mul' := φ.map_comp } end groupoid end category_theory
935eb12b73b00006dd1fd1c7ca54e813dc3f1bb1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/stone_cech.lean
d8f7cc15fb3bcfdecaa150c19459ad058086de75
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,180
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.bases import topology.dense_embedding /-! # Stone-Čech compactification > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ noncomputable theory open filter set open_locale topology universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := range $ λ s : set α, {u | s ∈ u} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem ua ub, assume v hv, ⟨_, _⟩⟩; apply mem_of_superset hv; simp [inter_subset_right a b] end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq_univ_of_forall (λ u, univ_mem)⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u} := ultrafilter_basis_is_basis.is_open ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u} := begin rw ← is_open_compl_iff, convert ultrafilter_is_open_basic sᶜ, ext u, exact ultrafilter.compl_mem_iff_not_mem.symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : ↑u ≤ 𝓝 x ↔ x = mjoin u := begin rw [eq_comm, ← ultrafilter.coe_le_coe], change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, {v : ultrafilter α | s ∈ v} ∈ u, simp only [topological_space.nhds_generate_from, le_infi_iff, ultrafilter_basis, le_principal_iff, mem_set_of_eq], split, { intros h a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros h a ⟨xi, a, rfl⟩, exact h _ xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨is_compact_iff_ultrafilter_le_nhds.mpr $ assume f _, ⟨mjoin f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume x y f fx fy, have hx : x = mjoin f, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin f, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm instance : totally_disconnected_space (ultrafilter α) := begin rw totally_disconnected_space_iff_connected_component_singleton, intro A, simp only [set.eq_singleton_iff_unique_mem, mem_connected_component, true_and], intros B hB, rw ← ultrafilter.coe_le_coe, intros s hs, rw [connected_component_eq_Inter_clopen, set.mem_Inter] at hB, let Z := { F : ultrafilter α | s ∈ F }, have hZ : is_clopen Z := ⟨ultrafilter_is_open_basic s, ultrafilter_is_closed_basic s⟩, exact hB ⟨Z, hZ, hs⟩, end lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine infi_le_of_le {u | s ∈ u} _, refine infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, exact principal_mono.2 (λ a, id) end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α) := singleton_mem_pure, rw h at this, exact (mem_singleton_iff.mp (mem_pure.mp this)).symm end open topological_space /-- The range of `pure : α → ultrafilter α` is dense in `ultrafilter α`. -/ lemma dense_range_pure : dense_range (pure : α → ultrafilter α) := λ x, mem_closure_iff_ultrafilter.mpr ⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩ /-- The map `pure : α → ultra_filter α` induces on `α` the discrete topology. -/ lemma induced_topology_pure : topological_space.induced (pure : α → ultrafilter α) ultrafilter.topological_space = ⊥ := begin apply eq_bot_of_singletons_open, intros x, use [{u : ultrafilter α | {x} ∈ u}, ultrafilter_is_open_basic _], simp, end /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact ⟨⟨induced_topology_pure.symm⟩, dense_range_pure⟩ -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, haveI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap pure (𝓝 b)) (𝓝 c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := is_compact_univ.ultrafilter_le_nhds (b.map f) (by rw [le_principal_iff]; exact univ_mem) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, haveI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : ↑b' ≤ 𝓝 b, from ultrafilter_converges_iff.mpr (bind_pure _).symm, rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) ↑b, rw ultrafilter_extend_extends, exact le_rfl end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma dense_range_stone_cech_unit : dense_range (stone_cech_unit : α → stone_cech α) := dense_range_pure.quotient section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {γ' : Type u} [topological_space γ'] [t2_space γ'] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) lemma stone_cech_hom_ext {g₁ g₂ : stone_cech α → γ'} (h₁ : continuous g₁) (h₂ : continuous g₂) (h : g₁ ∘ stone_cech_unit = g₂ ∘ stone_cech_unit) : g₁ = g₂ := begin apply continuous.ext_on dense_range_stone_cech_unit h₁ h₂, rintros x ⟨x, rfl⟩, apply (congr_fun h x) end end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : ↑u ≤ 𝓝 x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g gx, have ↑(g.map pure) ≤ 𝓝 g, by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g.map stone_cech_unit : filter (stone_cech α)) ≤ 𝓝 ⟦g⟧, from continuous_at_iff_ultrafilter.mp (continuous_quotient_mk.tendsto g) _ this, by rwa (show ⟦g⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros ⟨x⟩ ⟨y⟩ g gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim := λ (z : ultrafilter α) (gz : (g : filter (stone_cech α)) ≤ 𝓝 ⟦z⟧), ((continuous_stone_cech_extend hf).tendsto _).mono_left gz, exact tendsto_nhds_unique (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
b7608e7dd6caf0376f48a26bad6fe69b247e0938
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Parser/Basic.lean
677ef83e183e17e3e686399c046338d31d3b5fec
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
76,443
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.Trie import Lean.Data.Position import Lean.Syntax import Lean.ToExpr import Lean.Environment import Lean.Attributes import Lean.Message import Lean.Compiler.InitAttr import Lean.ResolveName /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /- Return character after position `pos` -/ def getNext (input : String) (pos : Nat) : Char := input.get (input.next pos) /- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := eval_prec max def argPrec : Nat := eval_prec arg def leadPrec : Nat := eval_prec lead def minPrec : Nat := eval_prec min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := Std.PersistentHashMap.insert s k () /- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable quotDepth : Nat := 0 suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] /-- Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser` for the use of `checkLhsPrec` in trailing parsers. Note that with chaining, the preceding parser can be another trailing parser: in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/ lhsPrec : Nat := 0 pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : Nat) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, use `missing` instead. -- Thus we ensure the property that an syntax tree contains (at least) one `missing` node -- if (and only if) there was a parse error. -- We should not create an actual node of kind `k` in this case because it would mean we -- choose an "arbitrary" node (in practice the last one) in an alternative of the form -- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we -- instead return a less misleading single `missing` node without randomly selecting any `ki`. let stack := stack.push Syntax.missing ⟨stack, lhsPrec, pos, cache, err⟩ else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink (iniStackSz - 1) let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def setError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩ def mkEOIError (s : ParserState) (expected : List String := []) : ParserState := s.mkUnexpectedError "unexpected end of input" expected def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) (p : Parser) : Parser where fn := dbgTraceStateFn label p.fn info := p.info @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s => if p s.stxStack.back then s else s.mkUnexpectedError msg @[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } @[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser where andThen a b := andthen a (b ()) @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } @[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg @[inline] def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } /- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.hasError then s else { s with lhsPrec := prec } @[inline] def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := setLhsPrecFn prec } def checkInsideQuotFn : ParserFn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax outside syntax quotation" @[inline] def checkInsideQuot : Parser := { info := epsilonInfo, fn := checkInsideQuotFn } def checkOutsideQuotFn : ParserFn := fun c s => if !c.quotDepth == 0 || c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax inside syntax quotation" @[inline] def checkOutsideQuot : Parser := { info := epsilonInfo, fn := checkOutsideQuotFn } def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s => p { c with quotDepth := c.quotDepth + i |>.toNat } s @[inline] def incQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn 1 p.fn } @[inline] def decQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn (-1) p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors else s | none => s @[inline] def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q true @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser where orElse a b := orelse a (b ()) @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } @[inline] def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos @[inline] def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p c s @[inline] def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz @[inline] def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz @[inline] def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos s := sep c s if s.hasError then s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } @[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } @[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } @[inline] def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then eoi s else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then eoi s else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then eoi s else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) where eoi s := s.mkUnexpectedError "unterminated comment" /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == '\t' then s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let startPos := i let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens else andthenFn (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s @[inline] def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s def binNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.bsize ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk.bsize let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := do let input := c.input let i := s.pos if input.atEnd i then return s.mkEOIError let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if input.atEnd s.pos then return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart let stopPart := s.pos let s := s.next c.input s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s else let stx := s.stxStack.back match stx with | Syntax.ident info rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.mkNameLit rawStr.toString info) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some e := s.errorMsg then (s.restore iniSz iniPos, Except.error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, Except.ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, Except.ok tkc.token) else peekTokenAux c s /- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s @[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } @[inline] def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") @[inline] def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universe (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz @[inline] def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } @[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? $ fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } @[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] @[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s @[inline] def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } @[inline] def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec p c s match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | none, some _ => -- prev succeeded, current failed ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio) else (s.mergeErrors prevSize oldError, prio) | some _, none => -- prev failed, current succeeded let successNode := s.stxStack.back let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack (s.pushSyntax successNode, prio) -- put successNode back on the stack def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s @[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg @[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } @[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg @[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } @[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.pos } s } @[inline] def withoutPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => let pos := c.fileMap.toPosition s.pos p.fn { c with savedPos? := none } s } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" @[inline] def eoi : Parser := { fn := eoiFn } open Std (RBMap RBMap.empty) /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq, Repr /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym) | Except.ok (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | Except.ok (Syntax.node k _) => find k | Except.ok _ => (s, []) | Except.error s' => (s', []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations @[inline] def termParser (prec : Nat := 0) : Parser := categoryParser `term prec /- ============== -/ /- Antiquotations -/ /- ============== -/ /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun c s => s.pushSyntax mkNullNode } -- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. Both forms can also be used with an appended `*` to turn them into an antiquotation "splice". If `kind` is given, it will additionally be checked when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser := let kind := (kind.getD Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := do if c.quotDepth == 0 then return false let (s, stx) := peekToken c s match stx with | Except.ok stx@(Syntax.atom _ sym) => sym == "$" | _ => false @[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ @[inline] def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } register_builtin_option internal.parseQuotWithCurrentStage : Bool := { defValue := false group := "internal" descr := "(Lean bootstrapping) use parsers from the current stage inside quotations" } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot && internal.parseQuotWithCurrentStage.get c.options && c.env.contains declName then evalParserConst declName c s else p.fn c s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ @[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos initStackSz @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : Type} {m : Type → Type} [Monad m] @[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b @[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) @[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
7dc2e0c940d50ad7a2281d43a29073c18e625236
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/regular.lean
63e4ed4ce88363b4b7f1080c21db430207959c69
[ "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
13,157
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group import algebra.group_power.basic import algebra.iterate_hom /-! # Regular elements We introduce left-regular, right-regular and regular elements. By definition, a regular element in a commutative ring is a non-zero divisor. Lemma `is_regular_of_ne_zero` implies that every non-zero element of an integral domain is regular. Since it assumes that the ring is a `cancel_monoid_with_zero` it applies also, for instance, to `ℕ`. The lemmas in Section `mul_zero_class` show that the `0` element is (left/right-)regular if and only if the `mul_zero_class` is trivial. This is useful when figuring out stopping conditions for regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence by adding one further `0`. The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors. -/ variables {R : Type*} {a b : R} section has_mul variable [has_mul R] /-- A left-regular element is an element `c` such that multiplication on the left by `c` is injective on the left. -/ def is_left_regular (c : R) := function.injective ((*) c) /-- A right-regular element is an element `c` such that multiplication on the right by `c` is injective on the right. -/ def is_right_regular (c : R) := function.injective (* c) /-- A regular element is an element `c` such that multiplication by `c` both on the left and on the right is injective. -/ structure is_regular (c : R) : Prop := (left : is_left_regular c) (right : is_right_regular c) end has_mul section semigroup variable [semigroup R] /-- In a semigroup, the product of left-regular elements is left-regular. -/ lemma is_left_regular.mul (lra : is_left_regular a) (lrb : is_left_regular b) : is_left_regular (a * b) := show function.injective ((*) (a * b)), from (comp_mul_left a b) ▸ lra.comp lrb /-- In a semigroup, the product of right-regular elements is right-regular. -/ lemma is_right_regular.mul (rra : is_right_regular a) (rrb : is_right_regular b) : is_right_regular (a * b) := show function.injective (* (a * b)), from (comp_mul_right b a) ▸ rrb.comp rra /-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular element, then `b` is left-regular. -/ lemma is_left_regular.of_mul (ab : is_left_regular (a * b)) : is_left_regular b := function.injective.of_comp (by rwa comp_mul_left a b) /-- An element is left-regular if and only if multiplying it on the left by a left-regular element is left-regular. -/ @[simp] lemma mul_is_left_regular_iff (b : R) (ha : is_left_regular a) : is_left_regular (a * b) ↔ is_left_regular b := ⟨λ ab, is_left_regular.of_mul ab, λ ab, is_left_regular.mul ha ab⟩ /-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular element, then `b` is right-regular. -/ lemma is_right_regular.of_mul (ab : is_right_regular (b * a)) : is_right_regular b := begin refine λ x y xy, ab (_ : x * (b * a) = y * (b * a)), rw [← mul_assoc, ← mul_assoc], exact congr_fun (congr_arg has_mul.mul xy) a, end /-- An element is right-regular if and only if multiplying it on the right with a right-regular element is right-regular. -/ @[simp] lemma mul_is_right_regular_iff (b : R) (ha : is_right_regular a) : is_right_regular (b * a) ↔ is_right_regular b := ⟨λ ab, is_right_regular.of_mul ab, λ ab, is_right_regular.mul ab ha⟩ /-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a` are regular. -/ lemma is_regular_mul_and_mul_iff : is_regular (a * b) ∧ is_regular (b * a) ↔ is_regular a ∧ is_regular b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, exact ⟨⟨is_left_regular.of_mul ba.left, is_right_regular.of_mul ab.right⟩, ⟨is_left_regular.of_mul ab.left, is_right_regular.of_mul ba.right⟩⟩ }, { rintros ⟨ha, hb⟩, exact ⟨⟨(mul_is_left_regular_iff _ ha.left).mpr hb.left, (mul_is_right_regular_iff _ hb.right).mpr ha.right⟩, ⟨(mul_is_left_regular_iff _ hb.left).mpr ha.left, (mul_is_right_regular_iff _ ha.right).mpr hb.right⟩⟩ } end /-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/ lemma is_regular.and_of_mul_of_mul (ab : is_regular (a * b)) (ba : is_regular (b * a)) : is_regular a ∧ is_regular b := is_regular_mul_and_mul_iff.mp ⟨ab, ba⟩ end semigroup section monoid variable [monoid R] /-- Any power of a left-regular element is left-regular. -/ lemma is_left_regular.pow (n : ℕ) (rla : is_left_regular a) : is_left_regular (a ^ n) := by simp only [is_left_regular, ← mul_left_iterate, rla.iterate n] /-- Any power of a right-regular element is right-regular. -/ lemma is_right_regular.pow (n : ℕ) (rra : is_right_regular a) : is_right_regular (a ^ n) := by { rw [is_right_regular, ← mul_right_iterate], exact rra.iterate n } /-- Any power of a regular element is regular. -/ lemma is_regular.pow (n : ℕ) (ra : is_regular a) : is_regular (a ^ n) := ⟨is_left_regular.pow n ra.left, is_right_regular.pow n ra.right⟩ /-- An element `a` is left-regular if and only if a positive power of `a` is left-regular. -/ lemma is_left_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_left_regular (a ^ n) ↔ is_left_regular a := begin refine ⟨_, is_left_regular.pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ'], exact is_left_regular.of_mul, end /-- An element `a` is right-regular if and only if a positive power of `a` is right-regular. -/ lemma is_right_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_right_regular (a ^ n) ↔ is_right_regular a := begin refine ⟨_, is_right_regular.pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ], exact is_right_regular.of_mul, end /-- An element `a` is regular if and only if a positive power of `a` is regular. -/ lemma is_regular.pow_iff {n : ℕ} (n0 : 0 < n) : is_regular (a ^ n) ↔ is_regular a := ⟨λ h, ⟨(is_left_regular.pow_iff n0).mp h.left, (is_right_regular.pow_iff n0).mp h.right⟩, λ h, ⟨is_left_regular.pow n h.left, is_right_regular.pow n h.right⟩⟩ end monoid section mul_zero_class variables [mul_zero_class R] /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular.subsingleton (h : is_left_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (zero_mul a) (zero_mul b).symm⟩ /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular.subsingleton (h : is_right_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (mul_zero a) (mul_zero b).symm⟩ /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular.subsingleton (h : is_regular (0 : R)) : subsingleton R := h.left.subsingleton /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular_zero_iff_subsingleton : is_left_regular (0 : R) ↔ subsingleton R := begin refine ⟨λ h, h.subsingleton, _⟩, intros H a b h, exact @subsingleton.elim _ H a b end /-- In a non-trivial `mul_zero_class`, the `0` element is not left-regular. -/ lemma not_is_left_regular_zero_iff : ¬ is_left_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_left_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular_zero_iff_subsingleton : is_right_regular (0 : R) ↔ subsingleton R := begin refine ⟨λ h, h.subsingleton, _⟩, intros H a b h, exact @subsingleton.elim _ H a b end /-- In a non-trivial `mul_zero_class`, the `0` element is not right-regular. -/ lemma not_is_right_regular_zero_iff : ¬ is_right_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_right_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular_iff_subsingleton : is_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.left.subsingleton, λ h, ⟨is_left_regular_zero_iff_subsingleton.mpr h, is_right_regular_zero_iff_subsingleton.mpr h⟩⟩ /-- A left-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_left_regular.ne_zero [nontrivial R] (la : is_left_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (la _), rw [zero_mul, zero_mul] end /-- A right-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_right_regular.ne_zero [nontrivial R] (ra : is_right_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (ra (_ : x * 0 = y * 0)), rw [mul_zero, mul_zero] end /-- A regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_regular.ne_zero [nontrivial R] (la : is_regular a) : a ≠ 0 := la.left.ne_zero /-- In a non-trivial ring, the element `0` is not left-regular -- with typeclasses. -/ lemma not_is_left_regular_zero [nR : nontrivial R] : ¬ is_left_regular (0 : R) := not_is_left_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not right-regular -- with typeclasses. -/ lemma not_is_right_regular_zero [nR : nontrivial R] : ¬ is_right_regular (0 : R) := not_is_right_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not regular -- with typeclasses. -/ lemma not_is_regular_zero [nontrivial R] : ¬ is_regular (0 : R) := λ h, is_regular.ne_zero h rfl end mul_zero_class section comm_semigroup variable [comm_semigroup R] /-- A product is regular if and only if the factors are. -/ lemma is_regular_mul_iff : is_regular (a * b) ↔ is_regular a ∧ is_regular b := begin refine iff.trans _ is_regular_mul_and_mul_iff, refine ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_semigroup section monoid variables [monoid R] /-- In a monoid, `1` is regular. -/ lemma is_regular_one : is_regular (1 : R) := ⟨λ a b ab, (one_mul a).symm.trans (eq.trans ab (one_mul b)), λ a b ab, (mul_one a).symm.trans (eq.trans ab (mul_one b))⟩ /-- An element admitting a left inverse is left-regular. -/ lemma is_left_regular_of_mul_eq_one (h : b * a = 1) : is_left_regular a := @is_left_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.left }) /-- An element admitting a right inverse is right-regular. -/ lemma is_right_regular_of_mul_eq_one (h : a * b = 1) : is_right_regular a := @is_right_regular.of_mul R _ a _ (by { rw h, exact is_regular_one.right }) /-- If `R` is a monoid, an element in `units R` is regular. -/ lemma units.is_regular (a : units R) : is_regular (a : R) := ⟨is_left_regular_of_mul_eq_one a.inv_mul, is_right_regular_of_mul_eq_one a.mul_inv⟩ /-- A unit in a monoid is regular. -/ lemma is_unit.is_regular (ua : is_unit a) : is_regular a := begin rcases ua with ⟨a, rfl⟩, exact units.is_regular a, end end monoid section left_or_right_cancel_semigroup /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element.", simps] def mul_left_embedding {G : Type*} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := mul_right_injective g } /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element.", simps] def mul_right_embedding {G : Type*} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := mul_left_injective g } /-- Elements of a left cancel semigroup are left regular. -/ lemma is_left_regular_of_left_cancel_semigroup [left_cancel_semigroup R] (g : R) : is_left_regular g := mul_right_injective g /-- Elements of a right cancel semigroup are right regular. -/ lemma is_right_regular_of_right_cancel_semigroup [right_cancel_semigroup R] (g : R) : is_right_regular g := mul_left_injective g end left_or_right_cancel_semigroup section cancel_monoid variables [cancel_monoid R] /-- Elements of a cancel monoid are regular. Cancel semigroups do not appear to exist. -/ lemma is_regular_of_cancel_monoid (g : R) : is_regular g := ⟨mul_right_injective g, mul_left_injective g⟩ end cancel_monoid section cancel_monoid_with_zero variables [cancel_monoid_with_zero R] /-- Non-zero elements of an integral domain are regular. -/ lemma is_regular_of_ne_zero (a0 : a ≠ 0) : is_regular a := ⟨λ b c, (mul_right_inj' a0).mp, λ b c, (mul_left_inj' a0).mp⟩ /-- In a non-trivial integral domain, an element is regular iff it is non-zero. -/ lemma is_regular_iff_ne_zero [nontrivial R] : is_regular a ↔ a ≠ 0 := ⟨is_regular.ne_zero, is_regular_of_ne_zero⟩ end cancel_monoid_with_zero
54a3b17fc7d1d0848b098387e8448d51dbae95ce
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/or_bot.lean
27076058f0be3dffacd4080a124e5c971dfbaae5
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
240
lean
import core.connectives namespace clfrags namespace hilbert namespace wr namespace or_bot axiom db₁ : Π {a : Prop}, or a bot → a end or_bot end wr end hilbert end clfrags
d1254676efc68d5e1287cf3e97958fd611271cd3
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-116.lean
aea55aa2e389bf75f00f394586f1901ae518b842
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
508
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import tactic.gptf import data.real.basic import data.real.sqrt example (k x: ℝ) (h₀ : x = (13 - real.sqrt 131) / 4) (h₁ : 2 * x ^ 2 - 13 * x + k = 0): k = 19/4 := begin rw h₀ at h₁, rw eq_comm.mp ( add_eq_zero_iff_neg_eq.mp h₁ ), norm_num, rw pow_two, rw mul_sub, rw [sub_mul, sub_mul], rw real.mul_self_sqrt _, ring, linarith, end
94601f19fc41e44b1e018909a127c3c1d5360b15
f3bade00efffc20399e2ac0a6b2e7726e8f9920e
/examples/lean/setoid.lean
928a24b44d436907e9bdeb9079890200f5b0ee80
[ "Apache-2.0" ]
permissive
leanparikshit/lean
466542d4e183361d28404b3a91412f2df2ead7e2
01eda46b69a87c8fe0eb764328eb1f526a587997
refs/heads/master
1,610,970,145,234
1,400,030,607,000
1,400,030,607,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,328
lean
-- Setoid example/test import macros definition reflexive {A : (Type U)} (r : A → A → Bool) := ∀ x, r x x definition symmetric {A : (Type U)} (r : A → A → Bool) := ∀ x y, r x y → r y x definition transitive {A : (Type U)} (r : A → A → Bool) := ∀ x y z, r x y → r y z → r x z -- We need to create a universe smaller than U for defining setoids. -- If we use (Type U) in the definition of setoid, then we will not be -- able to write s1 = s2 given s1 s2 : setoid. -- Writing the universes explicitily is really annoying. We should try to hide them. universe s ≥ 1 -- We currently don't have records. So, we use sigma types. definition setoid := sig A : (Type s), sig eq : A → A → Bool, (reflexive eq) # (symmetric eq) # (transitive eq) definition to_setoid (S : (Type s)) (eq : S → S → Bool) (Hrefl : reflexive eq) (Hsymm : symmetric eq) (Htrans : transitive eq) : setoid := pair S (pair eq (pair Hrefl (pair Hsymm Htrans))) -- The following definitions can be generated automatically. definition carrier (s : setoid) := proj1 s definition S_eq {s : setoid} : carrier s → carrier s → Bool := proj1 (proj2 s) infix 50 ≈ : S_eq definition S_refl {s : setoid} : ∀ x, x ≈ x := proj1 (proj2 (proj2 s)) definition S_symm {s : setoid} {x y : carrier s} : x ≈ y → y ≈ x := proj1 (proj2 (proj2 (proj2 s))) x y definition S_trans {s : setoid} {x y z : carrier s} : x ≈ y → y ≈ z → x ≈ z := proj2 (proj2 (proj2 (proj2 s))) x y z -- First example: the cross-product of two setoids is a setoid definition product (s1 s2 : setoid) : setoid := to_setoid (carrier s1 # carrier s2) (λ x y, proj1 x ≈ proj1 y ∧ proj2 x ≈ proj2 y) (take x, and_intro (S_refl (proj1 x)) (S_refl (proj2 x))) (take x y, assume H : proj1 x ≈ proj1 y ∧ proj2 x ≈ proj2 y, and_intro (S_symm (and_eliml H)) (S_symm (and_elimr H))) (take x y z, assume H1 : proj1 x ≈ proj1 y ∧ proj2 x ≈ proj2 y, assume H2 : proj1 y ≈ proj1 z ∧ proj2 y ≈ proj2 z, and_intro (S_trans (and_eliml H1) (and_eliml H2)) (S_trans (and_elimr H1) (and_elimr H2))) scope -- We need to extend the elaborator to be able to write -- p1 p2 : product s1 s2 set_option pp::implicit true check λ (s1 s2 : setoid) (p1 p2 : carrier (product s1 s2)), p1 ≈ p2 end definition morphism (s1 s2 : setoid) := sig f : carrier s1 → carrier s2, ∀ x y, x ≈ y → f x ≈ f y definition morphism_intro {s1 s2 : setoid} (f : carrier s1 → carrier s2) (H : ∀ x y, x ≈ y → f x ≈ f y) : morphism s1 s2 := pair f H definition f {s1 s2 : setoid} (m : morphism s1 s2) : carrier s1 → carrier s2 := proj1 m -- It would be nice to support (m.f x) as syntax sugar for (f m x) definition is_compat {s1 s2 : setoid} (m : morphism s1 s2) {x y : carrier s1} : x ≈ y → f m x ≈ f m y := proj2 m x y -- Second example: the composition of two morphism is a morphism definition compose {s1 s2 s3 : setoid} (m1 : morphism s1 s2) (m2 : morphism s2 s3) : morphism s1 s3 := morphism_intro (λ x, f m2 (f m1 x)) (take x y, assume Hxy : x ≈ y, have Hfxy : f m1 x ≈ f m1 y, from is_compat m1 Hxy, show f m2 (f m1 x) ≈ f m2 (f m1 y), from is_compat m2 Hfxy)
7e349a8615e1246fe8f4f82f002de4019a28f0f6
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/termparsertest1.lean
3ad94c1027d10641465cae82ef886f1c0db285b8
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,680
lean
import Lean.Parser.Term open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; stx ← IO.ofExcept $ runParserCategory env `term input "<input>"; IO.println stx def test (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParser input def testParserFailure (input : String) : IO Unit := do env ← mkEmptyEnvironment; match runParserCategory env `term input "<input>" with | Except.ok stx => throw (IO.userError ("unexpected success\n" ++ toString stx)) | Except.error msg => IO.println ("failed as expected, error: " ++ msg) def testFailures (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParserFailure input def main (xs : List String) : IO Unit := do test [ "`(a::b)", "match_syntax a with | `($f $a) => f | _ => Syntax.missing", "Prod.mk", "x.{u, v+1}", "x.{u}", "x", "x.{max u v}", "x.{max u v, 0}", "f 0 1", "f.{u+1} \"foo\" x", "(f x, 0, 1)", "()", "(f x)", "(f x : Type)", "h (f x) (g y)", "if x then f x else g x", "if h : x then f x h else g x h", "have p x y from f x; g this", "suffices h : p x y from f x; g this", "show p x y from f x", "fun x y => f y x", "fun (x y : Nat) => f y x", "fun (x, y) => f y x", "fun z (x, y) => f y x", "fun ⟨x, y⟩ ⟨z, w⟩ => f y x w z", "fun (Prod.mk x y) => f y x", "{ x := 10, y := 20 }", "{ x := 10, y := 20, }", "{ x // p x 10 }", "{ x : Nat // p x 10 }", "{ .. }", "{ Prod . fst := 10, .. }", "a[i]", "f [10, 20]", "g a[x+2]", "g f.a.1.2.bla x.1.a", "x+y*z < 10/3", "id (α := Nat) 10", "(x : a)", "a -> b", "{x : a} -> b", "{a : Type} -> [HasToString a] -> (x : a) -> b", "f ({x : a} -> b)", "f (x : a) -> b", "f ((x : a) -> b)", "(f : (n : Nat) → Vector Nat n) -> Nat", "∀ x y (z : Nat), x > y -> x > y - z", " match x with | some x => true | none => false", " match x with | some y => match y with | some (a, b) => a + b | none => 1 | none => 0 ", "Type u", "Sort v", "Type 1", "f Type 1", "let x := 0; x + 1", "let x : Nat := 0; x + 1", "let f (x : Nat) := x + 1; f 0", "let f {α : Type} (a : α) : α := a; f 10", "let f (x) := x + 1; f 10 + f 20", "let (x, y) := f 10; x + y", "let { fst := x, .. } := f 10; x + x", "let x.y := f 10; x", "let x.1 := f 10; x", "let x[i].y := f 10; x", "let x[i] := f 20; x", "-x + y", "!x", "¬ a ∧ b", " do x ← f a; x : Nat ← f a; g x; let y := g x; (a, b) <- h x y; let (a, b) := (b, a); pure (a + b)", "do { x ← f a; pure $ a + a }", "let f : Nat → Nat → Nat | 0, a => a + 10 | n+1, b => n * b; f 20", "max a b" ]; testFailures [ "f {x : a} -> b", "(x := 20)", "let x 10; x", "let x := y" ] #eval main []
f2f331c6ada997e2074e7d686c63b26829b97d0a
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/filter/basic.lean
49b4fc7c235c10626fa38a800fe2d02fd9768e0f
[ "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
99,231
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 -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ 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) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ 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 ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := 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, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma sInter_mem_sets_of_finite {s : set (set α)} (hfin : finite s) (h_in : ∀ U ∈ s, U ∈ f) : ⋂₀ s ∈ f := by { rw sInter_eq_bInter, exact Inter_mem_sets hfin h_in } lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨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) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], 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', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } 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 } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter 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} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], 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 ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, 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, x ∈ f := 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 := generate_sets g, 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)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } 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, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into 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 h, generate_sets.basic h, 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) (b ∈ g), 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 ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨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) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := 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 α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ 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.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.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.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⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ @[class] def ne_bot (f : filter α) := f ≠ ⊥ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := hf @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_not lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ne_bot_of_le_ne_bot hf hg lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg 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 α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : {i | i ∈ I} → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, apply sInter_mem_sets_of_finite (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype {i : ι | i ∈ I} := finite.fintype Ifin, exact finite_range _ } }, end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 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 (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) 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_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets), @nonempty_of_mem_sets _ _⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, 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 eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end 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 have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := ext $ λ t, by simp [mem_binfi h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f 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), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset ι, s ∈ ⨅i∈t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset (plift ι), s ∈ ⨅i∈t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup_sets, mem_join_sets] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_join_sets] 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.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (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 infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅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 /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] 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 /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (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 α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup_sets, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_principal_sets, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : sᶜ ∈ f) : f ⊓ 𝓟 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 ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h]) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := ⟨λ h, ⟨h.mono $ λ _, and.left, h.mono $ λ _, and.right⟩, λ h, h.1.and h.2⟩ lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := begin assume h', have := h.and h', simp only [and_not_self, eventually_false_iff_eq_bot] at this, contradiction end lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := (eventually_eq.refl l f).le @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ 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 (𝓟 s) = 𝓟 (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 eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, 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 /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, 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₂⟩ } @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- 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, ∃t∈ g, (∀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₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[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 ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨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_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {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 (𝓟 t) = 𝓟 (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⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] 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 @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[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 le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top 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 ∧ 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, comap_mono $ 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₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (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 image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : 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) (hsg : s ∈ g) (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) (hsg : s ∈ g) (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) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (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) (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) (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 subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := begin apply le_antisymm, { rw [map_le_iff_le_comap, comap_inf, comap_principal], have : (coe : s → α) ⁻¹' s = univ, by { ext x, simp }, rw [this, principal_univ], simp [le_refl _] }, { intros V V_in, rcases V_in with ⟨W, W_in, H⟩, rw mem_inf_sets, use [W, W_in, s, mem_principal_self s], erw [← image_subset_iff, subtype.image_preimage_coe] at H, exact H } end lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := let φ (x : s × s) : s.prod s := ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ in begin rw show (coe : s × s → α × α) = coe ∘ φ, by ext x; cases x; refl, rw [← filter.map_map, ← filter.comap_comap], rw map_comap_of_surjective, exact subtype_coe_map_comap _ _, exact λ ⟨⟨a, b⟩, ⟨ha, hb⟩⟩, ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩ end lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := hf.nonempty_of_mem (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[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_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := not_congr map_eq_bot_iff lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] 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 -- 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) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [mem_infi hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 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)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (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 map_inf_le (assume s hs, _), simp only [mem_inf_sets, exists_prop, mem_map, mem_preimage, 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 : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) 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), ⟨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, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, 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 ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀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) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨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, ∀u ∈ g, set.seq t u ∈ h) : 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 @[mono] 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, exact singleton_mem_pure_sets }, { 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 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 singleton_mem_pure_sets }, { 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 eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {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 principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list 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) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] 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 ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, 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 end list_traverse /-! ### Limits -/ /-- `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₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 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 γ} (hg : tendsto g y z) (hf : tendsto f x y) : 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.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono 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, tendsto_comap.comp h, 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) : 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, 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, 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.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] 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, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot hb.eq_bot lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ 𝓟 p) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { 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₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end /-! ### Products of filters -/ 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 localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, 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 comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (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 (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ 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₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (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₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (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.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ 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 ×ᶠ 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 β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (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 : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp only [← principal_singleton, prod_principal_principal, singleton_prod_singleton] lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := (not_congr prod_eq_bot).trans not_or_distrib lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ 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] end prod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h
3bb1f9452c2ec167a92af65d9703b7174c3c6473
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/measure_theory/lp_space.lean
dd734709fb3602b1f663b5fff0cf69747fc07430
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
49,474
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.ess_sup import measure_theory.ae_eq_fun import analysis.mean_inequalities /-! # ℒp space and Lp space This file describes properties of almost everywhere measurable functions with finite seminorm, denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`. The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm. The space `Lp α E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a metric space. TODO: prove that Lp is complete. ## Main definitions * `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable space and `F` is a normed group. * `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`. * `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ` for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`. * `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite p-seminorm for measure `μ` (`snorm f p μ < ∞`) * `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined as an `add_subgroup` of `α →ₘ[μ] E`. Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove that it is continuous. In particular, * `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map. * `Lp.pos_part` is the positive part of an `Lp` function. * `Lp.neg_part` is the negative part of an `Lp` function. ## Implementation Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to say that the coercion of `f` to a genuine function is measurable, instead of the non-working `f.measurable`. To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions coincide almost everywhere (this is registered as an `ext` rule). This can often be done using `filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h` could read (in the `Lp` namespace) ``` example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) := begin ext1, filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, add_assoc], end ``` The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the function coercion from the coercion to almost everywhere defined functions. -/ noncomputable theory open topological_space measure_theory open_locale nnreal ennreal big_operators lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := le_refl _ lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) := ennreal.coe_le_coe.2 (show (1 : nnreal) ≤ 2, by norm_num) lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := le_top local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] [normed_group G] open_locale ennreal namespace measure_theory section ℒp /-! ### ℒp seminorm We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential supremum (for which we use the notation `snorm_ess_sup f μ`). We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere measurable and has finite `snorm f p μ`. This paragraph is devoted to the basic properties of these definitions. It is constructed as follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense, deduce it for `snorm`, and translate it in terms of `mem_ℒp`. -/ section ℒp_space_definition /-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q) /-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/ def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ /-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to `ess_sup ∥f∥ μ` for `p = ∞`. -/ def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ := if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ) lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} : snorm f p μ = snorm' f (ennreal.to_real p) μ := by simp [snorm, hp_ne_zero, hp_ne_top] @[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm] /-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or `ess_sup f < ∞` if `p = ∞`. -/ def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop := ae_measurable f μ ∧ snorm f p μ < ∞ lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) : ae_measurable f μ := h.1 lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q := begin rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hq0_lt).symm, end end ℒp_space_definition section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2 lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2) lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q) (hfq : snorm' f q μ < ∞) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq), end end top section zero @[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 := by rw [snorm', div_zero, ennreal.rpow_zero] @[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 := by simp [snorm] lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ := by simp [mem_ℒp, snorm_exponent_zero] @[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 := by simp [snorm', hp0_lt] @[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 := begin cases le_or_lt 0 q with hq0 hq_neg, { exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), }, { simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], }, end @[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 := begin simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero], exact ess_sup_const_bot, end @[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ := ⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩ lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 := by simp [snorm', hq_pos] lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm'] lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ := by simp [snorm', hq_neg] @[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 := by simp [snorm_ess_sup] @[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, snorm', ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end end zero section const lemma snorm'_const (c : F) (hq_pos : 0 < q) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [hq_pos.le])], congr, rw ←ennreal.rpow_mul, suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm], end lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)], { congr, rw ←ennreal.rpow_mul, suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel hq_ne_zero], }, { rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq], split, { left, rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], }, { exact or.inl ennreal.coe_ne_top, }, }, end lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) : snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) := by rw [snorm_ess_sup, ess_sup_const _ hμ] lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) := by simp [snorm'_const c hq_pos, measure_univ] lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const c hμ], }, simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ := begin refine ⟨measurable_const.ae_measurable, _⟩, by_cases h0 : p = 0, { simp [h0], }, by_cases hμ : μ = 0, { simp [hμ], }, rw snorm_const c h0 hμ, refine ennreal.mul_lt_top ennreal.coe_lt_top _, refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), simp, end end const lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm' f q μ ≤ snorm' g q μ := begin rw [snorm'], refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq), refine lintegral_mono_ae (h.mono $ λ x hx, _), exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq end lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm' f q μ = snorm' g q μ := begin have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q), from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }), simp only [snorm', lintegral_congr_ae this] end lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ := snorm'_congr_norm_ae (hfg.fun_comp _) lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm_ess_sup f μ = snorm_ess_sup g μ := ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm)) lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm f p μ ≤ snorm g p μ := begin simp only [snorm], split_ifs, { exact le_rfl }, { refine ess_sup_mono_ae (h.mono $ λ x hx, _), exact_mod_cast hx }, { exact snorm'_mono_ae ennreal.to_real_nonneg h } end lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm f p μ = snorm g p μ := le_antisymm (snorm_mono_ae $ filter.eventually_eq.le hfg) (snorm_mono_ae $ (filter.eventually_eq.symm hfg).le) @[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ := snorm_congr_norm_ae $ filter.eventually_of_forall $ λ x, norm_norm _ lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ := snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl) lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ := by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg] lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ := (mem_ℒp_congr_ae hfg).1 hf_Lp lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ := ⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩ section opens_measurable_space variable [opens_measurable_space E] lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ := h.of_le h.ae_measurable.norm (filter.eventually_of_forall (λ x, by simp)) lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt] lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ] lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ) (h : snorm' f q μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm', ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff' hf.nnnorm.ennreal_coe.ennreal_rpow_const at h, refine h.left.mono (λ x hx, _), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exact absurd hx.left ennreal.coe_ne_top, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, exact hq0.not_lt h.right }, end lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) : snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩ lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) : ∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ := ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) @[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := by simp [filter.eventually_eq, snorm_ess_sup] lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) : snorm f p μ = 0 ↔ f =ᵐ[μ] 0 := begin by_cases h_top : p = ∞, { rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], }, rw snorm_eq_snorm' h0 h_top, exact snorm'_eq_zero_iff (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf, end end opens_measurable_space @[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup], }, simp [snorm_eq_snorm' h0 h_top], end section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ := ⟨ae_measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ℝ≥0∞), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm'}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.nnnorm.ennreal_coe ae_measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} : snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) := begin have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ, { refine lintegral_mono_ae _, have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ, refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), }, rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)], nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm, rw [ennreal.rpow_mul, one_div, ←@ennreal.mul_rpow_of_nonneg _ _ q⁻¹ (by simp [hq_pos.le])], refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]), rwa lintegral_const at h_le, end lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ := begin have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] : snorm' f q μ ≤ snorm_ess_sup f μ := le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ])) lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ←ne.def at hp0, by_cases hq_top : q = ∞, { by_cases hp_top : p = ∞, { rw [hq_top, hp_top], exact le_refl _, }, { have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top], refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _), simp [measure_univ], }, }, { have hp_top : p ≠ ∞, { by_contra hp_eq_top, push_neg at hp_eq_top, refine hq_top _, rwa [hp_eq_top, top_le_iff] at hpq, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top], exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, }, end lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) : snorm' f p μ < ∞ := begin cases le_or_lt p 0 with hp_nonpos hp_pos, { rw le_antisymm hp_nonpos hp_nonneg, simp, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, calc snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf ... < ∞ : begin rw ennreal.mul_lt_top_iff, refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩, rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], end end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, by_cases hp0 : p = 0, { rwa [hp0, mem_ℒp_zero_iff_ae_measurable], }, rw ←ne.def at hp0, refine ⟨hfq_m, _⟩, by_cases hp_top : p = ∞, { have hq_top : q = ∞, by rwa [hp_top, top_le_iff] at hpq, rw [hp_top], rwa hq_top at hfq_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, by_cases hq_top : q = ∞, { rw snorm_eq_snorm' hp0 hp_top, rw [hq_top, snorm_exponent_top] at hfq_lt_top, refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _, refine ennreal.mul_lt_top hfq_lt_top _, exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), }, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw snorm_eq_snorm' hp0 hp_top, rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top, exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real, end lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) : snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [le_trans zero_le_one hq1]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm' f q μ + snorm' g q μ : ennreal.lintegral_Lp_add_le hf.nnnorm.ennreal_coe hg.nnnorm.ennreal_coe hq1 lemma snorm_ess_sup_add_le {f g : α → F} : snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ := begin refine le_trans (ess_sup_mono_ae (filter.eventually_of_forall (λ x, _))) (ennreal.ess_sup_add_le _ _), simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _, end lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_add_le], }, have hp1_real : 1 ≤ p.to_real, by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top], repeat { rw snorm_eq_snorm' hp0 hp_top, }, exact snorm'_add_le hf hg hp1_real, end lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) : snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ) (λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1)) (λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) : snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ) (λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1) (λ x y, ae_measurable.add) _ hfs lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) (hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ := lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩) lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) : snorm' (f + g) q μ < ∞ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [hq_pos.le]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) (lintegral_mono (λ a, _)) (by simp [hq_pos.le]), exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1, end ... < ∞ : begin refine @ennreal.rpow_lt_top_of_nonneg _ (1/q) (by simp [hq_pos.le]) _, rw [lintegral_add' hf.nnnorm.ennreal_coe.ennreal_rpow_const hg.nnnorm.ennreal_coe.ennreal_rpow_const, ennreal.add_ne_top, ←lt_top_iff_ne_top, ←lt_top_iff_ne_top], exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm, lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩, end lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : snorm (f + g) p μ < ∞ := begin by_cases h0 : p = 0, { simp [h0], }, rw ←ne.def at h0, cases le_total 1 p with hp1 hp1, { exact snorm_add_lt_top_of_one_le hf hg hp1, }, have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne, have hp_pos : 0 < p.to_real, { rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top], exact ((zero_le p).lt_of_ne h0.symm), }, have hp1_real : p.to_real ≤ 1, { rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], }, rw snorm_eq_snorm' h0 hp_top, rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg, exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real, end section second_countable_topology variable [second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ := ⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩ lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } end second_countable_topology end borel_space section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq0_lt : 0 < q) : snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ := begin rw snorm', simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hq0_lt)], suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ = (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ, { apply_fun (λ x, x ^ (1/q)) at h_integral, rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [le_of_lt hq0_lt])], congr, simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hq0_lt).symm, ennreal.rpow_one], }, rw lintegral_const_mul', rw ennreal.coe_rpow_of_nonneg _ hq0_lt.le, exact ennreal.coe_ne_top, end lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) : snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ := by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul] lemma snorm_const_smul {f : α → F} (c : 𝕜) : snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const_smul], }, repeat { rw snorm_eq_snorm' h0 h_top, }, rw ←ne.def at h0, exact snorm'_const_smul c (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩), end lemma mem_ℒp.const_smul [borel_space E] {f : α → E} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (c • f) p μ := ⟨ae_measurable.const_smul hf.1 c, lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩ lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜] {f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ := hf.const_smul c lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {p q r : ℝ} {f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ := begin simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.nnnorm.ennreal_coe hf.nnnorm.ennreal_coe, end end normed_space section monotonicity lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin lift c to ℝ≥0 using hc, rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)], swap, apply_instance, refine snorm_mono_ae _, simpa end lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) : snorm f p μ = 0 ∧ snorm g p μ = 0 := begin suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0, by simp [snorm_congr_ae this.1, snorm_congr_ae this.2], refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩, { refine norm_le_zero_iff.1 (hx.trans _), exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) }, { refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc), exact (norm_nonneg _).trans hx } end lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin cases le_or_lt 0 c with hc hc, { exact snorm_le_mul_snorm_aux_of_nonneg h hc p }, { simp [snorm_le_mul_snorm_aux_of_neg h hc p] } end lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : mem_ℒp f p μ := begin simp only [mem_ℒp, hf, true_and], apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p), simp [lt_top_iff_ne_top, hg.snorm_ne_top], end end monotonicity end ℒp /-! ### Lp space The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`. -/ @[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) : snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ := snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _) lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) : snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ := by simp [hfp.2] /-- Lp space -/ def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [second_countable_topology E] (p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) := { carrier := {f | snorm f p μ < ∞}, zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero], add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _), snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩], neg_mem' := λ f hf, by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] } notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ namespace mem_ℒp variables [borel_space E] [second_countable_topology E] /-- make an element of Lp from a function verifying `mem_ℒp` -/ def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ := ⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩ lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g := by simp [to_Lp] @[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := by { convert hf.to_Lp_add hg.neg, exact sub_eq_add_neg f g } end mem_ℒp namespace Lp variables [borel_space E] [second_countable_topology E] instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩ @[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g := begin cases f, cases g, simp only [subtype.mk_eq_mk], exact ae_eq_fun.ext h end lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g := ⟨λ h, by rw h, λ h, ext h⟩ lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _ lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ := by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable] lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ := λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2 @[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl @[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl @[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f := by { cases f, simp [mem_ℒp.to_Lp] } lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩ variables (E p μ) lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {E p μ} lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _ lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _ lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] : @ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ := (mem_ℒp_const c).snorm_mk_lt_top instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) } instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥} instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) } lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl @[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) : ∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) := by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)] lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real := begin simp_rw [dist, norm_def], congr' 1, apply snorm_congr_ae (coe_fn_sub _ _), end lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ := begin simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)], exact snorm_congr_ae (coe_fn_sub _ _) end @[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ := by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) } @[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) : edist (hf.to_Lp f) 0 = snorm f p μ := by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp } @[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 := begin change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0, simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero] end lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 := begin refine ⟨λ hf, _, λ hf, by simp [hf]⟩, rw [norm_def, ennreal.to_real_eq_zero_iff] at hf, cases hf, { rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf, exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), }, { exact absurd hf (snorm_ne_top f), }, end lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 := begin split, { assume h, rw h, exact ae_eq_fun.coe_fn_const _ _ }, { assume h, ext1, filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)], assume a ha h'a, rw ha, exact h'a.symm } end @[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ := by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg] lemma norm_le_mul_norm_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ := begin by_cases pzero : p = 0, { simp [pzero, norm_def] }, cases le_or_lt 0 c with hc hc, { have := snorm_le_mul_snorm_aux_of_nonneg h hc p, rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this, { exact this }, { exact (Lp.mem_ℒp _).snorm_ne_top }, { simp [(Lp.mem_ℒp _).snorm_ne_top] } }, { have := snorm_le_mul_snorm_aux_of_neg h hc p, simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this, simp [this] } end lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ := begin rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)], exact snorm_mono_ae h end lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) := normed_group.of_core _ { norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp), triangle := begin assume f g, simp only [norm_def], rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g), suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ, { rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)), exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, }, rw [snorm_congr_ae (coe_fn_add _ _)], exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp, end, norm_neg := by simp } instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ := begin rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul, ennreal.mul_lt_top_iff], exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩, end instance : has_scalar 𝕜 (Lp E p μ) := { smul := λ c f, ⟨c • ↑f, mem_Lp_const_smul c f⟩ } lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ instance : semimodule 𝕜 (Lp E p μ) := { one_smul := λ _, subtype.eq (one_smul 𝕜 _), mul_smul := λ _ _ _, subtype.eq (mul_smul _ _ _), smul_add := λ _ _ _, subtype.eq (smul_add _ _ _), smul_zero := λ _, subtype.eq (smul_zero _), add_smul := λ _ _ _, subtype.eq (add_smul _ _ _), zero_smul := λ _, subtype.eq (zero_smul _ _) } lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ := by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c, ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def] instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) := { norm_smul_le := λ _ _, by simp [norm_const_smul] } instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance end normed_space end Lp namespace mem_ℒp variables [borel_space E] [second_countable_topology E] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) : (hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl end mem_ℒp end measure_theory open measure_theory /-! ### Composition on `L^p` We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize this to the composition with continuous linear maps, and to the definition of the positive part of an `L^p` function. -/ section composition variables [second_countable_topology E] [borel_space E] [second_countable_topology F] [measurable_space F] [borel_space F] {g : E → F} {c : nnreal} namespace lipschitz_with /-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well defined as an element of `Lp`. -/ def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ := ⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E), begin suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥, { exact Lp.mem_Lp_of_ae_le_mul this }, filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)], assume a ha, simp only [ha], rw [← dist_zero_right, ← dist_zero_right, ← g0], exact hg.dist_le_mul (f a) 0, end⟩ lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : hg.comp_Lp g0 f =ᵐ[μ] g ∘ f := ae_eq_fun.coe_fn_comp _ _ _ @[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) : hg.comp_Lp g0 (0 : Lp E p μ) = 0 := begin rw Lp.eq_zero_iff_ae_eq_zero, apply (coe_fn_comp_Lp _ _ _).trans, filter_upwards [Lp.coe_fn_zero E p μ], assume a ha, simp [ha, g0] end lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) : ∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ := begin apply Lp.norm_le_mul_norm_of_ae_le_mul, filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f', Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'], assume a ha1 ha2 ha3 ha4, simp [ha1, ha2, ha3, ha4, ← dist_eq_norm], exact hg.dist_le_mul (f a) (f' a) end lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : ∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ := by simpa using hg.norm_comp_Lp_sub_le g0 f 0 lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le] lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := (lipschitz_with_comp_Lp hg g0).continuous end lipschitz_with namespace continuous_linear_map variables [normed_space ℝ E] [normed_space ℝ F] /-- Composing `f : Lp ` with `L : E →L[ℝ] F`. -/ def comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : Lp F p μ := L.lipschitz.comp_Lp (map_zero L) f lemma coe_fn_comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : ∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) := lipschitz_with.coe_fn_comp_Lp _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `Lp E p μ`. -/ def comp_Lpₗ (L : E →L[ℝ] F) : (Lp E p μ) →ₗ[ℝ] (Lp F p μ) := { to_fun := λ f, L.comp_Lp f, map_add' := begin intros f g, ext1, filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f, coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)], assume a ha1 ha2 ha3 ha4 ha5, simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply], end, map_smul' := begin intros c f, ext1, filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f), coe_fn_comp_Lp L f], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply], end } variables {μ p} lemma norm_comp_Lp_le (L : E →L[ℝ] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ := lipschitz_with.norm_comp_Lp_le _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `Lp E p μ`. -/ def comp_LpL [fact (1 ≤ p)] (L : E →L[ℝ] F) : (Lp E p μ) →L[ℝ] (Lp F p μ) := linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[ℝ] F) : ∥L.comp_LpL p μ∥ ≤ ∥L∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end continuous_linear_map namespace measure_theory namespace Lp section pos_part lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) := lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs] /-- Positive part of a function in `L^p`. -/ def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ := lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f /-- Negative part of a function in `L^p`. -/ def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (coe_fn_neg_part_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) := lipschitz_with.continuous_comp_Lp _ _ lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) := have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part end Lp end measure_theory end composition
2391b4206349cdba3dfb16954651f37f0db58300
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/set/function.lean
30f445019479063e2dffb62a2c3820ac599ccf1c
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
12,408
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu Functions over sets. -/ import data.set.basic logic.function open function namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} /- maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (a : set α) (b : set β) : Prop := a ⊆ f ⁻¹' b theorem maps_to' (f : α → β) (a : set α) (b : set β) : maps_to f a b ↔ f '' a ⊆ b := image_subset_iff.symm theorem maps_to_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : maps_to f1 a b) : maps_to f2 a b := λ x h, by rw [mem_preimage, ← h₁ _ h]; exact h₂ h theorem maps_to_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : maps_to g b c) (h₂ : maps_to f a b) : maps_to (g ∘ f) a c := λ x h, h₁ (h₂ h) theorem maps_to_univ (f : α → β) (a) : maps_to f a univ := λ x h, trivial theorem maps_to_image (f : α → β) (a : set α) : maps_to f a (f '' a) := by rw maps_to' theorem maps_to_range (f : α → β) (a : set α) : maps_to f a (range f) := by rw [← image_univ, maps_to']; exact image_subset _ (subset_univ _) theorem image_subset_of_maps_to_of_subset {f : α → β} {a c : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : c ⊆ a) : f '' c ⊆ b := λ y hy, let ⟨x, hx, heq⟩ := hy in by rw [←heq]; apply h₁; apply h₂; assumption theorem image_subset_of_maps_to {f : α → β} {a : set α} {b : set β} (h : maps_to f a b) : f '' a ⊆ b := image_subset_of_maps_to_of_subset h (subset.refl _) /- injectivity -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (a : set α) : Prop := ∀⦃x1 x2 : α⦄, x1 ∈ a → x2 ∈ a → f x1 = f x2 → x1 = x2 theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ _ h₁ _ _, false.elim h₁ theorem inj_on_of_eq_on {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : inj_on f1 a) : inj_on f2 a := λ _ _ h₁' h₂' heq, by apply h₂ h₁' h₂'; rw [h₁, heq, ←h₁]; repeat {assumption} theorem inj_on_of_inj_on_of_subset {f : α → β} {a b : set α} (h₁ : inj_on f b) (h₂ : a ⊆ b) : inj_on f a := λ _ _ h₁' h₂' heq, h₁ (h₂ h₁') (h₂ h₂') heq lemma injective_iff_inj_on_univ {f : α → β} : injective f ↔ inj_on f univ := iff.intro (λ h _ _ _ _ heq, h heq) (λ h _ _ heq, h trivial trivial heq) lemma inj_on_of_injective {α β : Type*} {f : α → β} (s : set α) (h : injective f) : inj_on f s := inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 h) (subset_univ s) theorem inj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on g b) (h₃: inj_on f a) : inj_on (g ∘ f) a := λ _ _ h₁' h₂' heq, by apply h₃ h₁' h₂'; apply h₂; repeat {apply h₁, assumption}; assumption lemma inj_on_comp_of_injective_left {g : β → γ} {f : α → β} {a : set α} (hg : injective g) (hf : inj_on f a) : inj_on (g ∘ f) a := inj_on_comp (maps_to_univ _ _) (injective_iff_inj_on_univ.mp hg) hf lemma inj_on_iff_injective {f : α → β} {s : set α} : inj_on f s ↔ injective (λ x:s, f x.1) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inv_fun_on_image [inhabited α] {β : Type v} {s t : set α} {f : α → β} (h : inj_on f s) (ht : t ⊆ s) : (inv_fun_on f s) '' (f '' t) = t := begin have A : ∀z, z ∈ t → ((inv_fun_on f s) ∘ f) z = z := λz hz, inv_fun_on_eq' h (ht hz), rw ← image_comp, ext, simp [A] {contextual := tt} end lemma inj_on_preimage {f : α → β} {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := begin intros s t hs ht hst, rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst] end lemma subset_image_iff {s : set α} {t : set β} (f : α → β) : t ⊆ f '' s ↔ ∃u⊆s, t = f '' u ∧ inj_on f u := begin split, { assume h, choose g hg using h, refine ⟨ {a | ∃ b (h : b ∈ t), g h = a }, _, set.ext $ assume b, ⟨_, _⟩, _⟩, { rintros a ⟨b, hb, rfl⟩, exact (hg hb).1 }, { rintros hb, exact ⟨g hb, ⟨b, hb, rfl⟩, (hg hb).2⟩ }, { rintros ⟨c, ⟨b, hb, rfl⟩, rfl⟩, rwa (hg hb).2 }, { rintros a₁ a₂ ⟨b₁, h₁, rfl⟩ ⟨b₂, h₂, rfl⟩ eq, rw [(hg h₁).2, (hg h₂).2] at eq, subst eq } }, { rintros ⟨u, hu, rfl, _⟩, exact image_subset _ hu } end lemma subset_range_iff {s : set β} (f : α → β) : s ⊆ set.range f ↔ ∃u, s = f '' u ∧ inj_on f u := by rw [← image_univ, subset_image_iff]; simp /- surjectivity -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (a : set α) (b : set β) : Prop := b ⊆ f '' a theorem surj_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : surj_on f1 a b) : surj_on f2 a b := λ _ h, let ⟨x, hx⟩ := h₂ h in ⟨x, hx.left, by rw [←h₁ _ hx.left]; exact hx.right⟩ theorem surj_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : surj_on g b c) (h₂ : surj_on f a b) : surj_on (g ∘ f) a c := λ z h, let ⟨y, hy⟩ := h₁ h, ⟨x, hx⟩ := h₂ hy.left in ⟨x, hx.left, calc g (f x) = g y : by rw [hx.right] ... = z : hy.right⟩ lemma surjective_iff_surj_on_univ {f : α → β} : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective {f : α → β} {s : set α} : surj_on f s univ ↔ surjective (λ x:s, f x.1) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma image_eq_of_maps_to_of_surj_on {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : surj_on f a b) : f '' a = b := eq_of_subset_of_subset (image_subset_of_maps_to h₁) h₂ /- bijectivity -/ /-- `f` is bijective from `a` to `b` if `f` is injective on `a` and `f '' a = b`. -/ @[reducible] def bij_on (f : α → β) (a : set α) (b : set β) : Prop := maps_to f a b ∧ inj_on f a ∧ surj_on f a b lemma maps_to_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : maps_to f a b := h.left lemma inj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : inj_on f a := h.right.left lemma surj_on_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : surj_on f a b := h.right.right lemma bij_on.mk {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : inj_on f a) (h₃ : surj_on f a b) : bij_on f a b := ⟨h₁, h₂, h₃⟩ theorem bij_on_of_eq_on {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : eq_on f1 f2 a) (h₂ : bij_on f1 a b) : bij_on f2 a b := let ⟨map, inj, surj⟩ := h₂ in ⟨maps_to_of_eq_on h₁ map, inj_on_of_eq_on h₁ inj, surj_on_of_eq_on h₁ surj⟩ lemma image_eq_of_bij_on {f : α → β} {a : set α} {b : set β} (h : bij_on f a b) : f '' a = b := image_eq_of_maps_to_of_surj_on h.left h.right.right theorem bij_on_comp {g : β → γ} {f : α → β} {a : set α} {b : set β} {c : set γ} (h₁ : bij_on g b c) (h₂: bij_on f a b) : bij_on (g ∘ f) a c := let ⟨gmap, ginj, gsurj⟩ := h₁, ⟨fmap, finj, fsurj⟩ := h₂ in ⟨maps_to_comp gmap fmap, inj_on_comp fmap ginj finj, surj_on_comp gsurj fsurj⟩ lemma bijective_iff_bij_on_univ {f : α → β} : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /- left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (g : β → α) (f : α → β) (a : set α) : Prop := ∀ x ∈ a, g (f x) = x theorem left_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : eq_on g1 g2 b) (h₃ : left_inv_on g1 f a) : left_inv_on g2 f a := λ x h, calc g2 (f x) = g1 (f x) : eq.symm $ h₂ _ (h₁ h) ... = x : h₃ _ h theorem left_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} (h₁ : eq_on f1 f2 a) (h₂ : left_inv_on g f1 a) : left_inv_on g f2 a := λ x h, calc g (f2 x) = g (f1 x) : congr_arg g (h₁ _ h).symm ... = x : h₂ _ h theorem inj_on_of_left_inv_on {g : β → α} {f : α → β} {a : set α} (h : left_inv_on g f a) : inj_on f a := λ x₁ x₂ h₁ h₂ heq, calc x₁ = g (f x₁) : eq.symm $ h _ h₁ ... = g (f x₂) : congr_arg g heq ... = x₂ : h _ h₂ theorem left_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : left_inv_on f' f a) (h₃ : left_inv_on g' g b) : left_inv_on (f' ∘ g') (g ∘ f) a := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (h₃ _ (h₁ h)) ... = x : h₂ _ h /- right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (g : β → α) (f : α → β) (b : set β) : Prop := left_inv_on f g b theorem right_inv_on_of_eq_on_left {g1 g2 : β → α} {f : α → β} {b : set β} (h₁ : eq_on g1 g2 b) (h₂ : right_inv_on g1 f b) : right_inv_on g2 f b := left_inv_on_of_eq_on_right h₁ h₂ theorem right_inv_on_of_eq_on_right {g : β → α} {f1 f2 : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : eq_on f1 f2 a) (h₃ : right_inv_on g f1 b) : right_inv_on g f2 b := left_inv_on_of_eq_on_left h₁ h₂ h₃ theorem surj_on_of_right_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g b a) (h₂ : right_inv_on g f b) : surj_on f a b := λ y h, ⟨g y, h₁ h, h₂ _ h⟩ theorem right_inv_on_comp {f' : β → α} {g' : γ → β} {g : β → γ} {f : α → β} {c : set γ} {b : set β} (g'cb : maps_to g' c b) (h₁ : right_inv_on f' f b) (h₂ : right_inv_on g' g c) : right_inv_on (f' ∘ g') (g ∘ f) c := left_inv_on_comp g'cb h₂ h₁ theorem right_inv_on_of_inj_on_of_left_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inj_on f a) (h₄ : left_inv_on f g b) : right_inv_on f g a := λ x h, h₃ (h₂ $ h₁ h) h (h₄ _ (h₁ h)) theorem eq_on_of_left_inv_of_right_inv {g₁ g₂ : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to g₂ b a) (h₂ : left_inv_on g₁ f a) (h₃ : right_inv_on g₂ f b) : eq_on g₁ g₂ b := λ y h, calc g₁ y = (g₁ ∘ f ∘ g₂) y : congr_arg g₁ (h₃ _ h).symm ... = g₂ y : h₂ _ (h₁ h) theorem left_inv_on_of_surj_on_right_inv_on {f : α → β} {g : β → α} {a : set α} {b : set β} (h₁ : surj_on f a b) (h₂ : right_inv_on f g a) : left_inv_on f g b := λ y h, let ⟨x, hx, heq⟩ := h₁ h in calc (f ∘ g) y = (f ∘ g ∘ f) x : congr_arg (f ∘ g) heq.symm ... = f x : congr_arg f (h₂ _ hx) ... = y : heq /- inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (a : set α) (b : set β) : Prop := left_inv_on g f a ∧ right_inv_on g f b theorem bij_on_of_inv_on {g : β → α} {f : α → β} {a : set α} {b : set β} (h₁ : maps_to f a b) (h₂ : maps_to g b a) (h₃ : inv_on g f a b) : bij_on f a b := ⟨h₁, inj_on_of_left_inv_on h₃.left, surj_on_of_right_inv_on h₂ h₃.right⟩ lemma range_restrict {α : Type*} {β : Type*} (f : α → β) (p : set α) : range (restrict f p) = f '' (p : set α) := by { ext x, simp [restrict], refl } end set
55c184e181c9c95fd03e177a829b3d931034b509
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/apps/topological_semantics.lean
943b020c01cf2fa6a5aa7269b7c44d529adcb052
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
1,051
lean
import defs topology.basic open nnf structure topo_model (α : Type) extends topological_space α := (v : ℕ → set α) (is_alex : ∀s, (∀t∈s, is_open t) → is_open (⋂₀ s)) @[simp] def topo_force {α : Type} (tm : topo_model α) : α → nnf → Prop | s (var n) := tm.v n s | s (neg n) := ¬ tm.v n s | s (and φ ψ) := topo_force s φ ∧ topo_force s ψ | s (or φ ψ) := topo_force s φ ∨ topo_force s ψ | s (box φ) := @interior _ tm.to_topological_space (λ a, topo_force a φ) s | s (dia φ) := @_root_.closure _ tm.to_topological_space (λ a, topo_force a φ) s def topo_sat {α : Type} (tm : topo_model α) (s) (Γ : list nnf) : Prop := ∀ φ ∈ Γ, topo_force tm s φ def topo_unsatisfiable (Γ : list nnf) : Prop := ∀ (α) (tm : topo_model α) s, ¬ topo_sat tm s Γ def topo_unsat_singleton {φ} : topo_unsatisfiable [φ] → ∀ (α) (tm : topo_model α) s, ¬ topo_force tm s φ := begin intro h, intros, intro hf, apply h, intros ψ hψ, rw list.mem_singleton at hψ, rw hψ, exact hf end
a7a5a973c194d82a9e003b4d175b200ddbd85fa2
e1440579fb0723caf9edf1ed07aee74bbf4f5ce7
/lean-experiments/stumps-learnable/src/stump/setup_measurable.lean
952b988dd701ae7a0ae9fe5addc830595e3ccaf0
[ "Apache-2.0" ]
permissive
palmskog/coq-proba
1ecc5b7f399894ea14d6094a31a063280a122099
f73e2780871e2a3dd83b7ce9d3aed19f499f07e5
refs/heads/master
1,599,620,504,720
1,572,960,008,000
1,572,960,008,000
221,326,479
0
0
Apache-2.0
1,573,598,769,000
1,573,598,768,000
null
UTF-8
Lean
false
false
11,013
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import .setup_definition .setup_properties open set open measure_theory open probability_measure open lattice local attribute [instance] classical.prop_decidable namespace stump variables (μ: probability_measure ℍ) (target: ℍ) lemma is_meas_to_target: is_measurable {a: nnreal | a ≤ target} := begin apply is_measurable_of_is_closed, have TEST: Icc 0 target = {a: nnreal | a ≤ target}, { unfold Icc, rw ext_iff, intro, simp at *, }, rw ← TEST, apply is_closed_Icc, end @[simp] lemma label_measurable: measurable (label target) := begin dunfold label, apply measurable.prod, apply measurable_id, unfold rle, unfold to_bool, apply measurable.if, apply is_meas_to_target, apply measurable_const, apply measurable_const, end lemma measurable_interval_function: ∀ f: nnreal → nnreal, (∀ x: nnreal, is_measurable (f ⁻¹' Iio x)) → measurable f := begin intros, have FOO:= borel_eq_generate_Iio nnreal, unfold measurable, unfold stump.meas_ℍ, rw FOO, apply measurable_generate_from, intros, unfold range at H, rw mem_set_of_eq at H, cases H, unfold is_measurable, unfold is_measurable at a, unfold stump.meas_ℍ at a, rw FOO at a, rw ← H_h, apply a, end lemma measurable_lt :let f := λ x: nnreal, μ (Icc 0 x) in ∀ y : nnreal, (∃ θ : nnreal, {x : nnreal | f x < y} = Ico 0 θ) ∨ {x : nnreal | f x < y} = ∅ ∨ (∃ θ : nnreal, {x : nnreal | f x < y} = Icc 0 θ) ∨ {x : nnreal | f x < y} = Ici 0 := begin intros f y, let S := {x : ℍ | f x < y}, have hm : monotone f, from assume a b hab, prob_mono _ (Icc_subset_Icc (by refl) hab), have hm' : ∀ {x y}, f x < f y → x < y, { by_contradiction, push_neg at a, choose x₀ y₀ hxy using a, rcases hxy with ⟨hxy₁,hxy₂⟩, have : f y₀ ≤ f x₀, from hm hxy₂, rw ←not_lt at this, exact this hxy₁, }, by_cases (∃ u, f(u) ≥ y), swap, push_neg at h, have hS : S = Ici 0, { ext z, dsimp [S, Ici], fsplit, assume h₁, by_contra, simp at *, assumption, assume h₁, apply h, }, right, right, right, assumption, let T := {x : ℍ | f x ≥ y}, have Tne : T ≠ ∅, { assume not, choose u hyp using h, have : u ∈ T, by assumption, finish, }, have Tbdbl : bdd_below T, from ⟨ 0 , assume y hy, zero_le _ ⟩, let θ := Inf T, have Sleθ : ∀ x ∈ S, x ≤ θ, { assume s hs, refine le_cInf Tne _, assume b hb, dsimp [T,S] at hb hs, suffices : f s < f b, exact le_of_lt (hm' this), exact lt_of_lt_of_le hs hb, }, by_cases case : (f θ < y), have hS : S = Icc 0 θ, from set.ext (assume x, iff.intro (assume h₁, ⟨ by simp , Sleθ _ h₁⟩) (assume h₂, lt_of_le_of_lt (hm h₂.2) case)), right, right, left, existsi θ, exact hS, have hS : S = Ico 0 θ, { ext x, fsplit, assume h₁, suffices : x ≠ θ, dsimp [Ico], refine ⟨ by simp , lt_of_le_of_ne (Sleθ _ h₁) this ⟩, assume not, have : θ ∉ S, from case, rw not at h₁, exact this h₁, assume h₁, dsimp [S,Ico] at h₁ ⊢, have : x ∉ T, assume not, have : θ ≤ x, from cInf_le Tbdbl not, replace h₁ := h₁.2, rw ←not_le at h₁, exact h₁ this, simp at this, assumption, }, left, existsi θ, exact hS, end lemma measurable_Icc_0_x: measurable (λ x: nnreal, μ (Icc 0 x)) := begin apply measurable_interval_function, intros, unfold set.preimage, unfold Iio, conv { congr, congr, funext, rw mem_set_of_eq, skip, }, have FOO := measurable_lt μ x, cases FOO, cases FOO, rw FOO_h, exact is_measurable_Ico, cases FOO, rw FOO, exact is_measurable.empty, cases FOO, cases FOO, rw FOO_h, apply is_measurable_of_is_closed, apply is_closed_Icc, rw FOO, have COMPL: (Ici (0: nnreal) = - Iio 0), { unfold Ici, unfold Iio, rw ext_iff, intro, rw mem_set_of_eq, rw compl_set_of, rw mem_set_of_eq, split; intro, simp, simp at a, tidy, }, rw COMPL, apply is_measurable.compl, exact is_measurable_Iio, end noncomputable def error1: nnreal → nnreal := λ h, μ (Icc 0 target) - μ (Icc 0 h) noncomputable def error2: nnreal → nnreal := λ h, μ (Icc 0 h) - μ (Icc 0 target) noncomputable def error_decomposed: nnreal → nnreal := λ h, ite (rle h target) (error1 μ target h) (error2 μ target h) lemma decompose_error: error μ target = error_decomposed μ target := begin funext, unfold error_decomposed, by_cases (rle h target = tt), { dedup, rw h_1, simp, unfold error1, rw error_interval_1, rw ← Icc_diff_Ioc 0 h target, have INCL: Icc 0 h ⊆ Icc 0 target, swap, { have FOO:= @measure_diff nnreal _ μ _ _ INCL _ _ _, unfold_coes, unfold_coes at FOO, rw FOO, rw ← ennreal.coe_eq_coe, rw to_nnreal_sub, exact to_measure_lt_top μ (Icc 0 target), exact to_measure_lt_top μ (Icc 0 h), apply is_measurable_of_is_closed, apply is_closed_Icc, apply is_measurable_of_is_closed, apply is_closed_Icc, exact probability_measure.to_measure_lt_top μ (Icc 0 h), }, { have H: h ≤ target, { unfold rle at h_1, tidy, }, unfold Icc, rw subset_def, intros, rw mem_set_of_eq, rw mem_set_of_eq at a, cases a, split, assumption, transitivity h; assumption, }, { tidy, }, repeat { unfold rle at h_1, tidy, }, }, { dedup, simp at h_1, rw h_1, simp, unfold error2, rw error_interval_2, rw ← Icc_diff_Ioc 0 target h, have INCL: Icc 0 target ⊆ Icc 0 h, swap, { have FOO:= @measure_diff nnreal _ μ _ _ INCL _ _ _, unfold_coes, unfold_coes at FOO, rw FOO, rw ← ennreal.coe_eq_coe, rw to_nnreal_sub, exact to_measure_lt_top μ (Icc 0 h), exact to_measure_lt_top μ (Icc 0 target), apply is_measurable_of_is_closed, apply is_closed_Icc, apply is_measurable_of_is_closed, apply is_closed_Icc, exact probability_measure.to_measure_lt_top μ (Icc 0 target) }, { have H: target < h, { unfold rle at h_1, tidy, }, unfold Icc, rw subset_def, intros, rw mem_set_of_eq, rw mem_set_of_eq at a, cases a, split, assumption, transitivity target; try {assumption}, exact le_of_lt H, }, { tidy, }, { unfold rle at h_1, simp at h_1, exact le_of_lt h_1, }, { unfold rle at h_1, simp at h_1, exact (gt_from_lt h target).mp h_1, }, }, end lemma error_measurable: measurable (error μ target) := begin rw decompose_error, unfold error_decomposed, apply measurable.if, { unfold rle, simp, apply is_meas_to_target, }, { unfold error1, apply nnreal.measurable_sub, { apply measurable_const, }, { apply measurable_Icc_0_x, }, }, { unfold error2, apply nnreal.measurable_sub, { apply measurable_Icc_0_x, }, { apply measurable_const, }, }, end @[simp] lemma is_meas_gamma_1: ∀ ε, is_measurable {h: ℍ | error μ target h > ε} := begin intro, have COMPL: {h: ℍ | error μ target h > ε} = -{h: ℍ | error μ target h ≤ ε}, { rw compl_set_of, simp, }, rw COMPL, apply is_measurable.compl, have MLE := @measurable_le _ _ _ _ _ _ _ (λ h, error μ target h) (λ h, ε), apply MLE, apply error_measurable, apply measurable_const, end @[simp] lemma is_meas_gamma_2: ∀ ε, is_measurable {h: ℍ | error μ target h ≤ ε} := begin intros, have COMPL: {h: ℍ | error μ target h ≤ ε} = -{h: ℍ | error μ target h > ε}, { rw compl_set_of, simp, }, rw COMPL, apply is_measurable.compl, apply is_meas_gamma_1, end @[simp] lemma is_meas_one: ∀ θ, θ > 0 → is_measurable {x: ℍ | ∀ p = label target x, (if p.snd then p.fst else 0) < θ} := begin introv T0, convert_to (is_measurable {x: ℍ | (if (label target x).snd then (label target x).fst else 0) < θ}), { rw ext_iff, intro, repeat {rw mem_set_of_eq}, split; intros, apply a, trivial, rw H, assumption, }, unfold label, simp, unfold rle, rw ite_equals_union_interval θ T0 target, apply is_measurable.union, { exact is_measurable_Ico, }, { rw Ioi_complement target, apply is_measurable.compl, apply is_measurable.union, exact is_measurable_Iio, rw ← (Ico_diff_Ioo_eq_singleton (by exact lt_add_one target)), apply is_measurable.diff, exact is_measurable_Ico, exact is_measurable_Ioo, }, end @[simp] lemma is_meas_forall: ∀ θ, θ > 0 → ∀ n, is_measurable {S: vec ℍ n | ∀ (i: dfin (nat.succ n)), ∀ p = label target (kth_projn S i), (if p.snd then p.fst else 0) < θ} := begin intros, convert_to (is_measurable {S: vec ℍ n | ∀ (i: dfin (nat.succ n)), (if (label target (kth_projn S i)).snd then (label target (kth_projn S i)).fst else 0) < θ}), { rw ext_iff, intro, repeat {rw mem_set_of_eq}, split; intros, apply (a_1 i), trivial, rw H, apply (a_1 i), }, have FOO:= is_measurable_simple_vec (λ x, (if (label target x).snd then (label target x).fst else 0) < θ), apply FOO, convert_to (is_measurable {x: ℍ | ∀ p = label target x, (if p.snd then p.fst else 0) < θ}), { rw ext_iff, intro, repeat {rw mem_set_of_eq}, split; intros, rw H, assumption, apply a_1, trivial, }, apply is_meas_one; assumption, end end stump
990c925b50ff711ffdc3b26283daef793fc60e74
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/elab_cmd.lean
76a2754d5f1a5bb2e4f53b1d858554c9641a5963
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
648
lean
import Lean open Lean.Elab.Term open Lean.Elab.Command elab "∃'" b:term "," P:term : term => do let ex ← `(Exists (fun $b => $P)); elabTerm ex none elab "#check2" b:term : command => do let cmd ← `(#check $b #check $b); elabCommand cmd #check ∃' x, x > 0 #check ∃' (x : UInt32), x > 0 #check2 10 elab "try" t:tactic : tactic => do let t' ← `(tactic| $t <|> skip); Lean.Elab.Tactic.evalTactic t' theorem tst (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; }
f0e961ca1e6f41b0cc6f41dba9688c81491bd30e
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/choose/sum.lean
c22b35b937e7c65009024b7a6956c26a5fc88ec7
[ "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,859
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import tactic.linarith import algebra.big_operators.ring import algebra.big_operators.intervals import algebra.big_operators.order import algebra.big_operators.nat_antidiagonal /-! # Sums of binomial coefficients This file includes variants of the binomial theorem and other results on sums of binomial coefficients. Theorems whose proofs depend on such sums may also go in this file for import reasons. -/ open nat open finset open_locale big_operators variables {R : Type*} namespace commute variables [semiring R] {x y : R} (h : commute x y) (n : ℕ) include h /-- A version of the **binomial theorem** for noncommutative semirings. -/ theorem add_pow : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := begin let t : ℕ → ℕ → R := λ n m, x ^ m * (y ^ (n - m)) * (choose n m), change (x + y) ^ n = ∑ m in range (n + 1), t n m, have h_first : ∀ n, t n 0 = y ^ n := λ n, by { dsimp [t], rw [choose_zero_right, pow_zero, nat.cast_one, mul_one, one_mul] }, have h_last : ∀ n, t n n.succ = 0 := λ n, by { dsimp [t], rw [choose_succ_self, nat.cast_zero, mul_zero] }, have h_middle : ∀ (n i : ℕ), (i ∈ range n.succ) → ((t n.succ) ∘ nat.succ) i = x * (t n i) + y * (t n i.succ) := begin intros n i h_mem, have h_le : i ≤ n := nat.le_of_lt_succ (mem_range.mp h_mem), dsimp [t], rw [choose_succ_succ, nat.cast_add, mul_add], congr' 1, { rw [pow_succ x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] }, { rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq], by_cases h_eq : i = n, { rw [h_eq, choose_succ_self, nat.cast_zero, mul_zero, mul_zero] }, { rw [succ_sub (lt_of_le_of_ne h_le h_eq)], rw [pow_succ y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] } } end, induction n with n ih, { rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add], dsimp [t], rw [pow_zero, pow_zero, choose_self, nat.cast_one, mul_one, mul_one] }, { rw [sum_range_succ', h_first], rw [sum_congr rfl (h_middle n), sum_add_distrib, add_assoc], rw [pow_succ (x + y), ih, add_mul, mul_sum, mul_sum], congr' 1, rw [sum_range_succ', sum_range_succ, h_first, h_last, mul_zero, add_zero, pow_succ] } end /-- A version of `commute.add_pow` that avoids ℕ-subtraction by summing over the antidiagonal and also with the binomial coefficient applied via scalar action of ℕ. -/ lemma add_pow' : (x + y) ^ n = ∑ m in nat.antidiagonal n, choose n m.fst • (x ^ m.fst * y ^ m.snd) := by simp_rw [finset.nat.sum_antidiagonal_eq_sum_range_succ (λ m p, choose n m • (x^m * y^p)), _root_.nsmul_eq_mul, cast_comm, h.add_pow] end commute /-- The **binomial theorem** -/ theorem add_pow [comm_semiring R] (x y : R) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := (commute.all x y).add_pow n namespace nat /-- The sum of entries in a row of Pascal's triangle -/ theorem sum_range_choose (n : ℕ) : ∑ m in range (n + 1), choose n m = 2 ^ n := by simpa using (add_pow 1 1 n).symm lemma sum_range_choose_halfway (m : nat) : ∑ i in range (m + 1), choose (2 * m + 1) i = 4 ^ m := have ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) = ∑ i in range (m + 1), choose (2 * m + 1) i, from sum_congr rfl $ λ i hi, choose_symm $ by linarith [mem_range.1 hi], (nat.mul_right_inj zero_lt_two).1 $ calc 2 * (∑ i in range (m + 1), choose (2 * m + 1) i) = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) : by rw [two_mul, this] ... = (∑ i in range (m + 1), choose (2 * m + 1) i) + ∑ i in Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i : begin rw [range_eq_Ico, sum_Ico_reflect], { congr, have A : m + 1 ≤ 2 * m + 1, by linarith, rw [add_comm, add_tsub_assoc_of_le A, ← add_comm], congr, rw tsub_eq_iff_eq_add_of_le A, ring, }, { linarith } end ... = ∑ i in range (2 * m + 2), choose (2 * m + 1) i : sum_range_add_sum_Ico _ (by linarith) ... = 2^(2 * m + 1) : sum_range_choose (2 * m + 1) ... = 2 * 4^m : by { rw [pow_succ, pow_mul], refl } lemma choose_middle_le_pow (n : ℕ) : choose (2 * n + 1) n ≤ 4 ^ n := begin have t : choose (2 * n + 1) n ≤ ∑ i in range (n + 1), choose (2 * n + 1) i := single_le_sum (λ x _, by linarith) (self_mem_range_succ n), simpa [sum_range_choose_halfway n] using t end lemma four_pow_le_two_mul_add_one_mul_central_binom (n : ℕ) : 4 ^ n ≤ (2 * n + 1) * choose (2 * n) n := calc 4 ^ n = (1 + 1) ^ (2 * n) : by norm_num [pow_mul] ... = ∑ m in range (2 * n + 1), choose (2 * n) m : by simp [add_pow] ... ≤ ∑ m in range (2 * n + 1), choose (2 * n) (2 * n / 2) : sum_le_sum (λ i hi, choose_le_middle i (2 * n)) ... = (2 * n + 1) * choose (2 * n) n : by simp end nat theorem int.alternating_sum_range_choose {n : ℕ} : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = if n = 0 then 1 else 0 := begin cases n, { simp }, have h := add_pow (-1 : ℤ) 1 n.succ, simp only [one_pow, mul_one, add_left_neg] at h, rw [← h, zero_pow (nat.succ_pos n), if_neg (nat.succ_ne_zero n)], end theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) : ∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = 0 := by rw [int.alternating_sum_range_choose, if_neg h0] namespace finset theorem sum_powerset_apply_card {α β : Type*} [add_comm_monoid α] (f : ℕ → α) {x : finset β} : ∑ m in x.powerset, f m.card = ∑ m in range (x.card + 1), (x.card.choose m) • f m := begin transitivity ∑ m in range (x.card + 1), ∑ j in x.powerset.filter (λ z, z.card = m), f j.card, { refine (sum_fiberwise_of_maps_to _ _).symm, intros y hy, rw [mem_range, nat.lt_succ_iff], rw mem_powerset at hy, exact card_le_of_subset hy }, { refine sum_congr rfl (λ y hy, _), rw [← card_powerset_len, ← sum_const], refine sum_congr powerset_len_eq_filter.symm (λ z hz, _), rw (mem_powerset_len.1 hz).2 } end theorem sum_powerset_neg_one_pow_card {α : Type*} [decidable_eq α] {x : finset α} : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = if x = ∅ then 1 else 0 := begin rw sum_powerset_apply_card, simp only [nsmul_eq_mul', ← card_eq_zero, int.alternating_sum_range_choose] end theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : finset α} (h0 : x.nonempty) : ∑ m in x.powerset, (-1 : ℤ) ^ m.card = 0 := begin classical, rw [sum_powerset_neg_one_pow_card, if_neg], rw [← ne.def, ← nonempty_iff_ne_empty], apply h0, end end finset
487bc6e35e84aaa0375cfd7efdb553d62bc23d72
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/newfrontend1.lean
f7f7279c1fa044e6d7a97619eb9d8f1ae428f1d6
[ "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,812
lean
def x := 1 #check x variable {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check fun x y : Nat => x + y #check tst #check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := by { assumption } theorem simple2 (x y : Nat) : x = y → x = y := by { intro h; assumption } syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := by { intro2; assumption } macro "intro3" : tactic => `(tactic| (intro; intro; intro)) macro "check2" x:term : command => `(#check $x #check $x) macro "foo" x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := by { intro3; assumption } theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; exact Eq.trans h3 h1 } theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine Eq.trans ?_ h1; assumption } theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine' Eq.trans ?pre ?post; exact y; { exact h3 } { exact h1 } } theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by intro h1; intro _; intro h3 refine' Eq.trans ?pre ?post case post => exact h1 case pre => exact h3 theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 trace_state focus refine' Eq.trans ?pre ?post first | exact h1 assumption | exact y exact h3 assumption theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 trace_state focus refine' Eq.trans ?pre ?post first | exact h1 | exact y; exact h3 assumption theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 solve | exact h1 | refine' Eq.trans ?pre ?post; exact y; exact h3; assumption | exact h3 theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 refine' Eq.trans ?pre ?post solve | exact h1 | exact y | exact h3 solve | exact h1 | exact h3 solve | exact h1 | assumption namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption } theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; trace_state; exact h3; assumption } theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails trace_state; try exact h3; trace_state; try exact h1; } theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 trace_state apply @Eq.trans case b => exact y trace_state repeat assumption theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; trace_state; apply @Eq.trans; case b => exact y; trace_state; repeat assumption } theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros apply @Eq.trans case b => exact y repeat assumption theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 } theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; try clear x; -- should fail clear h2; trace_state; apply Eq.trans; exact h3; exact h1 } macro "blabla" : tactic => `(tactic| assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun α (a : α) => a) #check let myid := fun {α} (a : α) => a; myid [myid 1] -- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α], -- and will fail to generate instance for [Add α] #check @(fun α (s : Add α) (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := @(fun α (x : α) => id1 x) def id3 : {α : Type} → α → α := @(fun α x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := fun {α} x => id1 x def id6 : {α : Type} → α → α := @(fun {α} x => id1 x) def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orElse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩ #check_failure 1 + true /- universe u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option pp.raw.maxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/ syntax "fn" (term:max)+ "=>" term : term macro_rules | `(fn $xs* => $b) => `(fun $xs* => $b) set_option pp.all false #check fn x => x+1 #check fn α (a : α) => a def tst1 : {α : Type} → α → α := @(fn α a => a) #check @tst1 syntax ident "==>" term : term syntax "{" ident "}" "==>" term : term macro_rules | `($x:ident ==> $b) => `(fn $x => $b) | `({$x:ident} ==> $b) => `(fun {$x:ident} => $b) #check x ==> x+1 def tst2a : {α : Type} → α → α := @(α ==> a ==> a) def tst2b : {α : Type} → α → α := {α} ==> a ==> a #check @tst2a #check @tst2b def tst3a : {α : Type} → {β : Type} → α → β → α × β := @(α ==> @(β ==> a ==> b ==> (a, b))) def tst3b : {α : Type} → {β : Type} → α → β → α × β := {α} ==> {β} ==> a ==> b ==> (a, b) syntax "function" (term:max)+ "=>" term : term macro_rules | `(function $xs* => $b) => `(@(fun $xs* => $b)) def tst4 : {α : Type} → {β : Type} → α → β → α × β := function α β a b => (a, b) theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3; try clear x; -- should fail clear h2; trace_state; apply Eq.trans; exact h3; exact h1 theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by { apply Eq.symm; assumption }; Eq.trans this (by assumption) theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) := fun h1 h2 => show x = z + 0 by apply Eq.trans exact h2.symm assumption skip theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by apply Eq.symm; assumption Eq.trans this (by assumption) theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have h : x = y := by apply Eq.symm; assumption Eq.trans h (by assumption) def f1 (x : Nat) : Nat := let double x := x + x let rec loop x := match x with | 0 => 0 | x+1 => loop x + double x loop x #eval f1 5 def f2 (x : Nat) : String := let bad x : String := toString x bad x def f3 x y := x + y + 1 theorem f3eq x y : f3 x y = x + y + 1 := rfl def f4 (x y : Nat) : String := if x > y + 1 then "hello" else "world"
c48ff1a7b620021b220797081dbb906049857063
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Parser/Command.lean
7d168337aa9ec0ec04c8029c1f6a4f6b0c51ff04
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,110
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like `($x $y) will be parsed as an application, not two commands. Use `($x:command $y:command) instead. Multiple command will be put in a `null node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ -- TODO: use two separate quotation parsers with parser priorities instead @[builtinTermParser] def Term.quot := parser! "`(" >> toggleInsideQuot (termParser <|> many1Unbox commandParser) >> ")" namespace Command def namedPrio := parser! (atomic ("(" >> nonReservedSymbol "priority") >> " := " >> priorityParser >> ")") def optNamedPrio := optional namedPrio def «private» := parser! "private " def «protected» := parser! "protected " def visibility := «private» <|> «protected» def «noncomputable» := parser! "noncomputable " def «unsafe» := parser! "unsafe " def «partial» := parser! "partial " def declModifiers (inline : Bool) := parser! optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional «partial» def declId := parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := parser! many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := parser! many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType def declValSimple := parser! " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := parser! Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls def «abbrev» := parser! "abbrev " >> declId >> optDeclSig >> declVal def «def» := parser! "def " >> declId >> optDeclSig >> declVal def «theorem» := parser! "theorem " >> declId >> declSig >> declVal def «constant» := parser! "constant " >> declId >> declSig >> optional declValSimple def «instance» := parser! Term.attrKind >> "instance " >> optNamedPrio >> optional declId >> declSig >> declVal def «axiom» := parser! "axiom " >> declId >> declSig def «example» := parser! "example " >> declSig >> declVal def inferMod := parser! atomic (symbol "{" >> "}") def ctor := parser! "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig def optDeriving := parser! optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ") def «inductive» := parser! "inductive " >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def classInductive := parser! atomic (group (symbol "class " >> "inductive ")) >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def structExplicitBinder := parser! atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional Term.binderDefault >> ")" def structImplicitBinder := parser! atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := parser! atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := parser! atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional Term.binderDefault def structFields := parser! manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder)) def structCtor := parser! atomic (declModifiers true >> ident >> optional inferMod >> " :: ") def structureTk := parser! "structure " def classTk := parser! "class " def «extends» := parser! " extends " >> sepBy1 termParser ", " def «structure» := parser! (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >> optDeriving @[builtinCommandParser] def declaration := parser! declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «deriving» := parser! "deriving " >> "instance " >> sepBy1 ident ", " >> " for " >> sepBy1 ident ", " @[builtinCommandParser] def «section» := parser! "section " >> optional ident @[builtinCommandParser] def «namespace» := parser! "namespace " >> ident @[builtinCommandParser] def «end» := parser! "end " >> optional ident @[builtinCommandParser] def «variable» := parser! "variable" >> many1 Term.bracketedBinder @[builtinCommandParser] def «universe» := parser! "universe " >> ident @[builtinCommandParser] def «universes» := parser! "universes " >> many1 ident @[builtinCommandParser] def check := parser! "#check " >> termParser @[builtinCommandParser] def check_failure := parser! "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def reduce := parser! "#reduce " >> termParser @[builtinCommandParser] def eval := parser! "#eval " >> termParser @[builtinCommandParser] def synth := parser! "#synth " >> termParser @[builtinCommandParser] def exit := parser! "#exit" @[builtinCommandParser] def print := parser! "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := parser! "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := parser! "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := parser! "init_quot" @[builtinCommandParser] def «set_option» := parser! "set_option " >> ident >> ppSpace >> (nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit) @[builtinCommandParser] def «attribute» := parser! "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := parser! "export " >> ident >> "(" >> many1 ident >> ")" def openHiding := parser! atomic (ident >> "hiding") >> many1 ident def openRenamingItem := parser! ident >> unicodeSymbol "→" "->" >> ident def openRenaming := parser! atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := parser! atomic (ident >> "(") >> many1 ident >> ")" def openSimple := parser! many1 ident @[builtinCommandParser] def «open» := parser! "open " >> (openHiding <|> openRenaming <|> openOnly <|> openSimple) @[builtinCommandParser] def «mutual» := parser! "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end") @[builtinCommandParser] def «initialize» := parser! "initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «builtin_initialize» := parser! "builtin_initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := tparser! " in " >> commandParser @[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false @[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true builtin_initialize registerParserAlias! "declModifiers" declModifiersF registerParserAlias! "nestedDeclModifiers" declModifiersT registerParserAlias! "declId" declId registerParserAlias! "declSig" declSig registerParserAlias! "optDeclSig" optDeclSig end Command end Parser end Lean
e629ae17fe1b47cd61ac77841a3ea5e6b9674afa
b392eb79fb36952401156496daa60628ccb07438
/MathPort/Translate.lean
265a37dcdb235c131ce6b4e7e88bcca5ff72ca56
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
4,368
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import MathPort.Util import MathPort.Basic import MathPort.ActionItem import MathPort.OldRecursor import MathPort.Number import Lean namespace MathPort open Lean -- TODO: put somewhere else or don't call it State partial def translateName (s : State) (env : Environment) (n : Name) : Name := do match s.newNames.find? n with | some new => new | none => if n.isStr && n.getString! == "rec" && not n.getPrefix.isAnonymous then let newIndName := translateName s env n.getPrefix match env.find? newIndName with | none => dflt n | some cInfo => match cInfo with | ConstantInfo.inductInfo _ => if env.contains (mkOldRecName newIndName) then mkOldRecName newIndName else newIndName ++ "rec" | _ => dflt n else if n.isStr && (n.getString! == "below" || n.getString! == "ibelow") then let newName := Name.mkStr (dflt n.getPrefix) ("old_" ++ n.getString!) newName else dflt n where dflt n := `Mathlib ++ n partial def translateNamePrint (s : State) (env : Environment) (n : Name) : Name := do if n.isStr && n.getString! == "rec" && not n.getPrefix.isAnonymous then let newIndName := translateName s env n.getPrefix match env.find? newIndName with | none => dflt n | some cInfo => match cInfo with | ConstantInfo.inductInfo _ => if env.contains (mkOldRecName newIndName) then mkOldRecName newIndName else newIndName ++ "rec" | _ => dflt n else if n.isStr && (n.getString! == "below" || n.getString! == "ibelow") then let newName := Name.mkStr (dflt n.getPrefix) ("old_" ++ n.getString!) newName else dflt n where dflt n := `Mathlib ++ n def doubleCheck (e e' : Expr) : MetaM TransformStep := do if (← Meta.isDefEq e e') then TransformStep.done e' else throwError "[translateNumber] broke def-eq, \n{e}\n\n!=\n\n{e'}" def translate (e : Expr) : PortM Expr := do let s ← get let e := e.replaceConstNames (translateName s (← getEnv)) let e ← liftMetaM $ Meta.transform e (pre := translateNumbers s) let e ← liftMetaM $ Meta.transform e (pre := translateAutoParams s) e where translateNumbers s e : MetaM TransformStep := match isConcreteNat? e with | some n => TransformStep.done $ mkNatLit n | none => match isNumber? e with | none => TransformStep.visit e | some info@⟨n, level, type, hasZero?, hasOne?, hasAdd?⟩ => -- TODO: we will want to avoid wrapping "normal" Nat numbers -- (current workaround is for the OfNat instances to `no_index` the numbers) let inst := mkAppN (mkConst `OfNat.mk [level]) #[type, mkNatLit n, e] TransformStep.done $ mkAppN (mkConst `OfNat.ofNat [level]) #[type, mkNatLit n, inst] translateAutoParams s e : MetaM TransformStep := -- def auto_param : Sort u → name → Sort u := -- λ (α : Sort u) (tac_name : name), α if e.isAppOfArity `Mathlib.auto_param 2 then do let level := e.getAppFn.constLevels!.head! let type := e.getArg! 0 let tacName3 ← Meta.reduce (e.getArg! 1) try let tacNameOld ← decodeName tacName3 -- This may not always be the right decision, i.e. one of the tactics may be already in Lean4 -- currently, mathlib would need to alias that tactic in the Mathlib namespace let tacName := translateName s (← getEnv) tacNameOld let substr : Expr := mkAppN (mkConst `String.toSubstring) #[toExpr $ tacName.toString] -- Note: we currently hardcode `obviously` -- if Mathlib really uses other tactics here, we can parse the name from the auto-ported Lean3 string let tacSyntax := mkAppN (mkConst `Lean.Syntax.ident) #[mkConst `Lean.SourceInfo.none, substr, toExpr tacName, toExpr ([] : List (Prod Name (List String)))] TransformStep.done $ mkAppN (mkConst `autoParam [level]) #[type, tacSyntax ] -- they prove theorems about auto_param! catch ex => do println! "[decode] {(← ex.toMessageData.toString)}" TransformStep.visit e else TransformStep.visit e end MathPort
f39920d6a9ddff90b0bc38b0cf547184fe230645
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/polynomial/ring_division.lean
10676ed147e90c2abde2e1dc79c7110b8ca9247d
[ "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
25,340
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, Johan Commelin -/ import data.polynomial.basic import data.polynomial.div import data.polynomial.algebra_map import data.set.finite /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : polynomial R} variables [comm_ring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : polynomial R} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := eval₂_mod_by_monic_eq_self_of_root hq hx end comm_ring section integral_domain variables [integral_domain R] {p q : polynomial R} instance : integral_domain (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nontrivial, ..polynomial.comm_ring } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end section roots open multiset local attribute [reducible] with_zero lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C {r : R} : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : polynomial R) := by { convert (prime_X_sub_C : prime (X - C 0 : polynomial R)), simp } lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := irreducible_of_prime prime_X_sub_C theorem irreducible_X : irreducible (X : polynomial R) := irreducible_of_prime prime_X lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm) theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu end @[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) : root_multiplicity x p = 0 := begin rw root_multiplicity_eq_multiplicity, split_ifs, { refl }, rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, enat.coe_zero], intro hdvd, exact h (dvd_iff_is_root.mp hdvd) end lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := begin rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_lt_coe, enat.coe_get], exact multiplicity.dvd_iff_multiplicity_pos end lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, @multiplicity.mul' _ _ _ (X - C x) _ _ prime_X_sub_C], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero _) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : polynomial R) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : polynomial R).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p := by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a } @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots hp, root_multiplicity_pos hp] lemma eq_zero_of_infinite_is_root (p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 := begin by_contradiction hp, apply h, convert p.roots.to_finset.finite_to_set using 1, ext1 r, simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe] end lemma eq_of_infinite_eval_eq {R : Type*} [integral_domain R] (p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq), count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq] @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = r ::ₘ 0 := begin ext s, rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton] }, { rw [count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm, have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H, by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root] @[simp] lemma roots_one : (1 : polynomial R).roots = ∅ := roots_C 1 lemma roots_list_prod (L : list (polynomial R)) : (∀ p ∈ L, (p : _) ≠ 0) → L.prod.roots = (L : multiset (polynomial R)).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw list.forall_mem_cons at H, rw [list.prod_cons, roots_mul (mul_ne_zero H.1 $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset (polynomial R)) : (∀ p ∈ m, (p : _) ≠ 0) → m.prod.roots = m.bind roots := multiset.induction_on m (λ _, roots_one) $ λ hd tl ih H, begin rw multiset.forall_mem_cons at H, rw [multiset.prod_cons, roots_mul (mul_ne_zero H.1 $ multiset.prod_ne_zero H.2), multiset.cons_bind, ih H.2] end lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin refine s.induction_on _ _, { intros, exact roots_one }, intros i s hi ih ne_zero, rw prod_insert hi at ⊢ ne_zero, rw [roots_mul ne_zero, ih (right_ne_zero_of_mul ne_zero), insert_val, ndinsert_of_not_mem hi, cons_bind] end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, bind_cons, bind_zero, add_zero, multiset.map_id']) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [integral_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] end nth_roots lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa finsupp.mem_support_iff at hbs, refine coeff_eq_zero_of_degree_lt _, rw [degree_mul], erw degree_C this, rw [degree_pow, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], rw mul_lt_mul_right, apply lt_of_le_of_ne, assumption', swap, omega, exact le_nat_degree_of_ne_zero this, end begin intro h, contrapose! hp0, rw finsupp.mem_support_iff at h, push_neg at h, rwa ← leading_coeff_eq_zero, end ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) : (c : polynomial R).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact infinite.not_fintype ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end end roots theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [integral_domain R] {p q : polynomial R} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin have hp := mod_by_monic_add_div p hmonic, have hzero : (p /ₘ q) ≠ 0, { intro h, exact not_lt_of_le hdegree ((div_by_monic_eq_zero_iff hmonic (monic.ne_zero hmonic)).1 h) }, have deglt : (p %ₘ q).degree < (q * (p /ₘ q)).degree, { rw degree_mul, refine lt_of_lt_of_le (degree_mod_by_monic_lt p hmonic (monic.ne_zero hmonic)) _, rw [degree_eq_nat_degree (monic.ne_zero hmonic), degree_eq_nat_degree hzero], norm_cast, simp only [zero_le, le_add_iff_nonneg_right] }, have hrew := (leading_coeff_add_of_degree_lt deglt), rw leading_coeff_mul q (p /ₘ q) at hrew, simp only [hmonic, one_mul, monic.leading_coeff] at hrew, nth_rewrite 1 ← hp, exact hrew.symm end lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin obtain ⟨r, hr⟩ := hdiv, have rzero : r ≠ 0, { intro h, simpa [h, monic.ne_zero hq] using hr }, rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg, have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree, { suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree, { exact le_antisymm hdeg hdegle }, exact nat.le.intro rfl }, replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq), suffices hlead : 1 = r.leading_coeff, { have hcoeff := leading_coeff_C (r.coeff 0), rw [← hdegeq, ← hlead] at hcoeff, rw [← hcoeff, C_1] at hdegeq, rwa [hdegeq, mul_one] at hr }, have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff, { simp only [hr, leading_coeff_mul] }, rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod end end integral_domain section variables [semiring R] [integral_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, apply is_unit.map', convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map' _ hf, rw h at u, simpa using u, } end end section variables [integral_domain R] [integral_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : polynomial R) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin fsplit, { intro h, exact h_irr.1 (is_unit.map (monoid_hom.of (map φ)) h), }, { intros a b h, have q := (leading_coeff_mul a b).symm, rw ←h at q, dsimp [monic] at h_mon, rw h_mon at q, have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q, rw mul_comm at q, have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q, clear q h_mon, have h' := congr_arg (map φ) h, simp only [map_mul] at h', cases h_irr.2 _ _ h' with w w, { left, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, }, { right, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, } end end end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
e37c2e2cdb741db0cac30dd4c8c0f935ea712ac6
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/CoreM.lean
35c715cf1f03034c14e19fa12e87e74047743b30
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
13,533
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.Util.RecDepth import Lean.Util.Trace import Lean.Log import Lean.Eval import Lean.ResolveName import Lean.Elab.InfoTree.Types import Lean.MonadEnv namespace Lean namespace Core register_builtin_option maxHeartbeats : Nat := { defValue := 200000 descr := "maximum amount of heartbeats per command. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } def getMaxHeartbeats (opts : Options) : Nat := maxHeartbeats.get opts * 1000 abbrev InstantiateLevelCache := PersistentHashMap Name (List Level × Expr) /-- Cache for the `CoreM` monad -/ structure Cache where instLevelType : InstantiateLevelCache := {} instLevelValue : InstantiateLevelCache := {} deriving Inhabited /-- State for the CoreM monad. -/ structure State where /-- Current environment. -/ env : Environment /-- Next macro scope. We use macro scopes to avoid accidental name capture. -/ nextMacroScope : MacroScope := firstFrontendMacroScope + 1 /-- Name generator for producing unique `FVarId`s, `MVarId`s, and `LMVarId`s -/ ngen : NameGenerator := {} /-- Trace messages -/ traceState : TraceState := {} /-- Cache for instantiating universe polymorphic declarations. -/ cache : Cache := {} /-- Message log. -/ messages : MessageLog := {} /-- Info tree. We have the info tree here because we want to update it while adding attributes. -/ infoState : Elab.InfoState := {} deriving Inhabited /-- Context for the CoreM monad. -/ structure Context where /-- Name of the file being compiled. -/ fileName : String /-- Auxiliary datastructure for converting `String.Pos` into Line/Column number. -/ fileMap : FileMap options : Options := {} currRecDepth : Nat := 0 maxRecDepth : Nat := 1000 ref : Syntax := Syntax.missing currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] initHeartbeats : Nat := 0 maxHeartbeats : Nat := getMaxHeartbeats options currMacroScope : MacroScope := firstFrontendMacroScope /-- CoreM is a monad for manipulating the Lean environment. It is the base monad for `MetaM`. The main features it provides are: - name generator state - environment state - Lean options context - the current open namespace -/ abbrev CoreM := ReaderT Context <| StateRefT State (EIO Exception) -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. @[always_inline] instance : Monad CoreM := let i := inferInstanceAs (Monad CoreM); { pure := i.pure, bind := i.bind } instance : Inhabited (CoreM α) where default := fun _ _ => throw default instance : MonadRef CoreM where getRef := return (← read).ref withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : MonadEnv CoreM where getEnv := return (← get).env modifyEnv f := modify fun s => { s with env := f s.env, cache := {} } instance : MonadOptions CoreM where getOptions := return (← read).options instance : MonadWithOptions CoreM where withOptions f x := withReader (fun ctx => { ctx with options := f ctx.options }) x instance : AddMessageContext CoreM where addMessageContext := addMessageContextPartial instance : MonadNameGenerator CoreM where getNGen := return (← get).ngen setNGen ngen := modify fun s => { s with ngen := ngen } instance : MonadRecDepth CoreM where withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x getRecDepth := return (← read).currRecDepth getMaxRecDepth := return (← read).maxRecDepth instance : MonadResolveName CoreM where getCurrNamespace := return (← read).currNamespace getOpenDecls := return (← read).openDecls protected def withFreshMacroScope (x : CoreM α) : CoreM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation CoreM where getCurrMacroScope := return (← read).currMacroScope getMainModule := return (← get).env.mainModule withFreshMacroScope := Core.withFreshMacroScope instance : Elab.MonadInfoTree CoreM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } @[inline] def modifyCache (f : Cache → Cache) : CoreM Unit := modify fun ⟨env, next, ngen, trace, cache, messages, infoState⟩ => ⟨env, next, ngen, trace, f cache, messages, infoState⟩ @[inline] def modifyInstLevelTypeCache (f : InstantiateLevelCache → InstantiateLevelCache) : CoreM Unit := modifyCache fun ⟨c₁, c₂⟩ => ⟨f c₁, c₂⟩ @[inline] def modifyInstLevelValueCache (f : InstantiateLevelCache → InstantiateLevelCache) : CoreM Unit := modifyCache fun ⟨c₁, c₂⟩ => ⟨c₁, f c₂⟩ def instantiateTypeLevelParams (c : ConstantInfo) (us : List Level) : CoreM Expr := do if let some (us', r) := (← get).cache.instLevelType.find? c.name then if us == us' then return r let r := c.instantiateTypeLevelParams us modifyInstLevelTypeCache fun s => s.insert c.name (us, r) return r def instantiateValueLevelParams (c : ConstantInfo) (us : List Level) : CoreM Expr := do if let some (us', r) := (← get).cache.instLevelValue.find? c.name then if us == us' then return r unless c.hasValue do throwError "Not a definition or theorem: {c.name}" let r := c.instantiateValueLevelParams! us modifyInstLevelValueCache fun s => s.insert c.name (us, r) return r @[inline] def liftIOCore (x : IO α) : CoreM α := do let ref ← getRef IO.toEIO (fun (err : IO.Error) => Exception.error ref (toString err)) x instance : MonadLift IO CoreM where monadLift := liftIOCore instance : MonadTrace CoreM where getTraceState := return (← get).traceState modifyTraceState f := modify fun s => { s with traceState := f s.traceState } /-- Restore backtrackable parts of the state. -/ def restore (b : State) : CoreM Unit := modify fun s => { s with env := b.env, messages := b.messages, infoState := b.infoState } private def mkFreshNameImp (n : Name) : CoreM Name := do let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 }) return addMacroScope (← getEnv).mainModule n fresh def mkFreshUserName (n : Name) : CoreM Name := mkFreshNameImp n @[inline] def CoreM.run (x : CoreM α) (ctx : Context) (s : State) : EIO Exception (α × State) := (x ctx).run s @[inline] def CoreM.run' (x : CoreM α) (ctx : Context) (s : State) : EIO Exception α := Prod.fst <$> x.run ctx s @[inline] def CoreM.toIO (x : CoreM α) (ctx : Context) (s : State) : IO (α × State) := do match (← (x.run { ctx with initHeartbeats := (← IO.getNumHeartbeats) } s).toIO') with | Except.error (Exception.error _ msg) => throw <| IO.userError (← msg.toString) | Except.error (Exception.internal id _) => throw <| IO.userError <| "internal exception #" ++ toString id.idx | Except.ok a => return a instance [MetaEval α] : MetaEval (CoreM α) where eval env opts x _ := do let x : CoreM α := do try x finally printTraces let (a, s) ← x.toIO { maxRecDepth := maxRecDepth.get opts, options := opts, fileName := "<CoreM>", fileMap := default } { env := env } MetaEval.eval s.env opts a (hideUnit := true) -- withIncRecDepth for a monad `m` such that `[MonadControlT CoreM n]` protected def withIncRecDepth [Monad m] [MonadControlT CoreM m] (x : m α) : m α := controlAt CoreM fun runInBase => withIncRecDepth (runInBase x) def throwMaxHeartbeat (moduleName : Name) (optionName : Name) (max : Nat) : CoreM Unit := do let msg := s!"(deterministic) timeout at '{moduleName}', maximum number of heartbeats ({max/1000}) has been reached (use 'set_option {optionName} <num>' to set the limit)" throw <| Exception.error (← getRef) (MessageData.ofFormat (Std.Format.text msg)) def checkMaxHeartbeatsCore (moduleName : String) (optionName : Name) (max : Nat) : CoreM Unit := do unless max == 0 do let numHeartbeats ← IO.getNumHeartbeats if numHeartbeats - (← read).initHeartbeats > max then throwMaxHeartbeat moduleName optionName max def checkMaxHeartbeats (moduleName : String) : CoreM Unit := do checkMaxHeartbeatsCore moduleName `maxHeartbeats (← read).maxHeartbeats private def withCurrHeartbeatsImp (x : CoreM α) : CoreM α := do let heartbeats ← IO.getNumHeartbeats withReader (fun ctx => { ctx with initHeartbeats := heartbeats }) x def withCurrHeartbeats [Monad m] [MonadControlT CoreM m] (x : m α) : m α := controlAt CoreM fun runInBase => withCurrHeartbeatsImp (runInBase x) def setMessageLog (messages : MessageLog) : CoreM Unit := modify fun s => { s with messages := messages } def resetMessageLog : CoreM Unit := setMessageLog {} def getMessageLog : CoreM MessageLog := return (← get).messages instance : MonadLog CoreM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName hasErrors := return (← get).messages.hasErrors logMessage msg := do let ctx ← read let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } end Core export Core (CoreM mkFreshUserName checkMaxHeartbeats withCurrHeartbeats) @[inline] def withAtLeastMaxRecDepth [MonadFunctorT CoreM m] (max : Nat) : m α → m α := monadMap (m := CoreM) <| withReader (fun ctx => { ctx with maxRecDepth := Nat.max max ctx.maxRecDepth }) @[inline] def catchInternalId [Monad m] [MonadExcept Exception m] (id : InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do try x catch ex => match ex with | .error .. => throw ex | .internal id' _ => if id == id' then h ex else throw ex @[inline] def catchInternalIds [Monad m] [MonadExcept Exception m] (ids : List InternalExceptionId) (x : m α) (h : Exception → m α) : m α := do try x catch ex => match ex with | .error .. => throw ex | .internal id _ => if ids.contains id then h ex else throw ex /-- Return true if `ex` was generated by `throwMaxHeartbeat`. This function is a bit hackish. The heartbeat exception should probably be an internal exception. We used a similar hack at `Exception.isMaxRecDepth` -/ def Exception.isMaxHeartbeat (ex : Exception) : Bool := match ex with | Exception.error _ (MessageData.ofFormat (Std.Format.text msg)) => "(deterministic) timeout".isPrefixOf msg | _ => false /-- Creates the expression `d → b` -/ def mkArrow (d b : Expr) : CoreM Expr := return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b def addDecl (decl : Declaration) : CoreM 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 () -- Forward declaration @[extern "lean_lcnf_compile_decls"] opaque compileDeclsNew (declNames : List Name) : CoreM Unit def compileDecl (decl : Declaration) : CoreM Unit := do compileDeclsNew (Compiler.getDeclNamesForCodeGen decl) 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 (decls : List Name) : CoreM Unit := do compileDeclsNew decls 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 (decl : Declaration) : CoreM Unit := do addDecl decl; compileDecl decl def ImportM.runCoreM (x : CoreM α) : ImportM α := do let ctx ← read let (a, _) ← x.toIO { options := ctx.opts, fileName := "<ImportM>", fileMap := default } { env := ctx.env } return a end Lean
c307e003a4751a7d9ea257813682c96761f7ca00
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/module/basic.lean
c05e27069fbd8cb78d346753e9c2e9e6afa801f5
[ "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
92,976
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov, Frédéric Dupuis, Heather Macbeth -/ import topology.algebra.ring import topology.algebra.mul_action import topology.algebra.uniform_group import topology.continuous_function.basic import topology.uniform_space.uniform_embedding import algebra.algebra.basic import linear_algebra.projection import linear_algebra.pi import ring_theory.simple_module /-! # Theory of topological modules and continuous linear maps. We use the class `has_continuous_smul` for topological (semi) modules and topological vector spaces. In this file we define continuous (semi-)linear maps, as semilinear maps between topological modules which are continuous. The set of continuous semilinear maps between the topological `R₁`-module `M` and `R₂`-module `M₂` with respect to the `ring_hom` `σ` is denoted by `M →SL[σ] M₂`. Plain linear maps are denoted by `M →L[R] M₂` and star-linear maps by `M →L⋆[R] M₂`. The corresponding notation for equivalences is `M ≃SL[σ] M₂`, `M ≃L[R] M₂` and `M ≃L⋆[R] M₂`. -/ open filter linear_map (ker range) open_locale topological_space big_operators filter universes u v w u' section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] lemma has_continuous_smul.of_nhds_zero [topological_ring R] [topological_add_group M] (hmul : tendsto (λ p : R × M, p.1 • p.2) (𝓝 0 ×ᶠ (𝓝 0)) (𝓝 0)) (hmulleft : ∀ m : M, tendsto (λ a : R, a • m) (𝓝 0) (𝓝 0)) (hmulright : ∀ a : R, tendsto (λ m : M, a • m) (𝓝 0) (𝓝 0)) : has_continuous_smul R M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨a₀, m₀⟩, have key : ∀ p : R × M, p.1 • p.2 = a₀ • m₀ + ((p.1 - a₀) • m₀ + a₀ • (p.2 - m₀) + (p.1 - a₀) • (p.2 - m₀)), { rintro ⟨a, m⟩, simp [sub_smul, smul_sub], abel }, rw funext key, clear key, refine tendsto_const_nhds.add (tendsto.add (tendsto.add _ _) _), { rw [sub_self, zero_smul], apply (hmulleft m₀).comp, rw [show (λ p : R × M, p.1 - a₀) = (λ a, a - a₀) ∘ prod.fst, by {ext, refl }, nhds_prod_eq], have : tendsto (λ a, a - a₀) (𝓝 a₀) (𝓝 0), { rw ← sub_self a₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_fst }, { rw [sub_self, smul_zero], apply (hmulright a₀).comp, rw [show (λ p : R × M, p.2 - m₀) = (λ m, m - m₀) ∘ prod.snd, by {ext, refl }, nhds_prod_eq], have : tendsto (λ m, m - m₀) (𝓝 m₀) (𝓝 0), { rw ← sub_self m₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_snd }, { rw [sub_self, zero_smul, nhds_prod_eq, show (λ p : R × M, (p.fst - a₀) • (p.snd - m₀)) = (λ p : R × M, p.1 • p.2) ∘ (prod.map (λ a, a - a₀) (λ m, m - m₀)), by { ext, refl }], apply hmul.comp (tendsto.prod_map _ _); { rw ← sub_self , exact tendsto_id.sub tendsto_const_nhds } }, end⟩ end section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [has_continuous_add M] [module R M] [has_continuous_smul R M] /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nontrivially normed field. -/ lemma submodule.eq_top_of_nonempty_interior' [ne_bot (𝓝[{x : R | is_unit x}] 0)] (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (𝓝[{x : R | is_unit x}] 0) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, obtain ⟨_, hu : y + _ • _ ∈ s, u, rfl⟩ := nonempty_of_mem (inter_mem (mem_map.1 (this hy)) self_mem_nhds_within), have hy' : y ∈ ↑s := mem_of_mem_nhds hy, rwa [s.add_mem_iff_right hy', ←units.smul_def, s.smul_mem_iff' u] at hu, end variables (R M) /-- Let `R` be a topological ring such that zero is not an isolated point (e.g., a nontrivially normed field, see `normed_field.punctured_nhds_ne_bot`). Let `M` be a nontrivial module over `R` such that `c • x = 0` implies `c = 0 ∨ x = 0`. Then `M` has no isolated points. We formulate this using `ne_bot (𝓝[≠] x)`. This lemma is not an instance because Lean would need to find `[has_continuous_smul ?m_1 M]` with unknown `?m_1`. We register this as an instance for `R = ℝ` in `real.punctured_nhds_module_ne_bot`. One can also use `haveI := module.punctured_nhds_ne_bot R M` in a proof. -/ lemma module.punctured_nhds_ne_bot [nontrivial M] [ne_bot (𝓝[≠] (0 : R))] [no_zero_smul_divisors R M] (x : M) : ne_bot (𝓝[≠] x) := begin rcases exists_ne (0 : M) with ⟨y, hy⟩, suffices : tendsto (λ c : R, x + c • y) (𝓝[≠] 0) (𝓝[≠] x), from this.ne_bot, refine tendsto.inf _ (tendsto_principal_principal.2 $ _), { convert tendsto_const_nhds.add ((@tendsto_id R _).smul_const y), rw [zero_smul, add_zero] }, { intros c hc, simpa [hy] using hc } end end section lattice_ops variables {ι R M₁ M₂ : Type*} [semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [module R M₁] [module R M₂] [u : topological_space R] {t : topological_space M₂} [has_continuous_smul R M₂] (f : M₁ →ₗ[R] M₂) lemma has_continuous_smul_induced : @has_continuous_smul R M₁ _ u (t.induced f) := { continuous_smul := begin letI : topological_space M₁ := t.induced f, refine continuous_induced_rng.2 _, simp_rw [function.comp, f.map_smul], refine continuous_fst.smul (continuous_induced_dom.comp continuous_snd) end } end lattice_ops namespace submodule variables {α β : Type*} [topological_space β] instance [topological_space α] [semiring α] [add_comm_monoid β] [module α β] [has_continuous_smul α β] (S : submodule α β) : has_continuous_smul α S := { continuous_smul := begin rw embedding_subtype_coe.to_inducing.continuous_iff, exact continuous_fst.smul (continuous_subtype_coe.comp continuous_snd) end } instance [ring α] [add_comm_group β] [module α β] [topological_add_group β] (S : submodule α β) : topological_add_group S := S.to_add_subgroup.topological_add_group end submodule section closure variables {R R' : Type u} {M M' : Type v} [semiring R] [topological_space R] [ring R'] [topological_space R'] [topological_space M] [add_comm_monoid M] [topological_space M'] [add_comm_group M'] [module R M] [has_continuous_smul R M] [module R' M'] [has_continuous_smul R' M'] lemma submodule.closure_smul_self_subset (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' (set.univ ×ˢ closure s) ⊆ closure s := calc (λ p : R × M, p.1 • p.2) '' (set.univ ×ˢ closure s) = (λ p : R × M, p.1 • p.2) '' closure (set.univ ×ˢ s) : by simp [closure_prod_eq] ... ⊆ closure ((λ p : R × M, p.1 • p.2) '' (set.univ ×ˢ s)) : image_closure_subset_closure_image continuous_smul ... = closure s : begin congr, ext x, refine ⟨_, λ hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩⟩, rintros ⟨⟨c, y⟩, ⟨hc, hy⟩, rfl⟩, simp [s.smul_mem c hy] end lemma submodule.closure_smul_self_eq (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' (set.univ ×ˢ closure s) = closure s := s.closure_smul_self_subset.antisymm $ λ x hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩ variables [has_continuous_add M] /-- The (topological-space) closure of a submodule of a topological `R`-module `M` is itself a submodule. -/ def submodule.topological_closure (s : submodule R M) : submodule R M := { carrier := closure (s : set M), smul_mem' := λ c x hx, s.closure_smul_self_subset ⟨⟨c, x⟩, ⟨set.mem_univ _, hx⟩, rfl⟩, ..s.to_add_submonoid.topological_closure } @[simp] lemma submodule.topological_closure_coe (s : submodule R M) : (s.topological_closure : set M) = closure (s : set M) := rfl lemma submodule.submodule_topological_closure (s : submodule R M) : s ≤ s.topological_closure := subset_closure lemma submodule.is_closed_topological_closure (s : submodule R M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure lemma submodule.topological_closure_minimal (s : submodule R M) {t : submodule R M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht lemma submodule.topological_closure_mono {s : submodule R M} {t : submodule R M} (h : s ≤ t) : s.topological_closure ≤ t.topological_closure := s.topological_closure_minimal (h.trans t.submodule_topological_closure) t.is_closed_topological_closure /-- The topological closure of a closed submodule `s` is equal to `s`. -/ lemma is_closed.submodule_topological_closure_eq {s : submodule R M} (hs : is_closed (s : set M)) : s.topological_closure = s := le_antisymm (s.topological_closure_minimal rfl.le hs) s.submodule_topological_closure /-- A subspace is dense iff its topological closure is the entire space. -/ lemma submodule.dense_iff_topological_closure_eq_top {s : submodule R M} : dense (s : set M) ↔ s.topological_closure = ⊤ := by { rw [←set_like.coe_set_eq, dense_iff_closure_eq], simp } instance {M' : Type*} [add_comm_monoid M'] [module R M'] [uniform_space M'] [has_continuous_add M'] [has_continuous_smul R M'] [complete_space M'] (U : submodule R M') : complete_space U.topological_closure := is_closed_closure.complete_space_coe /-- A maximal proper subspace of a topological module (i.e a `submodule` satisfying `is_coatom`) is either closed or dense. -/ lemma submodule.is_closed_or_dense_of_is_coatom (s : submodule R M) (hs : is_coatom s) : is_closed (s : set M) ∨ dense (s : set M) := (hs.le_iff.mp s.submodule_topological_closure).swap.imp (is_closed_of_closure_subset ∘ eq.le) submodule.dense_iff_topological_closure_eq_top.mpr lemma linear_map.is_closed_or_dense_ker [has_continuous_add M'] [is_simple_module R' R'] (l : M' →ₗ[R'] R') : is_closed (l.ker : set M') ∨ dense (l.ker : set M') := begin rcases l.surjective_or_eq_zero with (hl|rfl), { refine l.ker.is_closed_or_dense_of_is_coatom (linear_map.is_coatom_ker_of_surjective hl) }, { rw linear_map.ker_zero, left, exact is_closed_univ }, end end closure /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M →ₛₗ[σ] M₂ := (cont : continuous to_fun . tactic.interactive.continuity') notation M ` →SL[`:25 σ `] ` M₂ := continuous_linear_map σ M M₂ notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map (ring_hom.id R) M M₂ notation M ` →L⋆[`:25 R `] ` M₂ := continuous_linear_map (star_ring_end R) M M₂ set_option old_structure_cmd true /-- `continuous_semilinear_map_class F σ M M₂` asserts `F` is a type of bundled continuous `σ`-semilinear maps `M → M₂`. See also `continuous_linear_map_class F R M M₂` for the case where `σ` is the identity map on `R`. A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S` is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = (σ c) • f x`. -/ class continuous_semilinear_map_class (F : Type*) {R S : out_param Type*} [semiring R] [semiring S] (σ : out_param $ R →+* S) (M : out_param Type*) [topological_space M] [add_comm_monoid M] (M₂ : out_param Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends semilinear_map_class F σ M M₂, continuous_map_class F M M₂ -- `σ`, `R` and `S` become metavariables, but they are all outparams so it's OK attribute [nolint dangerous_instance] continuous_semilinear_map_class.to_continuous_map_class /-- `continuous_linear_map_class F R M M₂` asserts `F` is a type of bundled continuous `R`-linear maps `M → M₂`. This is an abbreviation for `continuous_semilinear_map_class F (ring_hom.id R) M M₂`. -/ abbreviation continuous_linear_map_class (F : Type*) (R : out_param Type*) [semiring R] (M : out_param Type*) [topological_space M] [add_comm_monoid M] (M₂ : out_param Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module R M₂] := continuous_semilinear_map_class F (ring_hom.id R) M M₂ set_option old_structure_cmd false /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological semiring `R`. -/ @[nolint has_nonempty_instance] structure continuous_linear_equiv {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M ≃ₛₗ[σ] M₂ := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') notation M ` ≃SL[`:50 σ `] ` M₂ := continuous_linear_equiv σ M M₂ notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv (ring_hom.id R) M M₂ notation M ` ≃L⋆[`:50 R `] ` M₂ := continuous_linear_equiv (star_ring_end R) M M₂ set_option old_structure_cmd true /-- `continuous_semilinear_equiv_class F σ M M₂` asserts `F` is a type of bundled continuous `σ`-semilinear equivs `M → M₂`. See also `continuous_linear_equiv_class F R M M₂` for the case where `σ` is the identity map on `R`. A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S` is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = (σ c) • f x`. -/ class continuous_semilinear_equiv_class (F : Type*) {R : out_param Type*} {S : out_param Type*} [semiring R] [semiring S] (σ : out_param $ R →+* S) {σ' : out_param $ S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : out_param Type*) [topological_space M] [add_comm_monoid M] (M₂ : out_param Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends semilinear_equiv_class F σ M M₂ := (map_continuous : ∀ (f : F), continuous f . tactic.interactive.continuity') (inv_continuous : ∀ (f : F), continuous (inv f) . tactic.interactive.continuity') /-- `continuous_linear_equiv_class F σ M M₂` asserts `F` is a type of bundled continuous `R`-linear equivs `M → M₂`. This is an abbreviation for `continuous_semilinear_equiv_class F (ring_hom.id) M M₂`. -/ abbreviation continuous_linear_equiv_class (F : Type*) (R : out_param Type*) [semiring R] (M : out_param Type*) [topological_space M] [add_comm_monoid M] (M₂ : out_param Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module R M₂] := continuous_semilinear_equiv_class F (ring_hom.id R) M M₂ set_option old_structure_cmd false namespace continuous_semilinear_equiv_class variables (F : Type*) {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] include σ' -- `σ'` becomes a metavariable, but it's OK since it's an outparam @[priority 100, nolint dangerous_instance] instance [s: continuous_semilinear_equiv_class F σ M M₂] : continuous_semilinear_map_class F σ M M₂ := { coe := (coe : F → M → M₂), coe_injective' := @fun_like.coe_injective F _ _ _, ..s } omit σ' end continuous_semilinear_equiv_class section pointwise_limits variables {M₁ M₂ α R S : Type*} [topological_space M₂] [t2_space M₂] [semiring R] [semiring S] [add_comm_monoid M₁] [add_comm_monoid M₂] [module R M₁] [module S M₂] [has_continuous_const_smul S M₂] section variables (M₁ M₂) (σ : R →+* S) lemma is_closed_set_of_map_smul : is_closed {f : M₁ → M₂ | ∀ c x, f (c • x) = σ c • f x} := begin simp only [set.set_of_forall], exact is_closed_Inter (λ c, is_closed_Inter (λ x, is_closed_eq (continuous_apply _) ((continuous_apply _).const_smul _))) end end variables [has_continuous_add M₂] {σ : R →+* S} {l : filter α} /-- Constructs a bundled linear map from a function and a proof that this function belongs to the closure of the set of linear maps. -/ @[simps { fully_applied := ff }] def linear_map_of_mem_closure_range_coe (f : M₁ → M₂) (hf : f ∈ closure (set.range (coe_fn : (M₁ →ₛₗ[σ] M₂) → (M₁ → M₂)))) : M₁ →ₛₗ[σ] M₂ := { to_fun := f, map_smul' := (is_closed_set_of_map_smul M₁ M₂ σ).closure_subset_iff.2 (set.range_subset_iff.2 linear_map.map_smulₛₗ) hf, .. add_monoid_hom_of_mem_closure_range_coe f hf } /-- Construct a bundled linear map from a pointwise limit of linear maps -/ @[simps { fully_applied := ff }] def linear_map_of_tendsto (f : M₁ → M₂) (g : α → M₁ →ₛₗ[σ] M₂) [l.ne_bot] (h : tendsto (λ a x, g a x) l (𝓝 f)) : M₁ →ₛₗ[σ] M₂ := linear_map_of_mem_closure_range_coe f $ mem_closure_of_tendsto h $ eventually_of_forall $ λ a, set.mem_range_self _ variables (M₁ M₂ σ) lemma linear_map.is_closed_range_coe : is_closed (set.range (coe_fn : (M₁ →ₛₗ[σ] M₂) → (M₁ → M₂))) := is_closed_of_closure_subset $ λ f hf, ⟨linear_map_of_mem_closure_range_coe f hf, rfl⟩ end pointwise_limits namespace continuous_linear_map section semiring /-! ### Properties that hold for non-necessarily commutative semirings. -/ variables {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M'₁ : Type*} [topological_space M'₁] [add_comm_monoid M'₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₁ M'₁] [module R₂ M₂] [module R₃ M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M₁ →SL[σ₁₂] M₂) (M₁ →ₛₗ[σ₁₂] M₂) := ⟨to_linear_map⟩ -- make the coercion the preferred form @[simp] lemma to_linear_map_eq_coe (f : M₁ →SL[σ₁₂] M₂) : f.to_linear_map = f := rfl theorem coe_injective : function.injective (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) := by { intros f g H, cases f, cases g, congr' } instance : continuous_semilinear_map_class (M₁ →SL[σ₁₂] M₂) σ₁₂ M₁ M₂ := { coe := λ f, f.to_fun, coe_injective' := λ f g h, coe_injective (fun_like.coe_injective h), map_add := λ f, map_add f.to_linear_map, map_continuous := λ f, f.2, map_smulₛₗ := λ f, f.to_linear_map.map_smul' } /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun (M₁ →SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f.to_fun⟩ @[simp] lemma coe_mk (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ →ₛₗ[σ₁₂] M₂) = f := rfl @[simp] lemma coe_mk' (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ → M₂) = f := rfl @[continuity] protected lemma continuous (f : M₁ →SL[σ₁₂] M₂) : continuous f := f.2 protected lemma uniform_continuous {E₁ E₂ : Type*} [uniform_space E₁] [uniform_space E₂] [add_comm_group E₁] [add_comm_group E₂] [module R₁ E₁] [module R₂ E₂] [uniform_add_group E₁] [uniform_add_group E₂] (f : E₁ →SL[σ₁₂] E₂) : uniform_continuous f := uniform_continuous_add_monoid_hom_of_continuous f.continuous @[simp, norm_cast] lemma coe_inj {f g : M₁ →SL[σ₁₂] M₂} : (f : M₁ →ₛₗ[σ₁₂] M₂) = g ↔ f = g := coe_injective.eq_iff theorem coe_fn_injective : @function.injective (M₁ →SL[σ₁₂] M₂) (M₁ → M₂) coe_fn := fun_like.coe_injective /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : M₁ →SL[σ₁₂] M₂) : M₁ → M₂ := h /-- See Note [custom simps projection]. -/ def simps.coe (h : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂ := h initialize_simps_projections continuous_linear_map (to_linear_map_to_fun → apply, to_linear_map → coe) @[ext] theorem ext {f g : M₁ →SL[σ₁₂] M₂} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h theorem ext_iff {f g : M₁ →SL[σ₁₂] M₂} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Copy of a `continuous_linear_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : M₁ →SL[σ₁₂] M₂) (f' : M₁ → M₂) (h : f' = ⇑f) : M₁ →SL[σ₁₂] M₂ := { to_linear_map := f.to_linear_map.copy f' h, cont := show continuous f', from h.symm ▸ f.continuous } @[simp] lemma coe_copy (f : M₁ →SL[σ₁₂] M₂) (f' : M₁ → M₂) (h : f' = ⇑f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : M₁ →SL[σ₁₂] M₂) (f' : M₁ → M₂) (h : f' = ⇑f) : f.copy f' h = f := fun_like.ext' h -- make some straightforward lemmas available to `simp`. protected lemma map_zero (f : M₁ →SL[σ₁₂] M₂) : f (0 : M₁) = 0 := map_zero f protected lemma map_add (f : M₁ →SL[σ₁₂] M₂) (x y : M₁) : f (x + y) = f x + f y := map_add f x y @[simp] protected lemma map_smulₛₗ (f : M₁ →SL[σ₁₂] M₂) (c : R₁) (x : M₁) : f (c • x) = (σ₁₂ c) • f x := (to_linear_map _).map_smulₛₗ _ _ @[simp] protected lemma map_smul [module R₁ M₂] (f : M₁ →L[R₁] M₂)(c : R₁) (x : M₁) : f (c • x) = c • f x := by simp only [ring_hom.id_apply, continuous_linear_map.map_smulₛₗ] @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_smul R M₁] [module S M₁] [has_smul R M₂] [module S M₂] [linear_map.compatible_smul M₁ M₂ R S] (f : M₁ →L[S] M₂) (c : R) (x : M₁) : f (c • x) = c • f x := linear_map.compatible_smul.map_smul f c x protected lemma map_sum {ι : Type*} (f : M₁ →SL[σ₁₂] M₂) (s : finset ι) (g : ι → M₁) : f (∑ i in s, g i) = ∑ i in s, f (g i) := f.to_linear_map.map_sum @[simp, norm_cast] lemma coe_coe (f : M₁ →SL[σ₁₂] M₂) : ⇑(f : M₁ →ₛₗ[σ₁₂] M₂) = f := rfl @[ext] theorem ext_ring [topological_space R₁] {f g : R₁ →L[R₁] M₁} (h : f 1 = g 1) : f = g := coe_inj.1 $ linear_map.ext_ring h theorem ext_ring_iff [topological_space R₁] {f g : R₁ →L[R₁] M₁} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ /-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure of the `submodule.span` of this set. -/ lemma eq_on_closure_span [t2_space M₂] {s : set M₁} {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : set.eq_on f g (closure (submodule.span R₁ s : set M₁)) := (linear_map.eq_on_span' h).closure f.continuous g.continuous /-- If the submodule generated by a set `s` is dense in the ambient module, then two continuous linear maps equal on `s` are equal. -/ lemma ext_on [t2_space M₂] {s : set M₁} (hs : dense (submodule.span R₁ s : set M₁)) {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : f = g := ext $ λ x, eq_on_closure_span h (hs x) /-- Under a continuous linear map, the image of the `topological_closure` of a submodule is contained in the `topological_closure` of its image. -/ lemma _root_.submodule.topological_closure_map [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] (f : M₁ →SL[σ₁₂] M₂) (s : submodule R₁ M₁) : (s.topological_closure.map (f : M₁ →ₛₗ[σ₁₂] M₂)) ≤ (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure := image_closure_subset_closure_image f.continuous /-- Under a dense continuous linear map, a submodule whose `topological_closure` is `⊤` is sent to another such submodule. That is, the image of a dense set under a map with dense range is dense. -/ lemma _root_.dense_range.topological_closure_map_submodule [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] {f : M₁ →SL[σ₁₂] M₂} (hf' : dense_range f) {s : submodule R₁ M₁} (hs : s.topological_closure = ⊤) : (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [submodule.topological_closure_coe, submodule.top_coe, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image f.continuous hs end section smul_monoid variables {S₂ T₂ : Type*} [monoid S₂] [monoid T₂] variables [distrib_mul_action S₂ M₂] [smul_comm_class R₂ S₂ M₂] [has_continuous_const_smul S₂ M₂] variables [distrib_mul_action T₂ M₂] [smul_comm_class R₂ T₂ M₂] [has_continuous_const_smul T₂ M₂] instance : mul_action S₂ (M₁ →SL[σ₁₂] M₂) := { smul := λ c f, ⟨c • f, (f.2.const_smul _ : continuous (λ x, c • f x))⟩, one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ a b f, ext $ λ x, mul_smul _ _ _ } lemma smul_apply (c : S₂) (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_smul (c : S₂) (f : M₁ →SL[σ₁₂] M₂) : (↑(c • f) : M₁ →ₛₗ[σ₁₂] M₂) = c • f := rfl @[simp, norm_cast] lemma coe_smul' (c : S₂) (f : M₁ →SL[σ₁₂] M₂) : ⇑(c • f) = c • f := rfl instance [has_smul S₂ T₂] [is_scalar_tower S₂ T₂ M₂] : is_scalar_tower S₂ T₂ (M₁ →SL[σ₁₂] M₂) := ⟨λ a b f, ext $ λ x, smul_assoc a b (f x)⟩ instance [smul_comm_class S₂ T₂ M₂] : smul_comm_class S₂ T₂ (M₁ →SL[σ₁₂] M₂) := ⟨λ a b f, ext $ λ x, smul_comm a b (f x)⟩ end smul_monoid /-- The continuous map that is constantly zero. -/ instance: has_zero (M₁ →SL[σ₁₂] M₂) := ⟨⟨0, continuous_zero⟩⟩ instance : inhabited (M₁ →SL[σ₁₂] M₂) := ⟨0⟩ @[simp] lemma default_def : (default : M₁ →SL[σ₁₂] M₂) = 0 := rfl @[simp] lemma zero_apply (x : M₁) : (0 : M₁ →SL[σ₁₂] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ⇑(0 : M₁ →SL[σ₁₂] M₂) = 0 := rfl instance unique_of_left [subsingleton M₁] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique instance unique_of_right [subsingleton M₂] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique lemma exists_ne_zero {f : M₁ →SL[σ₁₂] M₂} (hf : f ≠ 0) : ∃ x, f x ≠ 0 := by { by_contra' h, exact hf (continuous_linear_map.ext h) } section variables (R₁ M₁) /-- the identity map as a continuous linear map. -/ def id : M₁ →L[R₁] M₁ := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M₁ →L[R₁] M₁) := ⟨id R₁ M₁⟩ lemma one_def : (1 : M₁ →L[R₁] M₁) = id R₁ M₁ := rfl lemma id_apply (x : M₁) : id R₁ M₁ x = x := rfl @[simp, norm_cast] lemma coe_id : (id R₁ M₁ : M₁ →ₗ[R₁] M₁) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : ⇑(id R₁ M₁) = _root_.id := rfl @[simp, norm_cast] lemma coe_eq_id {f : M₁ →L[R₁] M₁} : (f : M₁ →ₗ[R₁] M₁) = linear_map.id ↔ f = id _ _ := by rw [← coe_id, coe_inj] @[simp] lemma one_apply (x : M₁) : (1 : M₁ →L[R₁] M₁) x = x := rfl section add variables [has_continuous_add M₂] instance : has_add (M₁ →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply (f g : M₁ →SL[σ₁₂] M₂) (x : M₁) : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add (f g : M₁ →SL[σ₁₂] M₂) : (↑(f + g) : M₁ →ₛₗ[σ₁₂] M₂) = f + g := rfl @[norm_cast] lemma coe_add' (f g : M₁ →SL[σ₁₂] M₂) : ⇑(f + g) = f + g := rfl instance : add_comm_monoid (M₁ →SL[σ₁₂] M₂) := { zero := (0 : M₁ →SL[σ₁₂] M₂), add := (+), zero_add := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_zero := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_comm := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_assoc := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], nsmul := (•), nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_smul] } } @[simp, norm_cast] lemma coe_sum {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ↑(∑ d in t, f d) = (∑ d in t, f d : M₁ →ₛₗ[σ₁₂] M₂) := (add_monoid_hom.mk (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) rfl (λ _ _, rfl)).map_sum _ _ @[simp, norm_cast] lemma coe_sum' {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ⇑(∑ d in t, f d) = ∑ d in t, f d := by simp only [← coe_coe, coe_sum, linear_map.coe_fn_sum] lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) (b : M₁) : (∑ d in t, f d) b = ∑ d in t, f d b := by simp only [coe_sum', finset.sum_apply] end add variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- Composition of bounded linear maps. -/ def comp (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : M₁ →SL[σ₁₃] M₃ := ⟨(g : M₂ →ₛₗ[σ₂₃] M₃).comp ↑f, g.2.comp f.2⟩ infixr ` ∘L `:80 := @continuous_linear_map.comp _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) _ _ _ _ _ _ _ _ _ _ _ _ ring_hom_comp_triple.ids @[simp, norm_cast] lemma coe_comp (h : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (h.comp f : M₁ →ₛₗ[σ₁₃] M₃) = (h : M₂ →ₛₗ[σ₂₃] M₃).comp (f : M₁ →ₛₗ[σ₁₂] M₂) := rfl include σ₁₃ @[simp, norm_cast] lemma coe_comp' (h : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : ⇑(h.comp f) = h ∘ f := rfl lemma comp_apply (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : (g.comp f) x = g (f x) := rfl omit σ₁₃ @[simp] theorem comp_id (f : M₁ →SL[σ₁₂] M₂) : f.comp (id R₁ M₁) = f := ext $ λ x, rfl @[simp] theorem id_comp (f : M₁ →SL[σ₁₂] M₂) : (id R₂ M₂).comp f = f := ext $ λ x, rfl include σ₁₃ @[simp] theorem comp_zero (g : M₂ →SL[σ₂₃] M₃) : g.comp (0 : M₁ →SL[σ₁₂] M₂) = 0 := by { ext, simp } @[simp] theorem zero_comp (f : M₁ →SL[σ₁₂] M₂) : (0 : M₂ →SL[σ₂₃] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃] (g : M₂ →SL[σ₂₃] M₃) (f₁ f₂ : M₁ →SL[σ₁₂] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [has_continuous_add M₃] (g₁ g₂ : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } omit σ₁₃ theorem comp_assoc {R₄ : Type*} [semiring R₄] [module R₄ M₄] {σ₁₄ : R₁ →+* R₄} {σ₂₄ : R₂ →+* R₄} {σ₃₄ : R₃ →+* R₄} [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] (h : M₃ →SL[σ₃₄] M₄) (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M₁ →L[R₁] M₁) := ⟨comp⟩ lemma mul_def (f g : M₁ →L[R₁] M₁) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M₁ →L[R₁] M₁) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M₁ →L[R₁] M₁) (x : M₁) : (f * g) x = f (g x) := rfl instance : monoid_with_zero (M₁ →L[R₁] M₁) := { mul := (*), one := 1, zero := 0, mul_zero := λ f, ext $ λ _, map_zero f, zero_mul := λ _, ext $ λ _, rfl, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, } instance [has_continuous_add M₁] : semiring (M₁ →L[R₁] M₁) := { mul := (*), one := 1, left_distrib := λ f g h, ext $ λ x, map_add f (g x) (h x), right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.monoid_with_zero, ..continuous_linear_map.add_comm_monoid } /-- `continuous_linear_map.to_linear_map` as a `ring_hom`.-/ @[simps] def to_linear_map_ring_hom [has_continuous_add M₁] : (M₁ →L[R₁] M₁) →+* (M₁ →ₗ[R₁] M₁) := { to_fun := to_linear_map, map_zero' := rfl, map_one' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl } section apply_action variables [has_continuous_add M₁] /-- The tautological action by `M₁ →L[R₁] M₁` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_module : module (M₁ →L[R₁] M₁) M₁ := module.comp_hom _ to_linear_map_ring_hom @[simp] protected lemma smul_def (f : M₁ →L[R₁] M₁) (a : M₁) : f • a = f a := rfl /-- `continuous_linear_map.apply_module` is faithful. -/ instance apply_has_faithful_smul : has_faithful_smul (M₁ →L[R₁] M₁) M₁ := ⟨λ _ _, continuous_linear_map.ext⟩ instance apply_smul_comm_class : smul_comm_class R₁ (M₁ →L[R₁] M₁) M₁ := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M₁ →L[R₁] M₁) R₁ M₁ := { smul_comm := continuous_linear_map.map_smul } instance : has_continuous_const_smul (M₁ →L[R₁] M₁) M₁ := ⟨continuous_linear_map.continuous⟩ end apply_action /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : M₁ →L[R₁] (M₂ × M₃) := ⟨(f₁ : M₁ →ₗ[R₁] M₂).prod f₂, f₁.2.prod_mk f₂.2⟩ @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : (f₁.prod f₂ : M₁ →ₗ[R₁] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) (x : M₁) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl section variables (R₁ M₁ M₂) /-- The left injection into a product is a continuous linear map. -/ def inl [module R₁ M₂] : M₁ →L[R₁] M₁ × M₂ := (id R₁ M₁).prod 0 /-- The right injection into a product is a continuous linear map. -/ def inr [module R₁ M₂] : M₂ →L[R₁] M₁ × M₂ := (0 : M₂ →L[R₁] M₁).prod (id R₁ M₂) end variables {F : Type*} @[simp] lemma inl_apply [module R₁ M₂] (x : M₁) : inl R₁ M₁ M₂ x = (x, 0) := rfl @[simp] lemma inr_apply [module R₁ M₂] (x : M₂) : inr R₁ M₁ M₂ x = (0, x) := rfl @[simp, norm_cast] lemma coe_inl [module R₁ M₂] : (inl R₁ M₁ M₂ : M₁ →ₗ[R₁] M₁ × M₂) = linear_map.inl R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_inr [module R₁ M₂] : (inr R₁ M₁ M₂ : M₂ →ₗ[R₁] M₁ × M₂) = linear_map.inr R₁ M₁ M₂ := rfl lemma is_closed_ker [t1_space M₂] [continuous_semilinear_map_class F σ₁₂ M₁ M₂] (f : F) : is_closed (ker f : set M₁) := continuous_iff_is_closed.1 (map_continuous f) _ is_closed_singleton lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] [continuous_semilinear_map_class F σ₁₂ M' M₂] (f : F) : is_complete (ker f : set M') := (is_closed_ker f).is_complete @[priority 100] instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] [continuous_semilinear_map_class F σ₁₂ M' M₂] (f : F) : complete_space (ker f) := (is_closed_ker f).complete_space_coe @[simp] lemma ker_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : ker (f.prod g) = ker f ⊓ ker g := linear_map.ker_prod f g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : M₁ →SL[σ₁₂] p := { cont := f.continuous.subtype_mk _, to_linear_map := (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M₁ →ₛₗ[σ₁₂] p) = (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M₁ →ₛₗ[σ₁₂] M₂).ker_cod_restrict p h /-- `submodule.subtype` as a `continuous_linear_map`. -/ def _root_.submodule.subtypeL (p : submodule R₁ M₁) : p →L[R₁] M₁ := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma _root_.submodule.coe_subtypeL (p : submodule R₁ M₁) : (p.subtypeL : p →ₗ[R₁] M₁) = p.subtype := rfl @[simp] lemma _root_.submodule.coe_subtypeL' (p : submodule R₁ M₁) : ⇑p.subtypeL = p.subtype := rfl @[simp, norm_cast] lemma _root_.submodule.subtypeL_apply (p : submodule R₁ M₁) (x : p) : p.subtypeL x = x := rfl @[simp] lemma _root_.submodule.range_subtypeL (p : submodule R₁ M₁) : range p.subtypeL = p := submodule.range_subtype _ @[simp] lemma _root_.submodule.ker_subtypeL (p : submodule R₁ M₁) : ker p.subtypeL = ⊥ := submodule.ker_subtype _ variables (R₁ M₁ M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst [module R₁ M₂] : M₁ × M₂ →L[R₁] M₁ := { cont := continuous_fst, to_linear_map := linear_map.fst R₁ M₁ M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd [module R₁ M₂] : M₁ × M₂ →L[R₁] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R₁ M₁ M₂ } variables {R₁ M₁ M₂} @[simp, norm_cast] lemma coe_fst [module R₁ M₂] : ↑(fst R₁ M₁ M₂) = linear_map.fst R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_fst' [module R₁ M₂] : ⇑(fst R₁ M₁ M₂) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd [module R₁ M₂] : ↑(snd R₁ M₁ M₂) = linear_map.snd R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_snd' [module R₁ M₂] : ⇑(snd R₁ M₁ M₂) = prod.snd := rfl @[simp] lemma fst_prod_snd [module R₁ M₂] : (fst R₁ M₁ M₂).prod (snd R₁ M₁ M₂) = id R₁ (M₁ × M₂) := ext $ λ ⟨x, y⟩, rfl @[simp] lemma fst_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (fst R₁ M₂ M₃).comp (f.prod g) = f := ext $ λ x, rfl @[simp] lemma snd_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (snd R₁ M₂ M₃).comp (f.prod g) = g := ext $ λ x, rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : (M₁ × M₃) →L[R₁] (M₂ × M₄) := (f₁.comp (fst R₁ M₁ M₃)).prod (f₂.comp (snd R₁ M₁ M₃)) @[simp, norm_cast] lemma coe_prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : ↑(f₁.prod_map f₂) = ((f₁ : M₁ →ₗ[R₁] M₂).prod_map (f₂ : M₃ →ₗ[R₁] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (M₁ × M₂) →L[R₁] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (f₁.coprod f₂ : (M₁ × M₂) →ₗ[R₁] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl lemma range_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : range (f₁.coprod f₂) = range f₁ ⊔ range f₂ := linear_map.range_coprod _ _ section variables {R S : Type*} [semiring R] [semiring S] [module R M₁] [module R M₂] [module R S] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [has_continuous_smul S M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`). See also `continuous_linear_map.smul_rightₗ` and `continuous_linear_map.smul_rightL`. -/ def smul_right (c : M₁ →L[R] S) (f : M₂) : M₁ →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M₁ →L[R] S} {f : M₂} {x : M₁} : (smul_right c f : M₁ → M₂) x = c x • f := rfl end variables [module R₁ M₂] [topological_space R₁] [has_continuous_smul R₁ M₂] @[simp] lemma smul_right_one_one (c : R₁ →L[R₁] M₂) : smul_right (1 : R₁ →L[R₁] R₁) (c 1) = c := by ext; simp [← continuous_linear_map.map_smul_of_tower] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R₁ →L[R₁] R₁) f = smul_right (1 : R₁ →L[R₁] R₁) f' ↔ f = f' := by simp only [ext_ring_iff, smul_right_apply, one_apply, one_smul] lemma smul_right_comp [has_continuous_mul R₁] {x : M₂} {c : R₁} : (smul_right (1 : R₁ →L[R₁] R₁) x).comp (smul_right (1 : R₁ →L[R₁] R₁) c) = smul_right (1 : R₁ →L[R₁] R₁) (c • x) := by { ext, simp [mul_smul] } end semiring section pi variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂] {ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)] [∀i, module R (φ i)] /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) := ⟨linear_map.pi (λ i, f i), continuous_pi (λ i, (f i).continuous)⟩ @[simp] lemma coe_pi' (f : Π i, M →L[R] φ i) : ⇑(pi f) = λ c i, f i c := rfl @[simp] lemma coe_pi (f : Π i, M →L[R] φ i) : (pi f : M →ₗ[R] Π i, φ i) = linear_map.pi (λ i, f i) := rfl lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) : pi f c i = f i c := rfl lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by { simp only [ext_iff, pi_apply, function.funext_iff], exact forall_swap } lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := ext $ λ _, rfl lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj (i : ι) : (Πi, φ i) →L[R] φ i := ⟨linear_map.proj i, continuous_apply _⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i : (Πi, φ i) →L[R] φ i) : submodule R (Πi, φ i)) = ⊥ := linear_map.infi_ker_proj variables (R φ) /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i : (Πi, φ i) →L[R] φ i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) := { to_linear_equiv := linear_map.infi_ker_proj_equiv R φ hd hu, continuous_to_fun := continuous_pi (λ i, begin have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i : (Πi, φ i) →L[R] φ i) : submodule R (Πi, φ i))), have := continuous.comp (by exact continuous_apply i) this, exact this end), continuous_inv_fun := continuous.subtype_mk (continuous_pi (λ i, begin dsimp, split_ifs; [apply continuous_apply, exact continuous_zero] end)) _ } end pi section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {R₃ : Type*} [ring R₃] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R₂ M₂] [module R₃ M₃] {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} section protected lemma map_neg (f : M →SL[σ₁₂] M₂) (x : M) : f (-x) = - (f x) := map_neg _ _ protected lemma map_sub (f : M →SL[σ₁₂] M₂) (x y : M) : f (x - y) = f x - f y := map_sub _ _ _ @[simp] lemma sub_apply' (f g : M →SL[σ₁₂] M₂) (x : M) : ((f : M →ₛₗ[σ₁₂] M₂) - g) x = f x - g x := rfl end section variables [module R M₂] [module R M₃] [module R M₄] lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (f.prod g) = (range f).prod (range g) := linear_map.range_prod_eq h lemma ker_prod_ker_le_ker_coprod [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) : (linear_map.ker f).prod (linear_map.ker g) ≤ linear_map.ker (f.coprod g) := linear_map.ker_prod_ker_le_ker_coprod f.to_linear_map g.to_linear_map lemma ker_coprod_of_disjoint_range [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) (hd : disjoint (range f) (range g)) : linear_map.ker (f.coprod g) = (linear_map.ker f).prod (linear_map.ker g) := linear_map.ker_coprod_of_disjoint_range f.to_linear_map g.to_linear_map hd end section variables [topological_add_group M₂] instance : has_neg (M →SL[σ₁₂] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply (f : M →SL[σ₁₂] M₂) (x : M) : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg (f : M →SL[σ₁₂] M₂) : (↑(-f) : M →ₛₗ[σ₁₂] M₂) = -f := rfl @[norm_cast] lemma coe_neg' (f : M →SL[σ₁₂] M₂) : ⇑(-f) = -f := rfl instance : has_sub (M →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩ instance : add_comm_group (M →SL[σ₁₂] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := (•), zsmul := (•), zsmul_zero' := λ f, by { ext, simp }, zsmul_succ' := λ n f, by { ext, simp [add_smul, add_comm] }, zsmul_neg' := λ n f, by { ext, simp [nat.succ_eq_add_one, add_smul] }, .. continuous_linear_map.add_comm_monoid, .. }; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm, sub_eq_add_neg] lemma sub_apply (f g : M →SL[σ₁₂] M₂) (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub (f g : M →SL[σ₁₂] M₂) : (↑(f - g) : M →ₛₗ[σ₁₂] M₂) = f - g := rfl @[simp, norm_cast] lemma coe_sub' (f g : M →SL[σ₁₂] M₂) : ⇑(f - g) = f - g := rfl end @[simp] lemma comp_neg [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →SL[σ₂₃] M₃) (f : M →SL[σ₁₂] M₂) : g.comp (-f) = -g.comp f := by { ext, simp } @[simp] lemma neg_comp [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [topological_add_group M₃] (g : M₂ →SL[σ₂₃] M₃) (f : M →SL[σ₁₂] M₂) : (-g).comp f = -g.comp f := by { ext, simp } @[simp] lemma comp_sub [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →SL[σ₂₃] M₃) (f₁ f₂ : M →SL[σ₁₂] M₂) : g.comp (f₁ - f₂) = g.comp f₁ - g.comp f₂ := by { ext, simp } @[simp] lemma sub_comp [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [topological_add_group M₃] (g₁ g₂ : M₂ →SL[σ₂₃] M₃) (f : M →SL[σ₁₂] M₂) : (g₁ - g₂).comp f = g₁.comp f - g₂.comp f := by { ext, simp } instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, ..continuous_linear_map.semiring, ..continuous_linear_map.add_comm_group } lemma smul_right_one_pow [topological_space R] [topological_ring R] (c : R) (n : ℕ) : (smul_right (1 : R →L[R] R) c)^n = smul_right (1 : R →L[R] R) (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end section variables {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) : M →L[R] (linear_map.ker f₁) := (id R M - f₂.comp f₁).cod_restrict (linear_map.ker f₁) $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : linear_map.ker f₁) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.ext_iff_val.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.ext_iff_val.2 $ by simp [h y] end end ring section division_monoid variables {R M : Type*} /-- A nonzero continuous linear functional is open. -/ protected lemma is_open_map_of_ne_zero [topological_space R] [division_ring R] [has_continuous_sub R] [add_comm_group M] [topological_space M] [has_continuous_add M] [module R M] [has_continuous_smul R M] (f : M →L[R] R) (hf : f ≠ 0) : is_open_map f := let ⟨x, hx⟩ := exists_ne_zero hf in is_open_map.of_sections $ λ y, ⟨λ a, y + (a - f y) • (f x)⁻¹ • x, continuous.continuous_at $ by continuity, by simp, λ a, by simp [hx]⟩ end division_monoid section smul_monoid -- The M's are used for semilinear maps, and the N's for plain linear maps variables {R R₂ R₃ S S₃ : Type*} [semiring R] [semiring R₂] [semiring R₃] [monoid S] [monoid S₃] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R₂ M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] [module R₃ M₃] {N₂ : Type*} [topological_space N₂] [add_comm_monoid N₂] [module R N₂] {N₃ : Type*} [topological_space N₃] [add_comm_monoid N₃] [module R N₃] [distrib_mul_action S₃ M₃] [smul_comm_class R₃ S₃ M₃] [has_continuous_const_smul S₃ M₃] [distrib_mul_action S N₃] [smul_comm_class R S N₃] [has_continuous_const_smul S N₃] {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] include σ₁₃ @[simp] lemma smul_comp (c : S₃) (h : M₂ →SL[σ₂₃] M₃) (f : M →SL[σ₁₂] M₂) : (c • h).comp f = c • (h.comp f) := rfl omit σ₁₃ variables [distrib_mul_action S₃ M₂] [has_continuous_const_smul S₃ M₂] [smul_comm_class R₂ S₃ M₂] variables [distrib_mul_action S N₂] [has_continuous_const_smul S N₂] [smul_comm_class R S N₂] @[simp] lemma comp_smul [linear_map.compatible_smul N₂ N₃ S R] (hₗ : N₂ →L[R] N₃) (c : S) (fₗ : M →L[R] N₂) : hₗ.comp (c • fₗ) = c • (hₗ.comp fₗ) := by { ext x, exact hₗ.map_smul_of_tower c (fₗ x) } include σ₁₃ @[simp] lemma comp_smulₛₗ [smul_comm_class R₂ R₂ M₂] [smul_comm_class R₃ R₃ M₃] [has_continuous_const_smul R₂ M₂] [has_continuous_const_smul R₃ M₃] (h : M₂ →SL[σ₂₃] M₃) (c : R₂) (f : M →SL[σ₁₂] M₂) : h.comp (c • f) = (σ₂₃ c) • (h.comp f) := by { ext x, simp only [coe_smul', coe_comp', function.comp_app, pi.smul_apply, continuous_linear_map.map_smulₛₗ] } omit σ₁₃ instance [has_continuous_add M₂] : distrib_mul_action S₃ (M →SL[σ₁₂] M₂) := { smul_add := λ a f g, ext $ λ x, smul_add a (f x) (g x), smul_zero := λ a, ext $ λ x, smul_zero _ } end smul_monoid section smul -- The M's are used for semilinear maps, and the N's for plain linear maps variables {R R₂ R₃ S S₃ : Type*} [semiring R] [semiring R₂] [semiring R₃] [semiring S] [semiring S₃] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R₂ M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] [module R₃ M₃] {N₂ : Type*} [topological_space N₂] [add_comm_monoid N₂] [module R N₂] {N₃ : Type*} [topological_space N₃] [add_comm_monoid N₃] [module R N₃] [module S₃ M₃] [smul_comm_class R₃ S₃ M₃] [has_continuous_const_smul S₃ M₃] [module S N₂] [has_continuous_const_smul S N₂] [smul_comm_class R S N₂] [module S N₃] [smul_comm_class R S N₃] [has_continuous_const_smul S N₃] {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] (c : S) (h : M₂ →SL[σ₂₃] M₃) (f g : M →SL[σ₁₂] M₂) (x y z : M) /-- `continuous_linear_map.prod` as an `equiv`. -/ @[simps apply] def prod_equiv : ((M →L[R] N₂) × (M →L[R] N₃)) ≃ (M →L[R] N₂ × N₃) := { 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 } lemma prod_ext_iff {f g : M × N₂ →L[R] N₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := by { simp only [← coe_inj, linear_map.prod_ext_iff], refl } @[ext] lemma prod_ext {f g : M × N₂ →L[R] N₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ variables [has_continuous_add M₂] [has_continuous_add M₃] [has_continuous_add N₂] instance : module S₃ (M →SL[σ₁₃] M₃) := { zero_smul := λ _, ext $ λ _, zero_smul _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _ } instance [module S₃ᵐᵒᵖ M₃] [is_central_scalar S₃ M₃] : is_central_scalar S₃ (M →SL[σ₁₃] M₃) := { op_smul_eq_smul := λ _ _, ext $ λ _, op_smul_eq_smul _ _ } variables (S) [has_continuous_add N₃] /-- `continuous_linear_map.prod` as a `linear_equiv`. -/ @[simps apply] def prodₗ : ((M →L[R] N₂) × (M →L[R] N₃)) ≃ₗ[S] (M →L[R] N₂ × N₃) := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. prod_equiv } /-- The coercion from `M →L[R] M₂` to `M →ₗ[R] M₂`, as a linear map. -/ @[simps] def coe_lm : (M →L[R] N₃) →ₗ[S] (M →ₗ[R] N₃) := { to_fun := coe, map_add' := λ f g, coe_add f g, map_smul' := λ c f, coe_smul c f } variables {S} (σ₁₃) /-- The coercion from `M →SL[σ] M₂` to `M →ₛₗ[σ] M₂`, as a linear map. -/ @[simps] def coe_lmₛₗ : (M →SL[σ₁₃] M₃) →ₗ[S₃] (M →ₛₗ[σ₁₃] M₃) := { to_fun := coe, map_add' := λ f g, coe_add f g, map_smul' := λ c f, coe_smul c f } variables {σ₁₃} end smul section smul_rightₗ variables {R S T M M₂ : Type*} [semiring R] [semiring S] [semiring T] [module R S] [add_comm_monoid M₂] [module R M₂] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [topological_space M₂] [has_continuous_smul S M₂] [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_add M₂] [module T M₂] [has_continuous_const_smul T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] /-- Given `c : E →L[𝕜] 𝕜`, `c.smul_rightₗ` is the linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. See also `continuous_linear_map.smul_rightL`. -/ def smul_rightₗ (c : M →L[R] S) : M₂ →ₗ[T] (M →L[R] M₂) := { to_fun := c.smul_right, map_add' := λ x y, by { ext e, apply smul_add }, map_smul' := λ a x, by { ext e, dsimp, apply smul_comm } } @[simp] lemma coe_smul_rightₗ (c : M →L[R] S) : ⇑(smul_rightₗ c : M₂ →ₗ[T] (M →L[R] M₂)) = c.smul_right := rfl end smul_rightₗ section comm_ring variables {R : Type*} [comm_ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [has_continuous_const_smul R M₃] variables [topological_add_group M₂] [has_continuous_const_smul R M₂] instance : algebra R (M₂ →L[R] M₂) := algebra.of_module smul_comp (λ _ _ _, comp_smul _ _ _) end comm_ring section restrict_scalars variables {A M M₂ : Type*} [ring A] [add_comm_group M] [add_comm_group M₂] [module A M] [module A M₂] [topological_space M] [topological_space M₂] (R : Type*) [ring R] [module R M] [module R M₂] [linear_map.compatible_smul M M₂ R A] /-- If `A` is an `R`-algebra, then a continuous `A`-linear map can be interpreted as a continuous `R`-linear map. We assume `linear_map.compatible_smul M M₂ R A` to match assumptions of `linear_map.map_smul_of_tower`. -/ def restrict_scalars (f : M →L[A] M₂) : M →L[R] M₂ := ⟨(f : M →ₗ[A] M₂).restrict_scalars R, f.continuous⟩ variable {R} @[simp, norm_cast] lemma coe_restrict_scalars (f : M →L[A] M₂) : (f.restrict_scalars R : M →ₗ[R] M₂) = (f : M →ₗ[A] M₂).restrict_scalars R := rfl @[simp] lemma coe_restrict_scalars' (f : M →L[A] M₂) : ⇑(f.restrict_scalars R) = f := rfl @[simp] lemma restrict_scalars_zero : (0 : M →L[A] M₂).restrict_scalars R = 0 := rfl section variable [topological_add_group M₂] @[simp] lemma restrict_scalars_add (f g : M →L[A] M₂) : (f + g).restrict_scalars R = f.restrict_scalars R + g.restrict_scalars R := rfl @[simp] lemma restrict_scalars_neg (f : M →L[A] M₂) : (-f).restrict_scalars R = -f.restrict_scalars R := rfl end variables {S : Type*} [ring S] [module S M₂] [has_continuous_const_smul S M₂] [smul_comm_class A S M₂] [smul_comm_class R S M₂] @[simp] lemma restrict_scalars_smul (c : S) (f : M →L[A] M₂) : (c • f).restrict_scalars R = c • f.restrict_scalars R := rfl variables (A M M₂ R S) [topological_add_group M₂] /-- `continuous_linear_map.restrict_scalars` as a `linear_map`. See also `continuous_linear_map.restrict_scalarsL`. -/ def restrict_scalarsₗ : (M →L[A] M₂) →ₗ[S] (M →L[R] M₂) := { to_fun := restrict_scalars R, map_add' := restrict_scalars_add, map_smul' := restrict_scalars_smul } variables {A M M₂ R S} @[simp] lemma coe_restrict_scalarsₗ : ⇑(restrict_scalarsₗ A M M₂ R S) = restrict_scalars R := rfl end restrict_scalars end continuous_linear_map namespace continuous_linear_equiv section add_comm_monoid variables {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} [semiring R₁] [semiring R₂] [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₁ : R₂ →+* R₁} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} [ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃] {σ₁₃ : R₁ →+* R₃} {σ₃₁ : R₃ →+* R₁} [ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M'₁ : Type*} [topological_space M'₁] [add_comm_monoid M'₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₁ M'₁] [module R₂ M₂] [module R₃ M₃] include σ₂₁ /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M₁ ≃SL[σ₁₂] M₂) : M₁ →SL[σ₁₂] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M₁ ≃SL[σ₁₂] M₂) (M₁ →SL[σ₁₂] M₂) := ⟨to_continuous_linear_map⟩ instance : continuous_semilinear_equiv_class (M₁ ≃SL[σ₁₂] M₂) σ₁₂ M₁ M₂ := { coe := λ f, f, inv := λ f, f.inv_fun, coe_injective' := λ f g h₁ h₂, by { cases f with f' _, cases g with g' _, cases f', cases g', congr' }, left_inv := λ f, f.left_inv, right_inv := λ f, f.right_inv, map_add := λ f, f.map_add', map_smulₛₗ := λ f, f.map_smul', map_continuous := continuous_to_fun, inv_continuous := continuous_inv_fun } /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M₁ ≃SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f⟩ @[simp] theorem coe_def_rev (e : M₁ ≃SL[σ₁₂] M₂) : e.to_continuous_linear_map = e := rfl theorem coe_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : (e : M₁ →SL[σ₁₂] M₂) b = e b := rfl @[simp] lemma coe_to_linear_equiv (f : M₁ ≃SL[σ₁₂] M₂) : ⇑f.to_linear_equiv = f := rfl @[simp, norm_cast] lemma coe_coe (e : M₁ ≃SL[σ₁₂] M₂) : ⇑(e : M₁ →SL[σ₁₂] M₂) = e := rfl lemma to_linear_equiv_injective : function.injective (to_linear_equiv : (M₁ ≃SL[σ₁₂] M₂) → (M₁ ≃ₛₗ[σ₁₂] M₂)) | ⟨e, _, _⟩ ⟨e', _, _⟩ rfl := rfl @[ext] lemma ext {f g : M₁ ≃SL[σ₁₂] M₂} (h : (f : M₁ → M₂) = g) : f = g := to_linear_equiv_injective $ linear_equiv.ext $ congr_fun h lemma coe_injective : function.injective (coe : (M₁ ≃SL[σ₁₂] M₂) → (M₁ →SL[σ₁₂] M₂)) := λ e e' h, ext $ funext $ continuous_linear_map.ext_iff.1 h @[simp, norm_cast] lemma coe_inj {e e' : M₁ ≃SL[σ₁₂] M₂} : (e : M₁ →SL[σ₁₂] M₂) = e' ↔ e = e' := coe_injective.eq_iff /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : M₁ ≃ₜ M₂ := { to_equiv := e.to_linear_equiv.to_equiv, ..e } @[simp] lemma coe_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : ⇑e.to_homeomorph = e := rfl lemma image_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' closure s = closure (e '' s) := e.to_homeomorph.image_closure s lemma preimage_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e ⁻¹' closure s = closure (e ⁻¹' s) := e.to_homeomorph.preimage_closure s @[simp] lemma is_closed_image (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : is_closed (e '' s) ↔ is_closed s := e.to_homeomorph.is_closed_image lemma map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e (𝓝 x) = 𝓝 (e x) := e.to_homeomorph.map_nhds_eq x -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M₁ ≃SL[σ₁₂] M₂) : e (0 : M₁) = 0 := (e : M₁ →SL[σ₁₂] M₂).map_zero @[simp] lemma map_add (e : M₁ ≃SL[σ₁₂] M₂) (x y : M₁) : e (x + y) = e x + e y := (e : M₁ →SL[σ₁₂] M₂).map_add x y @[simp] lemma map_smulₛₗ (e : M₁ ≃SL[σ₁₂] M₂) (c : R₁) (x : M₁) : e (c • x) = σ₁₂ c • (e x) := (e : M₁ →SL[σ₁₂] M₂).map_smulₛₗ c x omit σ₂₁ @[simp] lemma map_smul [module R₁ M₂] (e : M₁ ≃L[R₁] M₂) (c : R₁) (x : M₁) : e (c • x) = c • (e x) := (e : M₁ →L[R₁] M₂).map_smul c x include σ₂₁ @[simp] lemma map_eq_zero_iff (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff attribute [continuity] continuous_linear_equiv.continuous_to_fun continuous_linear_equiv.continuous_inv_fun @[continuity] protected lemma continuous (e : M₁ ≃SL[σ₁₂] M₂) : continuous (e : M₁ → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : continuous_on (e : M₁ → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : continuous_at (e : M₁ → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} {x : M₁} : continuous_within_at (e : M₁ → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff omit σ₂₁ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R₁] {f g : R₁ ≃L[R₁] M₁} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R₁ M₁) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M₁ ≃L[R₁] M₁ := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R₁ M₁ } end @[simp, norm_cast] lemma coe_refl : ↑(continuous_linear_equiv.refl R₁ M₁) = continuous_linear_map.id R₁ M₁ := rfl @[simp, norm_cast] lemma coe_refl' : ⇑(continuous_linear_equiv.refl R₁ M₁) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M₁ ≃SL[σ₁₂] M₂) : M₂ ≃SL[σ₂₁] M₁ := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } include σ₂₁ @[simp] lemma symm_to_linear_equiv (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } @[simp] lemma symm_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : M₁ ≃SL[σ₁₂] M₂) : M₁ → M₂ := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : M₁ ≃SL[σ₁₂] M₂) : M₂ → M₁ := h.symm initialize_simps_projections continuous_linear_equiv (to_linear_equiv_to_fun → apply, to_linear_equiv_inv_fun → symm_apply) lemma symm_map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e.symm (𝓝 (e x)) = 𝓝 x := e.to_homeomorph.symm_map_nhds_eq x omit σ₂₁ include σ₂₁ σ₃₂ σ₃₁ /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : M₁ ≃SL[σ₁₃] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } include σ₁₃ @[simp] lemma trans_to_linear_equiv (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } omit σ₁₃ σ₂₁ σ₃₂ σ₃₁ /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (M₁ × M₃) ≃L[R₁] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (e.prod e' : (M₁ × M₃) →L[R₁] (M₂ × M₄)) = (e : M₁ →L[R₁] M₂).prod_map (e' : M₃ →L[R₁] M₄) := rfl lemma prod_symm [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (e.prod e').symm = e.symm.prod e'.symm := rfl include σ₂₁ protected theorem bijective (e : M₁ ≃SL[σ₁₂] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective protected theorem injective (e : M₁ ≃SL[σ₁₂] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective protected theorem surjective (e : M₁ ≃SL[σ₁₂] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective include σ₃₂ σ₃₁ σ₁₃ @[simp] theorem trans_apply (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) (c : M₁) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl omit σ₃₂ σ₃₁ σ₁₃ @[simp] theorem apply_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (c : M₂) : e (e.symm c) = c := e.1.right_inv c @[simp] theorem symm_apply_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : e.symm (e b) = b := e.1.left_inv b include σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_trans_apply (e₁ : M₂ ≃SL[σ₂₁] M₁) (e₂ : M₃ ≃SL[σ₃₂] M₂) (c : M₁) : (e₂.trans e₁).symm c = e₂.symm (e₁.symm c) := rfl omit σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_image_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e.symm '' (e '' s) = s := e.to_linear_equiv.to_equiv.symm_image_image s @[simp] theorem image_symm_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e '' (e.symm '' s) = s := e.symm.symm_image_image s include σ₃₂ σ₃₁ @[simp, norm_cast] lemma comp_coe (f : M₁ ≃SL[σ₁₂] M₂) (f' : M₂ ≃SL[σ₂₃] M₃) : (f' : M₂ →SL[σ₂₃] M₃).comp (f : M₁ →SL[σ₁₂] M₂) = (f.trans f' : M₁ →SL[σ₁₃] M₃) := rfl omit σ₃₂ σ₃₁ σ₂₁ @[simp] theorem coe_comp_coe_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ →SL[σ₁₂] M₂).comp (e.symm : M₂ →SL[σ₂₁] M₁) = continuous_linear_map.id R₂ M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ →SL[σ₂₁] M₁).comp (e : M₁ →SL[σ₁₂] M₂) = continuous_linear_map.id R₁ M₁ := continuous_linear_map.ext e.symm_apply_apply include σ₂₁ @[simp] lemma symm_comp_self (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ → M₁) ∘ (e : M₁ → M₂) = id := by{ ext x, exact symm_apply_apply e x } @[simp] lemma self_comp_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ → M₂) ∘ (e.symm : M₂ → M₁) = id := by{ ext x, exact apply_symm_apply e x } @[simp] theorem symm_symm (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.symm = e := by { ext x, refl } omit σ₂₁ @[simp] lemma refl_symm : (continuous_linear_equiv.refl R₁ M₁).symm = continuous_linear_equiv.refl R₁ M₁ := rfl include σ₂₁ theorem symm_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : e.symm.symm x = e x := rfl lemma symm_apply_eq (e : M₁ ≃SL[σ₁₂] M₂) {x y} : e.symm x = y ↔ x = e y := e.to_linear_equiv.symm_apply_eq lemma eq_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) {x y} : y = e.symm x ↔ e y = x := e.to_linear_equiv.eq_symm_apply protected lemma image_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' s = e.symm ⁻¹' s := e.to_linear_equiv.to_equiv.image_eq_preimage s protected lemma image_symm_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e.symm '' s = e ⁻¹' s := by rw [e.symm.image_eq_preimage, e.symm_symm] @[simp] protected lemma symm_preimage_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e.symm ⁻¹' (e ⁻¹' s) = s := e.to_linear_equiv.to_equiv.symm_preimage_preimage s @[simp] protected lemma preimage_symm_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e ⁻¹' (e.symm ⁻¹' s) = s := e.symm.symm_preimage_preimage s protected lemma uniform_embedding {E₁ E₂ : Type*} [uniform_space E₁] [uniform_space E₂] [add_comm_group E₁] [add_comm_group E₂] [module R₁ E₁] [module R₂ E₂] [uniform_add_group E₁] [uniform_add_group E₂] (e : E₁ ≃SL[σ₁₂] E₂) : uniform_embedding e := e.to_linear_equiv.to_equiv.uniform_embedding e.to_continuous_linear_map.uniform_continuous e.symm.to_continuous_linear_map.uniform_continuous protected lemma _root_.linear_equiv.uniform_embedding {E₁ E₂ : Type*} [uniform_space E₁] [uniform_space E₂] [add_comm_group E₁] [add_comm_group E₂] [module R₁ E₁] [module R₂ E₂] [uniform_add_group E₁] [uniform_add_group E₂] (e : E₁ ≃ₛₗ[σ₁₂] E₂) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding ({ continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } : E₁ ≃SL[σ₁₂] E₂) omit σ₂₁ /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M₁) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M₁ ≃SL[σ₁₂] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } include σ₂₁ @[simp] lemma equiv_of_inverse_apply (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl omit σ₂₁ variable (M₁) /-- The continuous linear equivalences from `M` to itself form a group under composition. -/ instance automorphism_group : group (M₁ ≃L[R₁] M₁) := { mul := λ f g, g.trans f, one := continuous_linear_equiv.refl R₁ M₁, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } variables {M₁} {R₄ : Type*} [semiring R₄] [module R₄ M₄] {σ₃₄ : R₃ →+* R₄} {σ₄₃ : R₄ →+* R₃} [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] {σ₂₄ : R₂ →+* R₄} {σ₁₄ : R₁ →+* R₄} [ring_hom_comp_triple σ₂₁ σ₁₄ σ₂₄] [ring_hom_comp_triple σ₂₄ σ₄₃ σ₂₃] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] /-- The continuous linear equivalence between `ulift M₁` and `M₁`. -/ def ulift : ulift M₁ ≃L[R₁] M₁ := { map_add' := λ x y, rfl, map_smul' := λ c x, rfl, continuous_to_fun := continuous_ulift_down, continuous_inv_fun := continuous_ulift_up, .. equiv.ulift } include σ₂₁ σ₃₄ σ₂₃ σ₂₄ σ₁₃ /-- A pair of continuous (semi)linear equivalences generates an equivalence between the spaces of continuous linear maps. See also `continuous_linear_equiv.arrow_congr`. -/ @[simps] def arrow_congr_equiv (e₁₂ : M₁ ≃SL[σ₁₂] M₂) (e₄₃ : M₄ ≃SL[σ₄₃] M₃) : (M₁ →SL[σ₁₄] M₄) ≃ (M₂ →SL[σ₂₃] M₃) := { to_fun := λ f, (e₄₃ : M₄ →SL[σ₄₃] M₃).comp (f.comp (e₁₂.symm : M₂ →SL[σ₂₁] M₁)), inv_fun := λ f, (e₄₃.symm : M₃ →SL[σ₃₄] M₄).comp (f.comp (e₁₂ : M₁ →SL[σ₁₂] M₂)), left_inv := λ f, continuous_linear_map.ext $ λ x, by simp only [continuous_linear_map.comp_apply, symm_apply_apply, coe_coe], right_inv := λ f, continuous_linear_map.ext $ λ x, by simp only [continuous_linear_map.comp_apply, apply_symm_apply, coe_coe] } end add_comm_monoid section add_comm_group variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] variables [topological_add_group M₄] /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl end add_comm_group section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R₂ M₂] variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ @[simp] lemma map_sub (e : M ≃SL[σ₁₂] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →SL[σ₁₂] M₂).map_sub x y @[simp] lemma map_neg (e : M ≃SL[σ₁₂] M₂) (x : M) : e (-x) = -e x := (e : M →SL[σ₁₂] M₂).map_neg x omit σ₂₁ section /-! The next theorems cover the identification between `M ≃L[𝕜] M`and the group of units of the ring `M →L[R] M`. -/ variables [topological_add_group M] /-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself. -/ def of_unit (f : (M →L[R] M)ˣ) : (M ≃L[R] M) := { to_linear_equiv := { to_fun := f.val, map_add' := by simp, map_smul' := by simp, inv_fun := f.inv, left_inv := λ x, show (f.inv * f.val) x = x, by {rw f.inv_val, simp}, right_inv := λ x, show (f.val * f.inv) x = x, by {rw f.val_inv, simp}, }, continuous_to_fun := f.val.continuous, continuous_inv_fun := f.inv.continuous } /-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/ def to_unit (f : (M ≃L[R] M)) : (M →L[R] M)ˣ := { val := f, inv := f.symm, val_inv := by {ext, simp}, inv_val := by {ext, simp} } variables (R M) /-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively equivalent to the type of continuous linear equivalences between `M` and itself. -/ def units_equiv : (M →L[R] M)ˣ ≃* (M ≃L[R] M) := { to_fun := of_unit, inv_fun := to_unit, left_inv := λ f, by {ext, refl}, right_inv := λ f, by {ext, refl}, map_mul' := λ x y, by {ext, refl} } @[simp] lemma units_equiv_apply (f : (M →L[R] M)ˣ) (x : M) : units_equiv R M f x = f x := rfl end section variables (R) [topological_space R] [has_continuous_mul R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `Rˣ`. -/ def units_equiv_aut : Rˣ ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u) (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : Rˣ) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : Rˣ) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [module R M₂] [topological_add_group M] open _root_.continuous_linear_map (id fst snd) open _root_.linear_map (mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × ker f₁:= equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (ker f₁).subtypeL) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × ker f₁) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end ring section variables (ι R M : Type*) [unique ι] [semiring R] [add_comm_monoid M] [module R M] [topological_space M] /-- If `ι` has a unique element, then `ι → M` is continuously linear equivalent to `M`. -/ def fun_unique : (ι → M) ≃L[R] M := { to_linear_equiv := linear_equiv.fun_unique ι R M, .. homeomorph.fun_unique ι M } variables {ι R M} @[simp] lemma coe_fun_unique : ⇑(fun_unique ι R M) = function.eval default := rfl @[simp] lemma coe_fun_unique_symm : ⇑(fun_unique ι R M).symm = function.const ι := rfl variables (R M) /-- Continuous linear equivalence between dependent functions `Π i : fin 2, M i` and `M 0 × M 1`. -/ @[simps { fully_applied := ff }] def pi_fin_two (M : fin 2 → Type*) [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] [Π i, topological_space (M i)] : (Π i, M i) ≃L[R] M 0 × M 1 := { to_linear_equiv := linear_equiv.pi_fin_two R M, .. homeomorph.pi_fin_two M } /-- Continuous linear equivalence between vectors in `M² = fin 2 → M` and `M × M`. -/ @[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → M) ≃L[R] M × M := { to_linear_equiv := linear_equiv.fin_two_arrow R M, .. pi_fin_two R (λ _, M) } end end continuous_linear_equiv namespace continuous_linear_map open_locale classical variables {R : Type*} {M : Type*} {M₂ : Type*} [topological_space M] [topological_space M₂] section variables [semiring R] variables [add_comm_monoid M₂] [module R M₂] variables [add_comm_monoid M] [module R M] /-- Introduce a function `inverse` from `M →L[R] M₂` to `M₂ →L[R] M`, which sends `f` to `f.symm` if `f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : (M →L[R] M₂) → (M₂ →L[R] M) := λ f, if h : ∃ (e : M ≃L[R] M₂), (e : M →L[R] M₂) = f then ((classical.some h).symm : M₂ →L[R] M) else 0 /-- By definition, if `f` is invertible then `inverse f = f.symm`. -/ @[simp] lemma inverse_equiv (e : M ≃L[R] M₂) : inverse (e : M →L[R] M₂) = e.symm := begin have h : ∃ (e' : M ≃L[R] M₂), (e' : M →L[R] M₂) = ↑e := ⟨e, rfl⟩, simp only [inverse, dif_pos h], congr, exact_mod_cast (classical.some_spec h) end /-- By definition, if `f` is not invertible then `inverse f = 0`. -/ @[simp] lemma inverse_non_equiv (f : M →L[R] M₂) (h : ¬∃ (e' : M ≃L[R] M₂), ↑e' = f) : inverse f = 0 := dif_neg h end section variables [ring R] variables [add_comm_group M] [topological_add_group M] [module R M] variables [add_comm_group M₂] [module R M₂] @[simp] lemma ring_inverse_equiv (e : M ≃L[R] M) : ring.inverse ↑e = inverse (e : M →L[R] M) := begin suffices : ring.inverse ((((continuous_linear_equiv.units_equiv _ _).symm e) : M →L[R] M)) = inverse ↑e, { convert this }, simp, refl, end /-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the ring of self-maps of the domain. -/ lemma to_ring_inverse (e : M ≃L[R] M₂) (f : M →L[R] M₂) : inverse f = (ring.inverse ((e.symm : (M₂ →L[R] M)).comp f)) ∘L ↑e.symm := begin by_cases h₁ : ∃ (e' : M ≃L[R] M₂), ↑e' = f, { obtain ⟨e', he'⟩ := h₁, rw ← he', change _ = (ring.inverse ↑(e'.trans e.symm)) ∘L ↑e.symm, ext, simp }, { suffices : ¬is_unit ((e.symm : M₂ →L[R] M).comp f), { simp [this, h₁] }, contrapose! h₁, rcases h₁ with ⟨F, hF⟩, use (continuous_linear_equiv.units_equiv _ _ F).trans e, ext, dsimp, rw [coe_fn_coe_base' F, hF], simp } end lemma ring_inverse_eq_map_inverse : ring.inverse = @inverse R M M _ _ _ _ _ _ _ := begin ext, simp [to_ring_inverse (continuous_linear_equiv.refl R M)], end end end continuous_linear_map namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨ker f, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - p.subtypeL.comp f) = p := linear_map.ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : (ker f₁).closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩ section quotient namespace submodule variables {R M : Type*} [ring R] [add_comm_group M] [module R M] [topological_space M] (S : submodule R M) lemma is_open_map_mkq [topological_add_group M] : is_open_map S.mkq := quotient_add_group.is_open_map_coe S.to_add_subgroup instance topological_add_group_quotient [topological_add_group M] : topological_add_group (M ⧸ S) := topological_add_group_quotient S.to_add_subgroup instance has_continuous_smul_quotient [topological_space R] [topological_add_group M] [has_continuous_smul R M] : has_continuous_smul R (M ⧸ S) := begin split, have quot : quotient_map (λ au : R × M, (au.1, S.mkq au.2)), from is_open_map.to_quotient_map (is_open_map.id.prod S.is_open_map_mkq) (continuous_id.prod_map continuous_quot_mk) (function.surjective_id.prod_map $ surjective_quot_mk _), rw quot.continuous_iff, exact continuous_quot_mk.comp continuous_smul end instance t3_quotient_of_is_closed [topological_add_group M] [is_closed (S : set M)] : t3_space (M ⧸ S) := begin letI : is_closed (S.to_add_subgroup : set M) := ‹_›, exact S.to_add_subgroup.t3_quotient_of_is_closed end end submodule end quotient
fcbbc8d849fa6c6af7d2e5b2c44462ab399a3ff9
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1338.lean
45ca3d4cfd0f8f9a0cc07dac612b553932d595e0
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
432
lean
import data.real.basic def fn_ub (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, f x ≤ a def fn_has_ub (f : ℝ → ℝ) := ∃ a, fn_ub f a open_locale classical variable (f : ℝ → ℝ) -- BEGIN example (h : ¬ ∀ a, ∃ x, f x > a) : fn_has_ub f := begin push_neg at h, exact h end example (h : ¬ fn_has_ub f) : ∀ a, ∃ x, f x > a := begin simp only [fn_has_ub, fn_ub] at h, push_neg at h, exact h end -- END
d50b15c35d99ccdba2de75afb3582abdcf9edcd9
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/tc_loop.lean
acccff54f62f4fc088b4baa0aee5aff48775cac2
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
304
lean
open tactic check (do { trace "foo", trace_state } : tactic unit) axiom Sorry {A : Sort*} : A check λ (A : Sort*) (a b c d : A) (H₁ : a = b) (H₂ : c = b) (H₃ : d = c), have a = c, by do { trace "have-expr...", trace_state, transitivity, assumption, symmetry, assumption }, show a = d, from Sorry
6fe33c6f5d716126f193f90320c6418e09886412
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/types/pi.lean
eef481e04f00cd2acc57470c73f31b8a5052cb13
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
15,038
lean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import .sigma hott.arity hott.cubical.square universe u hott_theory namespace hott open hott.eq hott.equiv hott.is_equiv hott.funext hott.sigma hott.is_trunc unit namespace pi variables {A : Type _} {A' : Type _} {B : A → Type _} {B' : A' → Type _} {C : Πa, B a → Type _} {D : Πa b, C a b → Type _} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g]. This equivalence, however, is just the combination of [apd10] and function extensionality [funext], and as such, [eq_of_homotopy] Now we show how these things compute. -/ @[hott] def apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) @[hott] def eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p @[hott] def eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f := eq_of_homotopy_eta (refl f) /- homotopy.symm is an equivalence -/ @[hott] def is_equiv_homotopy_symm : is_equiv (homotopy.symm : f ~ g → g ~ f) := begin apply adjointify homotopy.symm homotopy.symm, { intro p, apply eq_of_homotopy, intro a, apply eq.inv_inv }, { intro p, apply eq_of_homotopy, intro a, apply eq.inv_inv } end /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ @[hott] def pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := eq_equiv_homotopy f g @[hott,instance] def is_equiv_eq_of_homotopy (f g : Πx, B x) : is_equiv (eq_of_homotopy : f ~ g → f = g) := is_equiv_inv _ @[hott] def homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk eq_of_homotopy (by apply_instance) /- Transport -/ @[hott] def pi_transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, tr_inv_tr p b ▸ (p ▸D f (p⁻¹ ▸ b))) := by induction p; reflexivity /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ @[hott] def pi_transport_constant {C : A → A' → Type _} (p : a = a') (f : Π(b : A'), C a b) (b : A') : (transport _ p f) b = @transport A (λa, C a b) _ _ p (f b) := --fix by induction p; reflexivity /- Pathovers -/ @[hott] def pi_pathover' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apd011 C p q; λX, X] g b') : f =[p; λa, Πb, C a b] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, let z := eq_of_pathover_idp (r b b idpo), exact z --fix end @[hott] def pi_pathover_left' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a), f b =[apd011 C p (pathover_tr _ _); λX, X] g (p ▸ b)) : f =[p; λa, Πb, C a b] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, let z := eq_of_pathover_idp (r b), exact z --fix end @[hott] def pi_pathover_right' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apd011 C p (tr_pathover _ _); λX, X] g b') : f =[p; λa, Πb, C a b] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, dsimp [apd011, tr_pathover] at r, let z := eq_of_pathover_idp (r b), exact z --fix end @[hott] def pi_pathover_constant {C : A → A' → Type _} {f : Π(b : A'), C a b} {g : Π(b : A'), C a' b} {p : a = a'} (r : Π(b : A'), f b =[p; λa, C a b] g b) : f =[p; λa, Πb, C a b] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, let z := eq_of_pathover_idp (r b), exact z --fix end -- a version where C is uncurried, but where the conclusion of r is still a proper pathover -- instead of a heterogenous equality @[hott] def pi_pathover {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b') : f =[p; λa, Πb, C ⟨a, b⟩] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)), end @[hott] def pi_pathover_left {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p (pathover_tr _ _)] g (p ▸ b)) : f =[p; λa, Πb, C ⟨a, b⟩] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, apply eq_of_pathover_idp, exact pathover_ap _ _ (r b) end @[hott] def pi_pathover_right {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p (tr_pathover _ _)] g b') : f =[p; λa, Πb, C ⟨a, b⟩] g := begin induction p, apply pathover_idp_of_eq, apply eq_of_homotopy, hintro b, apply eq_of_pathover_idp, exact pathover_ap _ _ (r b) end /- Maps on paths -/ /- The action of maps given by lambda. -/ @[hott] def ap_lambdaD {C : A' → Type _} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply eq_of_homotopy_idp end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃ (transport (λa, Π(b : B a), C a b) p f = g) -/ @[hott] def heq_piD (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, homotopy_equiv_eq _ _) g @[hott] def heq_pi {C : A → Type _} (p : a = a') (f : Π(b : B a), C a) (g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, homotopy_equiv_eq _ _) g section /- more implicit arguments: (Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/ @[hott] def heq_pi_sigma {C : (Σa, B a) → Type _} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (dpair_eq_dpair p (pathover_tr p b)) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD (λa b, C ⟨a, b⟩) p _ (f b) = g (p ▸ b)) := by induction p; refl end /- Functorial action -/ variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') /- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/ @[hott] def pi_functor : (Π(a:A), B a) → (Π(a':A'), B' a') := λg a', f1 a' (g (f0 a')) @[hott] def pi_functor_left (B : A → Type _) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) := pi_functor f0 (λa, id) @[hott] def pi_functor_right {B' : A → Type _} (f1 : Π(a:A), B a → B' a) : (Π(a:A), B a) → (Π(a:A), B' a) := pi_functor id f1 @[hott] def pi_iff_pi {B' : A → Type _} (f : Πa, B a ↔ B' a) : (Π(a:A), B a) ↔ (Π(a:A), B' a) := ⟨pi_functor id (λa, (f a).1), pi_functor id (λa, (f a).2)⟩ @[hott,hsimp] def pi_functor_eq (g : Πa, B a) (a' : A') : pi_functor f0 f1 g a' = f1 a' (g (f0 a')) := by refl @[hott] def ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g') : ap (pi_functor f0 f1) (eq_of_homotopy h) = eq_of_homotopy (λ(a' : A'), (ap (f1 a') (h (f0 a')))) := begin apply is_equiv_rect (@apd10 A B g g') (λh, ap (pi_functor f0 f1) (eq_of_homotopy h) = eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a'))))), intro p, clear h, induction p, refine (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)) ⬝ _, symmetry, apply eq_of_homotopy_idp end /- Equivalences -/ /-@[hott] def pi_equiv_pi (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a')) : (Πa, B a) ≃ (Πa', B' a') := begin fapply equiv.MK, exact pi_functor f0 f1, (pi_functor f0⁻¹ᶠ (λ(a : A) (b' : B' (f0⁻¹ᶠ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ᶠ a))⁻¹ᶠ b'))) end-/ @[hott, instance] def is_equiv_pi_functor [H0 : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) := adjointify (pi_functor f0 f1) (pi_functor f0⁻¹ᶠ (λ(a : A) (b' : B' (f0⁻¹ᶠ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ᶠ a))⁻¹ᶠ b'))) begin intro h, apply eq_of_homotopy, intro a', dsimp, rwr [adj f0 a', hott.eq.inverse (tr_compose B f0 (left_inv f0 a') _), fn_tr_eq_tr_fn _ f1 _, right_inv (f1 _)], --fix apply apdt end begin intro h, apply eq_of_homotopy, intro a, dsimp, rwr [left_inv (f1 _)], apply apdt end @[hott] def pi_equiv_pi_of_is_equiv [H : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') := equiv.mk (pi_functor f0 f1) (by apply_instance) @[hott] def pi_equiv_pi (f0 : A' ≃ A) (f1 : Πa', (B (f0 a') ≃ B' a')) : (Πa, B a) ≃ (Πa', B' a') := pi_equiv_pi_of_is_equiv f0 (λa', f1 a') @[hott] def pi_equiv_pi_right {P Q : A → Type _} (g : Πa, P a ≃ Q a) : (Πa, P a) ≃ (Πa, Q a) := pi_equiv_pi equiv.rfl g /- Equivalence if one of the types is contractible -/ variable (B) @[hott] def pi_equiv_of_is_contr_left [H : is_contr A] : (Πa, B a) ≃ B (center A) := begin fapply equiv.MK, { intro f, exact f (center A)}, { intros b a, exact center_eq a ▸ b}, { intro b, dsimp, rwr [prop_eq_of_is_contr (center_eq (center A)) idp]}, { intro f, apply eq_of_homotopy, intro a, dsimp, induction (center_eq a), refl } end @[hott] def pi_equiv_of_is_contr_right [H : Πa, is_contr (B a)] : (Πa, B a) ≃ unit := begin fapply equiv.MK, { intro f, exact star }, { intros u a, exact center _ }, { intro u, induction u, reflexivity }, { intro f, apply eq_of_homotopy, intro a, apply is_prop.elim } end variable {B} /- Interaction with other type constructors -/ -- most of these are in the file of the other type constructor @[hott] def pi_empty_left (B : empty → Type _) : (Πx, B x) ≃ unit := begin fapply equiv.MK, { intro f, exact star }, { intros x y, exact empty.elim y }, { intro x, induction x, reflexivity }, { intro f, apply eq_of_homotopy, intro y, exact empty.elim y } end @[hott] def pi_unit_left (B : unit → Type _) : (Πx, B x) ≃ B star := pi_equiv_of_is_contr_left _ @[hott] def pi_bool_left (B : bool → Type _) : (Πx, B x) ≃ B ff × B tt := begin fapply equiv.MK, { intro f, exact (f ff, f tt) }, { intros x b, induction x, induction b, all_goals {assumption}}, { intro x, induction x, reflexivity }, { intro f, apply eq_of_homotopy, intro b, induction b, all_goals {reflexivity}}, end /- Truncatedness: any dependent product of n-types is an n-type -/ @[hott, instance, priority 1520] theorem is_trunc_pi (B : A → Type _) (n : trunc_index) [H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) := begin unfreezeI, induction n with n IH generalizing B H; resetI, { fapply is_contr.mk, intro a, apply center, intro f, apply eq_of_homotopy, intro x, apply (center_eq (f x)) }, { apply is_trunc_succ_intro, intros f g, exact is_trunc_equiv_closed_rev n (eq_equiv_homotopy f g) (by apply_instance) } end @[hott] theorem is_trunc_pi_eq (n : trunc_index) (f g : Πa, B a) [H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) := is_trunc_equiv_closed_rev n (eq_equiv_homotopy f g) (by apply_instance) @[hott, instance] theorem is_trunc_not (n : trunc_index) (A : Type _) : is_trunc (n.+1) ¬A := by dsimp [not]; apply_instance @[hott] theorem is_prop_pi_eq (a : A) : is_prop (Π(a' : A), a = a') := is_prop_of_imp_is_contr ( assume (f : Πa', a = a'), have is_contr A, from is_contr.mk a f, by unfreezeI; apply_instance) @[hott] theorem is_prop_neg (A : Type _) : is_prop (¬A) := by apply_instance @[hott] theorem is_prop_ne {A : Type _} (a b : A) : is_prop (a ≠ b) := by apply_instance @[hott] def is_contr_pi_of_neg {A : Type _} (B : A → Type _) (H : ¬ A) : is_contr (Πa, B a) := begin apply is_contr.mk (λa, empty.elim (H a)), intro f, apply eq_of_homotopy, intro x, exact empty.elim (H x) end /- Symmetry of Π -/ @[hott] def pi_flip {P : A → A' → Type _} (f : Πa b, P a b) (b : A') (a : A) : P a b := f a b @[hott, instance] def is_equiv_flip {P : A → A' → Type _} : is_equiv (@pi_flip A A' P) := begin fapply is_equiv.mk, exact (@pi_flip _ _ (pi_flip P)), all_goals {intro f; refl} end @[hott] def pi_comm_equiv {P : A → A' → Type _} : (Πa b, P a b) ≃ (Πb a, P a b) := equiv.mk (@pi_flip _ _ P) (by apply_instance) /- Dependent functions are equivalent to nondependent functions into the total space together with a homotopy -/ @[hott] def pi_equiv_arrow_sigma_right {A : Type _} {B : A → Type _} (f : Πa, B a) : Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id := ⟨λa, ⟨a, f a⟩, λa, idp⟩ @[hott] def pi_equiv_arrow_sigma_left (v : Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id) (a : A) : B a := transport B (v.2 a) (v.1 a).2 open funext @[hott] def pi_equiv_arrow_sigma : (Πa, B a) ≃ Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id := begin fapply equiv.MK, { exact pi_equiv_arrow_sigma_right }, { exact pi_equiv_arrow_sigma_left }, { intro v, induction v with f p, fapply sigma_eq, { apply eq_of_homotopy, intro a, fapply sigma_eq, { exact (p a)⁻¹ }, { apply inverseo, apply pathover_tr }}, { apply pi_pathover_constant, intro a, apply eq_pathover_constant_right, refine ap_compose (λf : A → A, f a) _ _ ⬝ph _, refine ap02 _ (compose_eq_of_homotopy (@sigma.fst A B) _) ⬝ph _, refine ap_eq_apd10 _ _ ⬝ph _, refine apd10 (right_inv apd10 _) a ⬝ph _, refine sigma_eq_fst _ _ ⬝ph _, apply square_of_eq, exact (con.left_inv _)⁻¹ }}, { intro a, reflexivity } end end pi namespace pi /- pointed pi types -/ open pointed @[hott, instance] def pointed_pi {A : Type _} (P : A → Type _) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) end pi end hott
c31192656a59801e28e066e03f89da0bcb3c6087
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/category.lean
bb4b35be50a09a751434635a3b98f8cb09e6190b
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
6,251
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, Johannes Hölzl, Reid Barton Defines a category, as a typeclass parametrised by the type of objects. Introduces notations `X ⟶ Y` for the morphism spaces, `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ``` local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ import tactic.basic import tactic.tidy universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory /- The propositional fields of `category` are annotated with the auto_param `obviously`, which is defined here as a [`replacer` tactic](https://github.com/leanprover/mathlib/blob/master/docs/tactics.md#def_replacer). We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more powerful tactics. -/ def_replacer obviously @[obviously] meta def obviously' := tactic.tidy class has_hom (obj : Type u) : Type (max u v) := (hom : obj → obj → Sort v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u v) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u v) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp lemma category.assoc_symm {C : Type u} [category.{v} C] {W X Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) : f ≫ (g ≫ h) = (f ≫ g) ≫ h := by rw ←category.assoc /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type u) : Type u := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u+1} C section variables {C : Type u} [𝒞 : category.{v} C] {X Y Z : C} include 𝒞 lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) @[simp] lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ @[simp] lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end section variables {C : Type u} def End [has_hom.{v} C] (X : C) := X ⟶ X instance End.has_one [category_struct.{v+1} C] {X : C} : has_one (End X) := by refine { one := 𝟙 X } instance End.has_mul [category_struct.{v+1} C] {X : C} : has_mul (End X) := by refine { mul := λ x y, x ≫ y } instance End.monoid [category.{v+1} C] {X : C} : monoid (End X) := by refine { .. End.has_one, .. End.has_mul, .. }; dsimp [has_mul.mul,has_one.one]; obviously @[simp] lemma End.one_def {C : Type u} [category_struct.{v+1} C] {X : C} : (1 : End X) = 𝟙 X := rfl @[simp] lemma End.mul_def {C : Type u} [category_struct.{v+1} C] {X : C} (xs ys : End X) : xs * ys = xs ≫ ys := rfl end end category_theory open category_theory namespace preorder variables (α : Type u) instance small_category [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ } end preorder
de922724a5a5b5700faf94facdbdd134f1198a04
d1bbf1801b3dcb214451d48214589f511061da63
/src/field_theory/separable.lean
a5198d1686198f6dfcd5834df5cefd3f13df74f2
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,931
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau. -/ import algebra.polynomial.big_operators import field_theory.minpoly import field_theory.splitting_field import field_theory.tower import algebra.squarefree /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, or.inl $ is_coprime_self.1 h.is_coprime.of_mul_right_left theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, finsupp.sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], refl, { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw finsupp.not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_eq_map_domain (p : ℕ) (f : polynomial R) : expand R p f = f.map_domain (*p) := polynomial.induction_on' f (λ p q hp hq, by simp [*, finsupp.map_domain_add]) $ λ n a, by simp_rw [expand_monomial, monomial_def, finsupp.map_domain_single] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← pow_two] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.1 $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.2 _ _ hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p variables (p : ℕ) [hp : fact p.prime] include hp /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (f : polynomial F) : polynomial F := ⟨f.support.preimage (*p) $ λ _ _ _ _, (nat.mul_left_inj hp.pos).1, λ n, f.coeff (n * p), λ n, by { rw [finset.mem_preimage, finsupp.mem_support_iff], refl }⟩ theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := rfl theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by rwa [expand_expand] variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, single_eq_C_mul_X, single_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : ℕ) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, {simp [ring_hom.one_def]}, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff] section splits open_locale big_operators variables {i : F →+* K} lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) := λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_separable {p q : polynomial F} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← pow_two, apply multiplicity.pow_dvd_of_le_multiplicity, exact_mod_cast (enat.add_one_le_of_lt hq) end lemma separable.squarefree {p : polynomial F} (hsep : separable p) : squarefree p := begin rw multiplicity.squarefree_iff_multiplicity_le_one p, intro f, by_cases hunit : is_unit f, { exact or.inr hunit }, exact or.inl (multiplicity_le_one_of_separable hunit hsep) end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/ lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : separable (X ^ n - C a) := begin cases nat.eq_zero_or_pos n with hzero hpos, { exfalso, rw hzero at hn, exact hn (refl 0) }, apply (separable_def' (X ^ n - C a)).2, use [-C (a⁻¹), (C ((a⁻¹) * (↑n)⁻¹) * X)], have mul_pow_sub : X * X ^ (n - 1) = X ^ n, { nth_rewrite 0 [←pow_one X], rw pow_mul_pow_sub X (nat.succ_le_iff.mpr hpos) }, rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one], have hcalc : C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * (X ^ n), { calc C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * C ((↑n)⁻¹) * (C ↑n * (X ^ n)) : by rw [C_mul, C_eq_nat_cast] ... = C a⁻¹ * (C ((↑n)⁻¹) * C ↑n) * (X ^ n) : by ring ... = C a⁻¹ * C ((↑n)⁻¹ * ↑n) * (X ^ n) : by rw [← C_mul] ... = C a⁻¹ * C 1 * (X ^ n) : by field_simp [hn] ... = C a⁻¹ * (X ^ n) : by rw [C_1, mul_one] }, calc -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * X * (↑n * X ^ (n - 1)) = -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * (↑n * (X * X ^ (n - 1))) : by ring ... = -C a⁻¹ * (X ^ n - C a) + C a⁻¹ * (X ^ n) : by rw [mul_pow_sub, hcalc] ... = C a⁻¹ * C a : by ring ... = (1 : polynomial F) : by rw [← C_mul, inv_mul_cancel ha, C_1] end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/ lemma squarefree_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : squarefree (X ^ n - C a) := (separable_X_pow_sub_C a hn ha).squarefree lemma root_multiplicity_le_one_of_separable {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get], exact multiplicity_le_one_of_separable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≤ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_separable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.1 _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero end /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. -/ @[class] def is_separable (F K : Sort*) [field F] [field K] [algebra F K] : Prop := ∀ x : K, ∃ H : is_integral F x, (minpoly H).separable instance is_separable_self (F : Type*) [field F] : is_separable F F := λ x, ⟨is_integral_algebra_map, by { rw minpoly.eq_X_sub_C, exact separable_X_sub_C }⟩ section is_separable_tower variables {F E : Type*} (K : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable (h : is_separable F E) : is_separable K E := λ x, Exists.cases_on (h x) (λ hx hs, ⟨is_integral_of_is_scalar_tower x hx, hs.map.of_dvd (minpoly.dvd_map_of_is_scalar_tower K hx)⟩) lemma is_separable_tower_bot_of_is_separable (h : is_separable F E) : is_separable F K := begin intro x, obtain ⟨hx, hs⟩ := h (algebra_map K E x), have hx' : is_integral F x := is_integral_tower_bot_of_is_integral_field hx, obtain ⟨q, hq⟩ := minpoly.dvd hx' (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minpoly.aeval hx)), use hx', apply polynomial.separable.of_mul_left, rw ← hq, exact hs, end lemma is_separable.of_alg_hom {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') (h : is_separable F E') : is_separable F E := begin letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom, haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm), exact is_separable_tower_bot_of_is_separable E h, end end is_separable_tower
a7090b1c9859e8a02e0f76e85937ced36e4c371d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/monad/cont.lean
25bdcbad971fa33b64f9a5a60f53a346c968169b
[]
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
11,526
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Monad encapsulating continuation passing programming style, similar to Haskell's `Cont`, `ContT` and `MonadCont`: <http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html> -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.monad.writer import Mathlib.PostPort universes u v w l u_1 u_2 u₀ u₁ v₀ v₁ namespace Mathlib structure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) where apply : α → m β def monad_cont.goto {α : Type u_1} {β : Type u} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) : m β := monad_cont.label.apply f x class monad_cont (m : Type u → Type v) where call_cc : {α β : Type u} → (monad_cont.label α m β → m α) → m α class is_lawful_monad_cont (m : Type u → Type v) [Monad m] [monad_cont m] extends is_lawful_monad m where call_cc_bind_right : ∀ {α ω γ : Type u} (cmd : m α) (next : monad_cont.label ω m γ → α → m ω), (monad_cont.call_cc fun (f : monad_cont.label ω m γ) => cmd >>= next f) = do let x ← cmd monad_cont.call_cc fun (f : monad_cont.label ω m γ) => next f x call_cc_bind_left : ∀ {α : Type u} (β : Type u) (x : α) (dead : monad_cont.label α m β → β → m α), (monad_cont.call_cc fun (f : monad_cont.label α m β) => monad_cont.goto f x >>= dead f) = pure x call_cc_dummy : ∀ {α β : Type u} (dummy : m α), (monad_cont.call_cc fun (f : monad_cont.label α m β) => dummy) = dummy def cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r def cont (r : Type u) (α : Type w) := cont_t r id α namespace cont_t def run {r : Type u} {m : Type u → Type v} {α : Type w} : cont_t r m α → (α → m r) → m r := id def map {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x theorem run_cont_t_map_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r) (x : cont_t r m α) : run (map f x) = f ∘ run x := rfl def with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w} (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β := fun (g : β → m r) => x (f g) theorem run_with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w} (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f := rfl protected theorem ext {r : Type u} {m : Type u → Type v} {α : Type w} {x : cont_t r m α} {y : cont_t r m α} (h : ∀ (f : α → m r), run x f = run y f) : x = y := funext fun (x_1 : α → m r) => h x_1 protected instance monad {r : Type u} {m : Type u → Type v} : Monad (cont_t r m) := sorry protected instance is_lawful_monad {r : Type u} {m : Type u → Type v} : is_lawful_monad (cont_t r m) := is_lawful_monad.mk (fun (α β : Type u_1) (x : α) (f : α → cont_t r m β) => cont_t.ext fun (f_1 : β → m r) => Eq.refl (run (pure x >>= f) f_1)) fun (α β γ : Type u_1) (x : cont_t r m α) (f : α → cont_t r m β) (g : β → cont_t r m γ) => cont_t.ext fun (f_1 : γ → m r) => Eq.refl (run (x >>= f >>= g) f_1) def monad_lift {r : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : m α → cont_t r m α := fun (x : m α) (f : α → m r) => x >>= f protected instance has_monad_lift {r : Type u} {m : Type u → Type v} [Monad m] : has_monad_lift m (cont_t r m) := has_monad_lift.mk fun (α : Type u) => monad_lift theorem monad_lift_bind {r : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Type u} {β : Type u} (x : m α) (f : α → m β) : monad_lift (x >>= f) = monad_lift x >>= monad_lift ∘ f := sorry protected instance monad_cont {r : Type u} {m : Type u → Type v} : monad_cont (cont_t r m) := monad_cont.mk fun (α β : Type u_1) (f : label α (cont_t r m) β → cont_t r m α) (g : α → m r) => f (monad_cont.label.mk fun (x : α) (h : β → m r) => g x) g protected instance is_lawful_monad_cont {r : Type u} {m : Type u → Type v} : is_lawful_monad_cont (cont_t r m) := is_lawful_monad_cont.mk sorry sorry sorry protected instance monad_except {r : Type u} {m : Type u → Type v} (ε : outParam (Type u_1)) [monad_except ε m] : monad_except ε (cont_t r m) := monad_except.mk (fun (x : Type u_2) (e : ε) (f : x → m r) => throw e) fun (α : Type u_2) (act : cont_t r m α) (h : ε → cont_t r m α) (f : α → m r) => catch (act f) fun (e : ε) => h e f protected instance monad_run {r : Type u} {m : Type u → Type v} : monad_run (fun (α : Type u) => (α → m r) → ulift (m r)) (cont_t r m) := monad_run.mk fun (α : Type u) (f : cont_t r m α) (x : α → m r) => ulift.up (f x) end cont_t def except_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {ε : Type u} : label (except ε α) m β → label α (except_t ε m) β := sorry theorem except_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {ε : Type u} (x : label (except ε α) m β) (i : α) : goto (except_t.mk_label x) i = except_t.mk (except.ok <$> goto x (except.ok i)) := monad_cont.label.cases_on x fun (x : except ε α → m β) => Eq.refl (goto (except_t.mk_label (monad_cont.label.mk x)) i) def except_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α := except_t.mk (monad_cont.call_cc fun (x : label (except ε α) m β) => except_t.run (f (except_t.mk_label x))) protected instance except_t.monad_cont {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] : monad_cont (except_t ε m) := monad_cont.mk fun (α β : Type u) => except_t.call_cc protected instance except_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) := is_lawful_monad_cont.mk sorry sorry sorry def option_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} : label (Option α) m β → label α (option_t m) β := sorry theorem option_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (x : label (Option α) m β) (i : α) : goto (option_t.mk_label x) i = option_t.mk (some <$> goto x (some i)) := monad_cont.label.cases_on x fun (x : Option α → m β) => Eq.refl (goto (option_t.mk_label (monad_cont.label.mk x)) i) def option_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u} (f : label α (option_t m) β → option_t m α) : option_t m α := option_t.mk (monad_cont.call_cc fun (x : label (Option α) m β) => option_t.run (f (option_t.mk_label x))) protected instance option_t.monad_cont {m : Type u → Type v} [Monad m] [monad_cont m] : monad_cont (option_t m) := monad_cont.mk fun (α β : Type u) => option_t.call_cc protected instance option_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) := is_lawful_monad_cont.mk sorry sorry sorry def writer_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} {ω : Type u} [HasOne ω] : label (α × ω) m β → label α (writer_t ω m) β := sorry theorem writer_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} {ω : Type u} [HasOne ω] (x : label (α × ω) m β) (i : α) : goto (writer_t.mk_label x) i = monad_lift (goto x (i, 1)) := monad_cont.label.cases_on x fun (x : α × ω → m β) => Eq.refl (goto (writer_t.mk_label (monad_cont.label.mk x)) i) def writer_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u} {ω : Type u} [HasOne ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α := writer_t.mk (monad_cont.call_cc (writer_t.run ∘ f ∘ writer_t.mk_label)) protected instance writer_t.monad_cont {m : Type u → Type v} [Monad m] (ω : Type u) [Monad m] [HasOne ω] [monad_cont m] : monad_cont (writer_t ω m) := monad_cont.mk fun (α β : Type u) => writer_t.call_cc def state_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β := sorry theorem state_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) : goto (state_t.mk_label x) i = state_t.mk fun (s : σ) => goto x (i, s) := monad_cont.label.cases_on x fun (x : α × σ → m (β × σ)) => Eq.refl (goto (state_t.mk_label (monad_cont.label.mk x)) i) def state_t.call_cc {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α := state_t.mk fun (r : σ) => monad_cont.call_cc fun (f' : label (α × σ) m (β × σ)) => state_t.run (f (state_t.mk_label f')) r protected instance state_t.monad_cont {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] : monad_cont (state_t σ m) := monad_cont.mk fun (α β : Type u) => state_t.call_cc protected instance state_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) := is_lawful_monad_cont.mk sorry sorry sorry def reader_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} (ρ : Type u) : label α m β → label α (reader_t ρ m) β := sorry theorem reader_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {ρ : Type u} {β : Type u} (x : label α m β) (i : α) : goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := monad_cont.label.cases_on x fun (x : α → m β) => Eq.refl (goto (reader_t.mk_label ρ (monad_cont.label.mk x)) i) def reader_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α := reader_t.mk fun (r : ε) => monad_cont.call_cc fun (f' : label α m β) => reader_t.run (f (reader_t.mk_label ε f')) r protected instance reader_t.monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u} [monad_cont m] : monad_cont (reader_t ρ m) := monad_cont.mk fun (α β : Type u) => reader_t.call_cc protected instance reader_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) := is_lawful_monad_cont.mk sorry sorry sorry /-- reduce the equivalence between two continuation passing monads to the equivalence between their underlying monad -/ def cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {r₁ : Type u₀} {α₂ : Type u₁} {r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ := equiv.mk (fun (f : cont_t r₁ m₁ α₁) (r : α₂ → m₂ r₂) => coe_fn F (f fun (x : α₁) => coe_fn (equiv.symm F) (r (coe_fn G x)))) (fun (f : cont_t r₂ m₂ α₂) (r : α₁ → m₁ r₁) => coe_fn (equiv.symm F) (f fun (x : α₂) => coe_fn F (r (coe_fn (equiv.symm G) x)))) sorry sorry
ea48e21e3aee987e03a346511ee5a9af1ae479fe
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/analysis/calculus/times_cont_diff.lean
3813f74edb187f73aed3e9d235b9449417c0d65e
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
121,936
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff_within_at`, `times_cont_diff_at`, `times_cont_diff_on` and `times_cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set and on the whole space respectively. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `times_cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `formal_multilinear_series 𝕜 E F`: a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `times_cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`. * `times_cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more complicated than the naive definitions one would guess from the intuition over the real or complex numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity in general. In the usual situations, they coincide with the usual definitions. ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. (Note that this issue can not happen over reals, thanks to partition of unity, but the behavior over a general field is not so clear, and we want a definition for general fields). Also, there are locality problems for the order parameter: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and order in our definition of `times_cont_diff_within_at` and `times_cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)` for each natural `m` is by definition `C^∞` at `0`. There is another issue with the definition of `times_cont_diff_within_at 𝕜 n f s x`. We can require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x` within `s`. However, this does not imply continuity or differentiability within `s` of the function at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file). ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. In this file, we denote `⊤ : with_top ℕ` with `∞`. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical big_operators local notation `∞` := (⊤ : with_top ℕ) universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_semimodule add_comm_group.to_add_comm_monoid open set fin open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group] def formal_multilinear_series (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (F : Type*) [normed_group F] [normed_space 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ local attribute [reducible] formal_multilinear_series instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : ∀ n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, apply_instance end end module namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F) (q n) /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi } end formal_multilinear_series /-! ### Functions with a Taylor series on a domain -/ variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa continuous_linear_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, have : (m : with_top ℕ) = ((0 : ℕ) : with_bot ℕ) := le_antisymm hm bot_le, rw with_top.coe_eq_coe at this, rw this, have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, continuous_linear_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m (le_refl _) } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr' with i, have : i = 0 := subsingleton.elim i 0, rw this, refl end lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) (le_refl _)⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s, rw continuous_linear_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa continuous_linear_equiv.comp_continuous_on_iff at this } } } end /-! ### Smooth functions within a set around a point -/ variable (𝕜) /-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not better, is `C^∞` at `0` within `univ`. -/ def times_cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma times_cont_diff_within_at_nat {n : ℕ} : times_cont_diff_within_at 𝕜 n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := ⟨λ H, H n (le_refl _), λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩ lemma times_cont_diff_within_at_top : times_cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H n m hm, rcases H m le_top with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ }, { assume H m hm, rcases H m m (le_refl _) with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ } end lemma times_cont_diff_within_at.continuous_within_at' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) : continuous_within_at f (insert x s) x := begin rcases h 0 bot_le with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, have A : x ∈ t ∩ insert x s, by simp [xt], have := (H.mono tu).continuous_on.continuous_within_at A, rw inter_comm at this, exact (continuous_within_at_inter (mem_nhds_sets t_open xt)).1 this end lemma times_cont_diff_within_at.continuous_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x := (h.continuous_within_at').mono (subset_insert x s) lemma times_cont_diff_within_at.congr_of_eventually_eq {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, rcases h₁.exists_mem with ⟨v, v_neighb, hv⟩, refine ⟨u ∩ ((insert x v) ∩ (insert x s)), _, p, _⟩, { exact filter.inter_mem_sets hu (filter.inter_mem_sets (mem_nhds_within_insert v_neighb) self_mem_nhds_within) }, { apply (H.mono (inter_subset_left u _)).congr (λ y hy, _), simp at hy, rcases hy.2.1 with rfl|hy', { exact hx }, { exact hv hy' } } end lemma times_cont_diff_within_at.congr_of_eventually_eq' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f₁ s x := begin apply h.congr_of_eventually_eq h₁, rcases h₁.exists_mem with ⟨t, ht, t_eq⟩, exact t_eq (mem_of_mem_nhds_within hx ht) end lemma filter.eventually_eq.times_cont_diff_within_at_iff {n : with_top ℕ} (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x ↔ times_cont_diff_within_at 𝕜 n f s x := ⟨λ H, times_cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm, λ H, H.congr_of_eventually_eq h₁ hx⟩ lemma times_cont_diff_within_at.congr {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : times_cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx lemma times_cont_diff_within_at.mono {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) : times_cont_diff_within_at 𝕜 n f t x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_mono _ (insert_subset_insert hst) hu, p, H⟩, end lemma times_cont_diff_within_at.of_le {m n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) : times_cont_diff_within_at 𝕜 m f s x := λ k hk, h k (le_trans hk hmn) lemma times_cont_diff_within_at_inter' {n : with_top ℕ} (h : t ∈ 𝓝[s] x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := begin refine ⟨λ H m hm, _, λ H, H.mono (inter_subset_left _ _)⟩, rcases H m hm with ⟨u, u_nhbd, p, hu⟩, refine ⟨(insert x s ∩ insert x t) ∩ u, _, p, hu.mono (inter_subset_right _ _)⟩, rw nhds_within_restrict'' (insert x s) (mem_nhds_within_insert h), rw insert_inter at u_nhbd, exact filter.inter_mem_sets self_mem_nhds_within u_nhbd end lemma times_cont_diff_within_at_inter {n : with_top ℕ} (h : t ∈ 𝓝 x) : times_cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ times_cont_diff_within_at 𝕜 n f s x := times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h) /-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable within this set at this point. -/ lemma times_cont_diff_within_at.differentiable_within_at' {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f (insert x s) x := begin rcases h 1 hn with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, have := ((H.mono tu).differentiable_on (le_refl _)) x ⟨mem_insert x s, xt⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 this, end lemma times_cont_diff_within_at.differentiable_within_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f s x := (h.differentiable_within_at' hn).mono (subset_insert x s) /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_within_at 𝕜 n f' u x) := begin split, { assume h, rcases h n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, assume m hm, refine ⟨u, _, λ (y : E), (p y).shift, _⟩, { convert self_mem_nhds_within, have : x ∈ insert x s, by simp, exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) }, { rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, exact Hp.2.2.of_le hm } }, { rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩, rw times_cont_diff_within_at_nat, rcases Hf' n (le_refl _) with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩, { apply filter.inter_mem_sets _ hu, apply nhds_within_le_of_mem hu, exact nhds_within_mono _ (subset_insert x u) hv }, { rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ (z : E), (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } } end /-! ### Smooth functions within a set -/ variable (𝕜) /-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). -/ definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ x ∈ s, times_cont_diff_within_at 𝕜 n f s x variable {𝕜} lemma times_cont_diff_on.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hx : x ∈ s) : times_cont_diff_within_at 𝕜 n f s x := h x hx lemma times_cont_diff_within_at.times_cont_diff_on {n : with_top ℕ} {m : ℕ} (hm : (m : with_top ℕ) ≤ n) (h : times_cont_diff_within_at 𝕜 n f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ times_cont_diff_on 𝕜 m f u := begin rcases h m hm with ⟨u, u_nhd, p, hp⟩, refine ⟨u ∩ insert x s, filter.inter_mem_sets u_nhd self_mem_nhds_within, inter_subset_right _ _, _⟩, assume y hy m' hm', refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hy end lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s := by { simp [times_cont_diff_on, times_cont_diff_within_at_top], tauto } lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := λ x hx, (h x hx).continuous_within_at lemma times_cont_diff_on.congr {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := λ x hx, (h x hx).congr h₁ (h₁ x hx) lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma times_cont_diff_on.mono {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : times_cont_diff_on 𝕜 n f t := λ x hx, (h x (hst hx)).mono hst lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : times_cont_diff_on 𝕜 m f s := λ x hx, (h x hx).of_le hmn /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h x hx).differentiable_within_at hn /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin assume x xs, rcases h x xs with ⟨u, u_open, xu, hu⟩, apply (times_cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩), exact mem_nhds_sets u_open xu end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases (h x hx) n.succ (le_refl _) with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume z hz m hm, refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hz, }, { assume h x hx, rw times_cont_diff_within_at_succ_iff_has_fderiv_within_at, rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩, have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd, exact ⟨u, u_nhbd, f', hu, hf' x this⟩ } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, continuous_linear_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F), have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw continuous_linear_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (mem_nhds_sets hu hx.2) ((unique_diff_within_at_inter (mem_nhds_sets hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume x hx m hm, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩ end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩, rw insert_eq_of_mem hx at hu, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (mem_nhds_sets o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h x hx m hm with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw insert_eq_of_mem hx at ho, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) } end lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : times_cont_diff_on 𝕜 n f s := begin assume x hx m hm, rw insert_eq_of_mem hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume y hy, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk y hy, convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume H, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩, rcases times_cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx) with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw [inter_comm, insert_eq_of_mem hx] at ho, have := hf'.mono ho, rw times_cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (mem_nhds_sets o_open xo)) at this, apply this.congr_of_eventually_eq' _ hx, have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩, rw inter_comm at this, apply filter.eventually_eq_of_mem this (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (mem_nhds_sets o_open hy.2) (hs y hy.1) at A, }, { rintros ⟨hdiff, h⟩ x hx, rw [times_cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ y hy, (hdiff y hy).has_fderiv_within_at, h x hx⟩ } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) : times_cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s := begin rw times_cont_diff_on_top_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.fderiv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s := (hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_fderiv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv 𝕜 f x) s := ((times_cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-! ### Functions with a Taylor series on the whole space -/ /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_zero.coe_add] /-! ### Smooth functions at a point -/ variable (𝕜) /-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`, there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous. -/ def times_cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) := times_cont_diff_within_at 𝕜 n f univ x variable {𝕜} theorem times_cont_diff_within_at_univ {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n f univ x ↔ times_cont_diff_at 𝕜 n f x := iff.rfl lemma times_cont_diff_at_top : times_cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_within_at_univ, times_cont_diff_within_at_top] lemma times_cont_diff_at.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : times_cont_diff_within_at 𝕜 n f s x := h.mono (subset_univ _) lemma times_cont_diff_within_at.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) : times_cont_diff_at 𝕜 n f x := by rwa [times_cont_diff_at, ← times_cont_diff_within_at_inter hx, univ_inter] lemma times_cont_diff_at.of_le {m n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hmn : m ≤ n) : times_cont_diff_at 𝕜 m f x := h.of_le hmn lemma times_cont_diff_at.continuous_at {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) : continuous_at f x := by simpa [continuous_within_at_univ] using h.continuous_within_at /-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/ lemma times_cont_diff_at.differentiable {n : with_top ℕ} (h : times_cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x := by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at /-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} : times_cont_diff_at 𝕜 ((n + 1) : ℕ) f x ↔ (∃ f' : E → (E →L[𝕜] F), (∃ u ∈ 𝓝 x, (∀ x ∈ u, has_fderiv_at f (f' x) x)) ∧ (times_cont_diff_at 𝕜 n f' x)) := begin rw [← times_cont_diff_within_at_univ, times_cont_diff_within_at_succ_iff_has_fderiv_within_at], simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem], split, { rintros ⟨u, H, f', h_fderiv, h_times_cont_diff⟩, rcases mem_nhds_sets_iff.mp H with ⟨t, htu, ht, hxt⟩, refine ⟨f', ⟨t, _⟩, h_times_cont_diff.times_cont_diff_at H⟩, refine ⟨mem_nhds_sets_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩, intros y hyt, refine (h_fderiv y (htu hyt)).has_fderiv_at _, exact mem_nhds_sets_iff.mpr ⟨t, htu, ht, hyt⟩ }, { rintros ⟨f', ⟨u, H, h_fderiv⟩, h_times_cont_diff⟩, refine ⟨u, H, f', _, h_times_cont_diff.times_cont_diff_within_at⟩, intros x hxu, exact (h_fderiv x hxu).has_fderiv_within_at } end /-! ### Smooth functions -/ variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition times_cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ x hx m hm, exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma times_cont_diff_iff_times_cont_diff_at {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ ∀ x, times_cont_diff_at 𝕜 n f x := by simp [← times_cont_diff_on_univ, times_cont_diff_on, times_cont_diff_at] lemma times_cont_diff.times_cont_diff_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_at 𝕜 n f x := times_cont_diff_iff_times_cont_diff_at.1 h x lemma times_cont_diff.times_cont_diff_within_at {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_within_at 𝕜 n f s x := h.times_cont_diff_at.times_cont_diff_within_at lemma times_cont_diff_top : times_cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s := (times_cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := begin rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ], exact times_cont_diff_on_zero end lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) : times_cont_diff 𝕜 m f := times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := times_cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma times_cont_diff.differentiable {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn /-! ### Iterated derivative -/ variable (𝕜) /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_fderiv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_zero.coe_add, -add_comm] /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_top_iff_fderiv : times_cont_diff 𝕜 ∞ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) := begin simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma times_cont_diff_zero_fun {n : with_top ℕ} : times_cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin suffices h : times_cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact times_cont_diff_zero_fun end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on lemma times_cont_diff_at_const {n : with_top ℕ} {c : F} : times_cont_diff_at 𝕜 n (λx : E, c) x := times_cont_diff_const.times_cont_diff_at lemma times_cont_diff_within_at_const {n : with_top ℕ} {c : F} : times_cont_diff_within_at 𝕜 n (λx : E, c) s x := times_cont_diff_at_const.times_cont_diff_within_at /-! ### Linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin suffices h : times_cont_diff 𝕜 ∞ f, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const end lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) : times_cont_diff 𝕜 n f := f.is_bounded_linear_map.times_cont_diff /-- The first projection in a product is `C^∞`. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The first projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_fst {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.fst : E × F → E) s := times_cont_diff.times_cont_diff_on times_cont_diff_fst /-- The first projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_fst {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.fst : E × F → E) p := times_cont_diff_fst.times_cont_diff_at /-- The first projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_fst {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p := times_cont_diff_fst.times_cont_diff_within_at /-- The second projection in a product is `C^∞`. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The second projection on a domain in a product is `C^∞`. -/ lemma times_cont_diff_on_snd {s : set (E×F)} {n : with_top ℕ} : times_cont_diff_on 𝕜 n (prod.snd : E × F → F) s := times_cont_diff.times_cont_diff_on times_cont_diff_snd /-- The second projection at a point in a product is `C^∞`. -/ lemma times_cont_diff_at_snd {p : E × F} {n : with_top ℕ} : times_cont_diff_at 𝕜 n (prod.snd : E × F → F) p := times_cont_diff_snd.times_cont_diff_at /-- The second projection within a domain at a point in a product is `C^∞`. -/ lemma times_cont_diff_within_at_snd {s : set (E × F)} {p : E × F} {n : with_top ℕ} : times_cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p := times_cont_diff_snd.times_cont_diff_within_at /-- The identity is `C^∞`. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin suffices h : times_cont_diff 𝕜 ∞ b, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin split, { assume x hx, simp [(hf.zero_eq x hx).symm] }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, have := hf.fderiv_within m hm x hx, convert has_fderiv_at.comp_has_fderiv_within_at x (hA.has_fderiv_at) this }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, exact hA.continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_within_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma times_cont_diff_at.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := times_cont_diff_within_at.continuous_linear_map_comp g hf /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := λ x hx, (hf x hx).continuous_linear_map_comp g /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp _ (times_cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_within_at_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have : f = e.symm ∘ (e ∘ f), by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) }, rw this, exact H.continuous_linear_map_comp _ }, { assume H, exact H.continuous_linear_map_comp _ } end /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_on_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s := by simp [times_cont_diff_on, e.comp_times_cont_diff_within_at_iff] /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) := begin let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ m h, h.comp_continuous_linear_map (λ _, g), have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) := λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g, split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, exact (hA m).continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on a domain. -/ lemma times_cont_diff_within_at.comp_continuous_linear_map {n : with_top ℕ} {x : G} (g : G →L[𝕜] E) (hf : times_cont_diff_within_at 𝕜 n f s (g x)) : times_cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { apply nhds_within_mono (g x) _ hu, rw image_insert_eq, exact insert_subset_insert (image_preimage_subset g s) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := λ x hx, (hf (g x) hx).comp_continuous_linear_map g /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability at a point in a domain. -/ lemma continuous_linear_equiv.times_cont_diff_within_at_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔ times_cont_diff_within_at 𝕜 n f s x := begin split, { assume H, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _}, { assume H, have : x = e (e.symm x), by simp, rw this at H, exact H.comp_continuous_linear_map _ }, end /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _ end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, convert hA.has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, exact hA.continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/ lemma times_cont_diff_within_at.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (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:E, (f x, g x)) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, rcases hg m hm with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem_sets hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := λ x hx, (hf x hx).prod (hg x hx) /-- The cartesian product of `C^n` functions at a point is `C^n`. -/ lemma times_cont_diff_at.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g x) : times_cont_diff_at 𝕜 n (λx:E, (f x, g x)) x := times_cont_diff_within_at_univ.1 $ times_cont_diff_within_at.prod (times_cont_diff_within_at_univ.2 hf) (times_cont_diff_within_at_univ.2 hg) /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma times_cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu }, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, rw insert_eq_of_mem hx at hu ⊢, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ 𝓝[s] x, { apply filter.inter_mem_sets self_mem_nhds_within, apply filter.inter_mem_sets hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { apply nhds_within_mono _ _ hv, exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := times_cont_diff_on.prod B A, have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on, exact IH D C (subset_univ _) } }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := by apply_instance, letI : normed_space 𝕜 Eu := by apply_instance, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := by apply_instance, letI : normed_space 𝕜 Fu := by apply_instance, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := by apply_instance, letI : normed_space 𝕜 Gu := by apply_instance, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s), by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t), by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff], have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply times_cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) (subset_univ _) /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) : times_cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hg.times_cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩, rcases hf.times_cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩, have xmem : x ∈ f ⁻¹' u ∩ v := ⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _), mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩, have : f ⁻¹' u ∈ 𝓝[insert x s] x, { apply hf.continuous_within_at'.preimage_mem_nhds_within', apply nhds_within_mono _ _ u_nhd, rw image_insert_eq, exact insert_subset_insert (image_subset_iff.mpr st) }, have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _)) .times_cont_diff_within_at) xmem m (le_refl _), have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x, { have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v), { apply subset.antisymm _ (inter_subset_right _ _), rintros y ⟨hy1, hy2⟩, simp [hy1, hy2, vs hy2] }, rw [A, ← nhds_within_restrict''], exact filter.inter_mem_sets this v_nhd }, rwa [insert_eq_of_mem xmem, this] at Z, end /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma times_cont_diff_within_at.comp' {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_within_at 𝕜 n g t (f x)) (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma times_cont_diff_at.comp {n : with_top ℕ} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff_at 𝕜 n g (f x)) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp x hf subset_preimage_univ lemma times_cont_diff.comp_times_cont_diff_within_at {n : with_top ℕ} {g : F → G} {f : E → F} (h : times_cont_diff 𝕜 n g) (hf : times_cont_diff_within_at 𝕜 n f t x) : times_cont_diff_within_at 𝕜 n (g ∘ f) t x := begin have : times_cont_diff_within_at 𝕜 n g univ (f x) := h.times_cont_diff_at.times_cont_diff_within_at, exact this.comp x hf (subset_univ _), end lemma times_cont_diff.comp_times_cont_diff_at {n : with_top ℕ} {g : F → G} {f : E → F} (x : E) (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (g ∘ f) x := hg.comp_times_cont_diff_within_at hf /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ , apply is_bounded_linear_map.snd.times_cont_diff } }, exact A.comp_times_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-! ### Sum of two functions -/ /- The sum is smooth. -/ lemma times_cont_diff_add {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2) := (is_bounded_linear_map.fst.add is_bounded_linear_map.snd).times_cont_diff /-- The sum of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.add {n : with_top ℕ} {s : set E} {f g : E → F} (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_add.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The sum of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.add {n : with_top ℕ} {f g : E → F} (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 := by rw [← times_cont_diff_within_at_univ] at *; exact hf.add hg /-- The sum of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := times_cont_diff_add.comp (hf.prod hg) /-- The sum of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (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).add (hg x hx) /-! ### Negative -/ /- The negative is smooth. -/ lemma times_cont_diff_neg {n : with_top ℕ} : times_cont_diff 𝕜 n (λp : F, -p) := is_bounded_linear_map.id.neg.times_cont_diff /-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at this point. -/ lemma times_cont_diff_within_at.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_within_at 𝕜 n f s x) : times_cont_diff_within_at 𝕜 n (λx, -f x) s x := times_cont_diff_neg.times_cont_diff_within_at.comp x hf subset_preimage_univ /-- The negative of a `C^n` function at a point is `C^n` at this point. -/ lemma times_cont_diff_at.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff_at 𝕜 n f x) : times_cont_diff_at 𝕜 n (λx, -f x) x := by rw ← times_cont_diff_within_at_univ at *; exact hf.neg /-- The negative of a `C^n`function is `C^n`. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := times_cont_diff_neg.comp hf /-- The negative of a `C^n` function on a domain is `C^n`. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s := λ x hx, (hf x hx).neg /-! ### Subtraction -/ /-- The difference of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.sub {n : with_top ℕ} {s : set E} {f g : E → F} (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 := hf.add hg.neg /-- The difference of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.sub {n : with_top ℕ} {f g : E → F} (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.add hg.neg /-- The difference of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (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 := hf.add hg.neg /-- The difference of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := hf.add hg.neg /-! ### Sum of finitely many functions -/ lemma times_cont_diff_within_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} {x : E} (h : ∀ i ∈ s, times_cont_diff_within_at 𝕜 n (λ x, f i x) t x) : times_cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x := begin classical, induction s using finset.induction_on with i s is IH, { simp [times_cont_diff_within_at_const] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end lemma times_cont_diff_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {x : E} (h : ∀ i ∈ s, times_cont_diff_at 𝕜 n (λ x, f i x) x) : times_cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x := by rw [← times_cont_diff_within_at_univ] at *; exact times_cont_diff_within_at.sum h lemma times_cont_diff_on.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} {t : set E} (h : ∀ i ∈ s, times_cont_diff_on 𝕜 n (λ x, f i x) t) : times_cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t := λ x hx, times_cont_diff_within_at.sum (λ i hi, h i hi x hx) lemma times_cont_diff.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {n : with_top ℕ} (h : ∀ i ∈ s, times_cont_diff 𝕜 n (λ x, f i x)) : times_cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) := by simp [← times_cont_diff_on_univ] at *; exact times_cont_diff_on.sum h /-! ### Product of two functions -/ /- The product is smooth. -/ lemma times_cont_diff_mul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) := is_bounded_bilinear_map_mul.times_cont_diff /-- The product of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (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_mul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The product of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.mul {n : with_top ℕ} {f g : E → 𝕜} (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 := by rw [← times_cont_diff_within_at_univ] at *; exact hf.mul hg /-- The product of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.mul {n : with_top ℕ} {f g : E → 𝕜} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x * g x) := times_cont_diff_mul.comp (hf.prod hg) /-- The product of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.mul {n : with_top ℕ} {s : set E} {f g : E → 𝕜} (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).mul (hg x hx) /-! ### Scalar multiplication -/ /- The scalar multiplication is smooth. -/ lemma times_cont_diff_smul {n : with_top ℕ} : times_cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) := is_bounded_bilinear_map_smul.times_cont_diff /-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma times_cont_diff_within_at.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (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_smul.times_cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/ lemma times_cont_diff_at.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (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 := by rw [← times_cont_diff_within_at_univ] at *; exact hf.smul hg /-- The scalar multiplication of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.smul {n : with_top ℕ} {f : E → 𝕜} {g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λ x, f x • g x) := times_cont_diff_smul.comp (hf.prod hg) /-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/ lemma times_cont_diff_on.smul {n : with_top ℕ} {s : set E} {f : E → 𝕜} {g : E → F} (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).smul (hg x hx) /-! ### Cartesian product of two functions-/ section prod_map variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {n : with_top ℕ} /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_within_at.prod_map' {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_within_at 𝕜 n f s p.1) (hg : times_cont_diff_within_at 𝕜 n g t p.2) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) p := (hf.comp p times_cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod (hg.comp p times_cont_diff_within_at_snd (prod_subset_preimage_snd _ _)) lemma times_cont_diff_within_at.prod_map {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_within_at 𝕜 n f s x) (hg : times_cont_diff_within_at 𝕜 n g t y) : times_cont_diff_within_at 𝕜 n (prod.map f g) (set.prod s t) (x, y) := times_cont_diff_within_at.prod_map' hf hg /-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/ lemma times_cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {s : set E} {t : set E'} {n : with_top ℕ} {f : E → F} {g : E' → F'} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g t) : times_cont_diff_on 𝕜 n (prod.map f g) (set.prod s t) := (hf.comp times_cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod (hg.comp (times_cont_diff_on_snd) (prod_subset_preimage_snd _ _)) /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : times_cont_diff_at 𝕜 n f x) (hg : times_cont_diff_at 𝕜 n g y) : times_cont_diff_at 𝕜 n (prod.map f g) (x, y) := begin rw times_cont_diff_at at *, convert hf.prod_map hg, simp only [univ_prod_univ] end /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma times_cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'} (hf : times_cont_diff_at 𝕜 n f p.1) (hg : times_cont_diff_at 𝕜 n g p.2) : times_cont_diff_at 𝕜 n (prod.map f g) p := begin rcases p, exact times_cont_diff_at.prod_map hf hg end /-- The product map of two `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod_map {f : E → F} {g : E' → F'} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (prod.map f g) := begin rw times_cont_diff_iff_times_cont_diff_at at *, exact λ ⟨x, y⟩, (hf x).prod_map (hg y) end end prod_map /-! ### Inversion in a complete normed algebra -/ section algebra_inverse variables (𝕜) (R : Type*) [normed_ring R] [normed_algebra 𝕜 R] open normed_ring continuous_linear_map ring /-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each invertible element. The proof is by induction, bootstrapping using an identity expressing the derivative of inversion as a bilinear map of inversion itself. -/ lemma times_cont_diff_at_ring_inverse [complete_space R] {n : with_top ℕ} (x : units R) : times_cont_diff_at 𝕜 n ring.inverse (x : R) := begin induction n using with_top.nat_induction with n IH Itop, { intros m hm, refine ⟨{y : R | is_unit y}, _, _⟩, { simp [nhds_within_univ], exact x.nhds }, { use (ftaylor_series_within 𝕜 inverse univ), rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff], split, { rintros _ ⟨x', hx'⟩, rw ← hx', exact (inverse_continuous_at x').continuous_within_at }, { simp [ftaylor_series_within] } } }, { apply times_cont_diff_at_succ_iff_has_fderiv_at.mpr, refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x, inverse x), _, _⟩, { refine ⟨{y : R | is_unit y}, x.nhds, _⟩, intros y hy, cases mem_set_of_eq.mp hy with y' hy', rw [← hy', inverse_unit], exact @has_fderiv_at_ring_inverse 𝕜 _ _ _ _ _ y' }, { exact (lmul_left_right_is_bounded_bilinear 𝕜 R).times_cont_diff.neg.comp_times_cont_diff_at (x : R) (IH.prod IH) } }, { exact times_cont_diff_at_top.mpr Itop } end end algebra_inverse /-! ### Inversion of continuous linear maps between Banach spaces -/ section map_inverse open continuous_linear_map /-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of inversion is `C^n`, for all `n`. -/ lemma times_cont_diff_at_map_inverse [complete_space E] {n : with_top ℕ} (e : E ≃L[𝕜] F) : times_cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) := begin -- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring -- `E →L[𝕜] E` let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)), let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f, have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂, { funext f, rw to_ring_inverse e}, rw this, -- `O₁` and `O₂` are `times_cont_diff`, so we reduce to proving that `ring.inverse` is `times_cont_diff` have h₁ : times_cont_diff 𝕜 n O₁, { exact is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_const.prod times_cont_diff_id) }, have h₂ : times_cont_diff 𝕜 n O₂, { exact is_bounded_bilinear_map_comp.times_cont_diff.comp (times_cont_diff_id.prod times_cont_diff_const) }, refine h₁.times_cont_diff_at.comp _ (times_cont_diff_at.comp _ _ h₂.times_cont_diff_at), -- this works differently depending on whether or not `E` is `nontrivial` (the condition for -- `E →L[𝕜] E` to be a `normed_algebra`) cases subsingleton_or_nontrivial E with _i _i; resetI, { convert @times_cont_diff_at_const _ _ _ _ _ _ _ _ _ _ (0 : E →L[𝕜] E), ext, simp }, { convert times_cont_diff_at_ring_inverse 𝕜 (E →L[𝕜] E) 1, simp [O₂], refl }, end end map_inverse section real /-! ### Results over `ℝ` The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and its extension fields such as `ℂ`). -/ variables {E' : Type*} [normed_group E'] [normed_space ℝ E'] {F' : Type*} [normed_group F'] [normed_space ℝ F'] /-- If a function has a Taylor series at order at least 1, then at points in the interior of the domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at {s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series ℝ E' F'} {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) : has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 ℝ E' F') (p x 1)) x := begin let f' := λ x, (continuous_multilinear_curry_fin1 ℝ E' F') (p x 1), have hf' : ∀ x, x ∈ s → has_fderiv_within_at f (f' x) s x := λ x, has_ftaylor_series_up_to_on.has_fderiv_within_at hf hn, have hcont : continuous_on f' s := (continuous_multilinear_curry_fin1 ℝ E' F').continuous.comp_continuous_on (hf.cont 1 hn), exact strict_fderiv_of_cont_diff hf' hcont hs, end /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma times_cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff_at ℝ n f x) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv ℝ f x) x := begin rcases hf 1 hn with ⟨u, H, p, hp⟩, simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H, have := hp.has_strict_fderiv_at (by norm_num) H, convert this, exact this.has_fderiv_at.fderiv end /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma times_cont_diff.has_strict_fderiv_at {f : E' → F'} {x : E'} {n : with_top ℕ} (hf : times_cont_diff ℝ n f) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv ℝ f x) x := hf.times_cont_diff_at.has_strict_fderiv_at hn end real section deriv /-! ### One dimension All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this paragraph, we reformulate some higher smoothness results in terms of `deriv`. -/ variables {f₂ : 𝕜 → F} {s₂ : set 𝕜} open continuous_linear_map (smul_right) /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ := begin rw times_cont_diff_on_succ_iff_fderiv_within hs, congr' 2, rw ← iff_iff_eq, split, { assume h, have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂), by { ext x, refl }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff }, { assume h, have : fderiv_within 𝕜 f₂ s₂ = (λ u, smul_right 1 u) ∘ (λ x, deriv_within f₂ s₂ x), by { ext x, simp [deriv_within] }, simp only [this], apply times_cont_diff.comp_times_cont_diff_on _ h, exact (is_bounded_bilinear_map_smul_right.is_bounded_linear_map_right _).times_cont_diff } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/ theorem times_cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 n (deriv f₂) s₂ := begin rw times_cont_diff_on_succ_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_deriv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((times_cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^∞`. -/ theorem times_cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) : times_cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ times_cont_diff_on 𝕜 ∞ (deriv f₂) s₂ := begin rw times_cont_diff_on_top_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply times_cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end lemma times_cont_diff_on.deriv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_deriv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.deriv_of_open {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (deriv f₂) s₂ := (hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm) lemma times_cont_diff_on.continuous_on_deriv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) : continuous_on (deriv_within f₂ s₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on lemma times_cont_diff_on.continuous_on_deriv_of_open {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) : continuous_on (deriv f₂) s₂ := ((times_cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on end deriv
acf495b338821ec71d8694022c1ffcfe32603dfa
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/smt_tests.lean
c4a4c59ed43f49053f80a2f1998fc422c725cdd8
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,578
lean
attribute [pre_smt] add_zero zero_add mul_one one_mul constant p : nat → nat → Prop constants a b : nat constant h : p (a + 1 * b + 0) (a + b) open tactic smt_tactic def ex : p (a + b) (a + b) := begin [smt] do { h ← to_expr ```(h), t ← infer_type h, (new_t, he) ← preprocess t, -- use smt_tactic preprocessor new_h ← mk_app `eq.mp [he, h], exact new_h } end def foo : nat → nat | 0 := 0 | (n+1) := 2*n lemma ex1 (n : nat) : n = 0 → foo (n+1) = 2*0 := begin [smt] intros, add_lemma [mul_zero, zero_mul], add_eqn_lemmas foo, ematch end lemma ex2 (n : nat) : n = 0 → foo (n+1) = 2*0 := begin [smt] intros, ematch_using [foo, mul_zero, zero_mul], end lemma ex3 (n : nat) : n = 0 → foo n = 0 := begin [smt] intros, add_eqn_lemmas foo end def boo : nat → nat | 0 := 1 | (n+1) := match foo n with | 0 := 2 | _ := 3 end lemma ex4 (n : nat) : n = 0 → boo (n+1) = 2 := begin [smt] intros, add_eqn_lemmas boo foo, ematch, end lemma ex5 (n : nat) : n = 0 → boo (n+1) = 2 := begin [smt] intros, ematch_using [boo, foo] end def r (x : nat) := x lemma ex6 (n : nat) : n = 0 → boo (n+1) = r 2 := begin [smt] intros, add_eqn_lemmas boo foo r, (smt_tactic.get_lemmas >>= smt_tactic.trace), ematch, end lemma ex7 (a b : nat) : a = 0 → b = a → b = 0 := begin [smt] intros, try { trace "hello", @smt_tactic.failed unit }, end set_option trace.smt true lemma ex8 (n : nat) : n = 0 → boo (n+1) = r 2 := begin [smt] intros, add_eqn_lemmas boo foo r, ematch, end
550ab8a6fa883704c96467f7cac45c4450ebb4cf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/lifting_properties/basic.lean
79a4919486576627290a0e3770a59d95327923fa
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,462
lean
/- Copyright (c) 2021 Jakob Scholbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Scholbach, Joël Riou -/ import category_theory.comm_sq /-! # Lifting properties This file defines the lifting property of two morphisms in a category and shows basic properties of this notion. ## Main results - `has_lifting_property`: the definition of the lifting property ## Tags lifting property @TODO : 1) define llp/rlp with respect to a `morphism_property` 2) retracts, direct/inverse images, (co)products, adjunctions -/ universe v namespace category_theory open category variables {C : Type*} [category C] {A B B' X Y Y' : C} (i : A ⟶ B) (i' : B ⟶ B') (p : X ⟶ Y) (p' : Y ⟶ Y') /-- `has_lifting_property i p` means that `i` has the left lifting property with respect to `p`, or equivalently that `p` has the right lifting property with respect to `i`. -/ class has_lifting_property : Prop := (sq_has_lift : ∀ {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g), sq.has_lift) @[priority 100] instance sq_has_lift_of_has_lifting_property {f : A ⟶ X} {g : B ⟶ Y} (sq : comm_sq f i p g) [hip : has_lifting_property i p] : sq.has_lift := by apply hip.sq_has_lift namespace has_lifting_property variables {i p} lemma op (h : has_lifting_property i p) : has_lifting_property p.op i.op := ⟨λ f g sq, begin simp only [comm_sq.has_lift.iff_unop, quiver.hom.unop_op], apply_instance, end⟩ lemma unop {A B X Y : Cᵒᵖ} {i : A ⟶ B} {p : X ⟶ Y} (h : has_lifting_property i p) : has_lifting_property p.unop i.unop := ⟨λ f g sq, begin rw comm_sq.has_lift.iff_op, simp only [quiver.hom.op_unop], apply_instance, end⟩ lemma iff_op : has_lifting_property i p ↔ has_lifting_property p.op i.op := ⟨op, unop⟩ lemma iff_unop {A B X Y : Cᵒᵖ} (i : A ⟶ B) (p : X ⟶ Y) : has_lifting_property i p ↔ has_lifting_property p.unop i.unop := ⟨unop, op⟩ variables (i p) @[priority 100] instance of_left_iso [is_iso i] : has_lifting_property i p := ⟨λ f g sq, comm_sq.has_lift.mk' { l := inv i ≫ f, fac_left' := by simp only [is_iso.hom_inv_id_assoc], fac_right' := by simp only [sq.w, assoc, is_iso.inv_hom_id_assoc], }⟩ @[priority 100] instance of_right_iso [is_iso p] : has_lifting_property i p := ⟨λ f g sq, comm_sq.has_lift.mk' { l := g ≫ inv p, fac_left' := by simp only [← sq.w_assoc, is_iso.hom_inv_id, comp_id], fac_right' := by simp only [assoc, is_iso.inv_hom_id, comp_id], }⟩ instance of_comp_left [has_lifting_property i p] [has_lifting_property i' p] : has_lifting_property (i ≫ i') p := ⟨λ f g sq, begin have fac := sq.w, rw assoc at fac, exact comm_sq.has_lift.mk' { l := (comm_sq.mk (comm_sq.mk fac).fac_right).lift, fac_left' := by simp only [assoc, comm_sq.fac_left], fac_right' := by simp only [comm_sq.fac_right], }, end⟩ instance of_comp_right [has_lifting_property i p] [has_lifting_property i p'] : has_lifting_property i (p ≫ p') := ⟨λ f g sq, begin have fac := sq.w, rw ← assoc at fac, let sq₂ := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift, exact comm_sq.has_lift.mk' { l := (comm_sq.mk ((comm_sq.mk fac).fac_left.symm)).lift, fac_left' := by simp only [comm_sq.fac_left], fac_right' := by simp only [comm_sq.fac_right_assoc, comm_sq.fac_right], }, end⟩ lemma of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'} (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) [hip : has_lifting_property i p] : has_lifting_property i' p := by { rw arrow.iso_w' e, apply_instance, } lemma of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'} (e : arrow.mk p ≅ arrow.mk p') [hip : has_lifting_property i p] : has_lifting_property i p' := by { rw arrow.iso_w' e, apply_instance, } lemma iff_of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'} (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) : has_lifting_property i p ↔ has_lifting_property i' p := by { split; introI, exacts [of_arrow_iso_left e p, of_arrow_iso_left e.symm p], } lemma iff_of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'} (e : arrow.mk p ≅ arrow.mk p') : has_lifting_property i p ↔ has_lifting_property i p' := by { split; introI, exacts [of_arrow_iso_right i e, of_arrow_iso_right i e.symm], } end has_lifting_property end category_theory
949a0915a982b4f937bf46bc52cf131ae484ee58
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/fiber_bundle/constructions.lean
fe7aca58bf792c10eb5fca5eca71108414a3efed
[ "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
16,728
lean
/- Copyright © 2022 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Sébastien Gouëzel, Heather Macbeth, Floris van Doorn -/ import topology.fiber_bundle.basic /-! # Standard constructions on fiber bundles This file contains several standard constructions on fiber bundles: * `bundle.trivial.fiber_bundle 𝕜 B F`: the trivial fiber bundle with model fiber `F` over the base `B` * `fiber_bundle.prod`: for fiber bundles `E₁` and `E₂` over a common base, a fiber bundle structure on their fiberwise product `E₁ ×ᵇ E₂` (the notation stands for `λ x, E₁ x × E₂ x`). * `fiber_bundle.pullback`: for a fiber bundle `E` over `B`, a fiber bundle structure on its pullback `f *ᵖ E` by a map `f : B' → B` (the notation is a type synonym for `E ∘ f`). ## Tags fiber bundle, fibre bundle, fiberwise product, pullback -/ open topological_space filter set bundle open_locale topology classical bundle /-! ### The trivial bundle -/ namespace bundle namespace trivial variables (B : Type*) (F : Type*) instance [I : topological_space F] : ∀ x : B, topological_space (trivial B F x) := λ x, I instance [t₁ : topological_space B] [t₂ : topological_space F] : topological_space (total_space (trivial B F)) := induced total_space.proj t₁ ⊓ induced (trivial.proj_snd B F) t₂ variables [topological_space B] [topological_space F] /-- Local trivialization for trivial bundle. -/ def trivialization : trivialization F (π (bundle.trivial B F)) := { to_fun := λ x, (x.fst, x.snd), inv_fun := λ y, ⟨y.fst, y.snd⟩, source := univ, target := univ, map_source' := λ x h, mem_univ (x.fst, x.snd), map_target' := λ y h, mem_univ ⟨y.fst, y.snd⟩, left_inv' := λ x h, sigma.eq rfl rfl, right_inv' := λ x h, prod.ext rfl rfl, open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [prod.topological_space, induced_inf, induced_compose], exact le_rfl, }, continuous_inv_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [bundle.total_space.topological_space, induced_inf, induced_compose], exact le_rfl, }, base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp only [univ_prod_univ], proj_to_fun := λ y hy, rfl } @[simp] lemma trivialization_source : (trivialization B F).source = univ := rfl @[simp] lemma trivialization_target : (trivialization B F).target = univ := rfl /-- Fiber bundle instance on the trivial bundle. -/ instance fiber_bundle : fiber_bundle F (bundle.trivial B F) := { trivialization_atlas := {bundle.trivial.trivialization B F}, trivialization_at := λ x, bundle.trivial.trivialization B F, mem_base_set_trivialization_at := mem_univ, trivialization_mem_atlas := λ x, mem_singleton _, total_space_mk_inducing := λ b, ⟨begin have : (λ (x : trivial B F b), x) = @id F, by { ext x, refl }, simp only [total_space.topological_space, induced_inf, induced_compose, function.comp, total_space.proj, induced_const, top_inf_eq, trivial.proj_snd, id.def, trivial.topological_space, this, induced_id], end⟩ } lemma eq_trivialization (e : _root_.trivialization F (π (bundle.trivial B F))) [i : mem_trivialization_atlas e] : e = trivialization B F := i.out end trivial end bundle /-! ### Fibrewise product of two bundles -/ section prod variables {B : Type*} section defs variables (E₁ : B → Type*) (E₂ : B → Type*) variables [topological_space (total_space E₁)] [topological_space (total_space E₂)] /-- Equip the total space of the fiberwise product of two fiber bundles `E₁`, `E₂` with the induced topology from the diagonal embedding into `total_space E₁ × total_space E₂`. -/ instance fiber_bundle.prod.topological_space : topological_space (total_space (E₁ ×ᵇ E₂)) := topological_space.induced (λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂))) (by apply_instance : topological_space (total_space E₁ × total_space E₂)) /-- The diagonal map from the total space of the fiberwise product of two fiber bundles `E₁`, `E₂` into `total_space E₁ × total_space E₂` is `inducing`. -/ lemma fiber_bundle.prod.inducing_diag : inducing (λ p, (⟨p.1, p.2.1⟩, ⟨p.1, p.2.2⟩) : total_space (E₁ ×ᵇ E₂) → total_space E₁ × total_space E₂) := ⟨rfl⟩ end defs open fiber_bundle variables [topological_space B] (F₁ : Type*) [topological_space F₁] (E₁ : B → Type*) [topological_space (total_space E₁)] (F₂ : Type*) [topological_space F₂] (E₂ : B → Type*) [topological_space (total_space E₂)] namespace trivialization variables {F₁ E₁ F₂ E₂} (e₁ : trivialization F₁ (π E₁)) (e₂ : trivialization F₂ (π E₂)) /-- Given trivializations `e₁`, `e₂` for fiber bundles `E₁`, `E₂` over a base `B`, the forward function for the construction `trivialization.prod`, the induced trivialization for the fiberwise product of `E₁` and `E₂`. -/ def prod.to_fun' : total_space (E₁ ×ᵇ E₂) → B × (F₁ × F₂) := λ p, ⟨p.1, (e₁ ⟨p.1, p.2.1⟩).2, (e₂ ⟨p.1, p.2.2⟩).2⟩ variables {e₁ e₂} lemma prod.continuous_to_fun : continuous_on (prod.to_fun' e₁ e₂) (@total_space.proj B (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) := begin let f₁ : total_space (E₁ ×ᵇ E₂) → total_space E₁ × total_space E₂ := λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂)), let f₂ : total_space E₁ × total_space E₂ → (B × F₁) × (B × F₂) := λ p, ⟨e₁ p.1, e₂ p.2⟩, let f₃ : (B × F₁) × (B × F₂) → B × F₁ × F₂ := λ p, ⟨p.1.1, p.1.2, p.2.2⟩, have hf₁ : continuous f₁ := (prod.inducing_diag E₁ E₂).continuous, have hf₂ : continuous_on f₂ (e₁.source ×ˢ e₂.source) := e₁.to_local_homeomorph.continuous_on.prod_map e₂.to_local_homeomorph.continuous_on, have hf₃ : continuous f₃ := (continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd), refine ((hf₃.comp_continuous_on hf₂).comp hf₁.continuous_on _).congr _, { rw [e₁.source_eq, e₂.source_eq], exact maps_to_preimage _ _ }, rintros ⟨b, v₁, v₂⟩ ⟨hb₁, hb₂⟩, simp only [prod.to_fun', prod.mk.inj_iff, eq_self_iff_true, and_true], rw e₁.coe_fst, rw [e₁.source_eq, mem_preimage], exact hb₁, end variables (e₁ e₂) [Π x, has_zero (E₁ x)] [∀ x, has_zero (E₂ x)] /-- Given trivializations `e₁`, `e₂` for fiber bundles `E₁`, `E₂` over a base `B`, the inverse function for the construction `trivialization.prod`, the induced trivialization for the fiberwise product of `E₁` and `E₂`. -/ noncomputable def prod.inv_fun' (p : B × (F₁ × F₂)) : total_space (E₁ ×ᵇ E₂) := ⟨p.1, e₁.symm p.1 p.2.1, e₂.symm p.1 p.2.2⟩ variables {e₁ e₂} lemma prod.left_inv {x : total_space (E₁ ×ᵇ E₂)} (h : x ∈ @total_space.proj B (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) : prod.inv_fun' e₁ e₂ (prod.to_fun' e₁ e₂ x) = x := begin obtain ⟨x, v₁, v₂⟩ := x, obtain ⟨h₁ : x ∈ e₁.base_set, h₂ : x ∈ e₂.base_set⟩ := h, simp only [prod.to_fun', prod.inv_fun', symm_apply_apply_mk, h₁, h₂] end lemma prod.right_inv {x : B × F₁ × F₂} (h : x ∈ (e₁.base_set ∩ e₂.base_set) ×ˢ (univ : set (F₁ × F₂))) : prod.to_fun' e₁ e₂ (prod.inv_fun' e₁ e₂ x) = x := begin obtain ⟨x, w₁, w₂⟩ := x, obtain ⟨⟨h₁ : x ∈ e₁.base_set, h₂ : x ∈ e₂.base_set⟩, -⟩ := h, simp only [prod.to_fun', prod.inv_fun', apply_mk_symm, h₁, h₂] end lemma prod.continuous_inv_fun : continuous_on (prod.inv_fun' e₁ e₂) ((e₁.base_set ∩ e₂.base_set) ×ˢ univ) := begin rw (prod.inducing_diag E₁ E₂).continuous_on_iff, have H₁ : continuous (λ p : B × F₁ × F₂, ((p.1, p.2.1), (p.1, p.2.2))) := (continuous_id.prod_map continuous_fst).prod_mk (continuous_id.prod_map continuous_snd), refine (e₁.continuous_on_symm.prod_map e₂.continuous_on_symm).comp H₁.continuous_on _, exact λ x h, ⟨⟨h.1.1, mem_univ _⟩, ⟨h.1.2, mem_univ _⟩⟩ end variables (e₁ e₂ e₁ e₂) /-- Given trivializations `e₁`, `e₂` for bundle types `E₁`, `E₂` over a base `B`, the induced trivialization for the fiberwise product of `E₁` and `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ noncomputable def prod : trivialization (F₁ × F₂) (π (E₁ ×ᵇ E₂)) := { to_fun := prod.to_fun' e₁ e₂, inv_fun := prod.inv_fun' e₁ e₂, source := (@total_space.proj B (E₁ ×ᵇ E₂)) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ set.univ, map_source' := λ x h, ⟨h, set.mem_univ _⟩, map_target' := λ x h, h.1, left_inv' := λ x, prod.left_inv, right_inv' := λ x, prod.right_inv, open_source := begin convert (e₁.open_source.prod e₂.open_source).preimage (fiber_bundle.prod.inducing_diag E₁ E₂).continuous, ext x, simp only [trivialization.source_eq] with mfld_simps, end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, continuous_to_fun := prod.continuous_to_fun, continuous_inv_fun := prod.continuous_inv_fun, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ x h, rfl } @[simp] lemma base_set_prod : (prod e₁ e₂).base_set = e₁.base_set ∩ e₂.base_set := rfl lemma prod_symm_apply (x : B) (w₁ : F₁) (w₂ : F₂) : (prod e₁ e₂).to_local_equiv.symm (x, w₁, w₂) = ⟨x, e₁.symm x w₁, e₂.symm x w₂⟩ := rfl end trivialization open trivialization variables [Π x, has_zero (E₁ x)] [∀ x, has_zero (E₂ x)] [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [fiber_bundle F₁ E₁] [fiber_bundle F₂ E₂] /-- The product of two fiber bundles is a fiber bundle. -/ noncomputable instance fiber_bundle.prod : fiber_bundle (F₁ × F₂) (E₁ ×ᵇ E₂) := { total_space_mk_inducing := λ b, begin rw (prod.inducing_diag E₁ E₂).inducing_iff, exact (total_space_mk_inducing F₁ E₁ b).prod_mk (total_space_mk_inducing F₂ E₂ b), end, trivialization_atlas := {e | ∃ (e₁ : trivialization F₁ (π E₁)) (e₂ : trivialization F₂ (π E₂)) [mem_trivialization_atlas e₁] [mem_trivialization_atlas e₂], by exactI e = trivialization.prod e₁ e₂}, trivialization_at := λ b, (trivialization_at F₁ E₁ b).prod (trivialization_at F₂ E₂ b), mem_base_set_trivialization_at := λ b, ⟨mem_base_set_trivialization_at F₁ E₁ b, mem_base_set_trivialization_at F₂ E₂ b⟩, trivialization_mem_atlas := λ b, ⟨trivialization_at F₁ E₁ b, trivialization_at F₂ E₂ b, by apply_instance, by apply_instance, rfl⟩ } instance {e₁ : trivialization F₁ (π E₁)} {e₂ : trivialization F₂ (π E₂)} [mem_trivialization_atlas e₁] [mem_trivialization_atlas e₂] : mem_trivialization_atlas (e₁.prod e₂ : trivialization (F₁ × F₂) (π (E₁ ×ᵇ E₂))) := { out := ⟨e₁, e₂, by apply_instance, by apply_instance, rfl⟩ } end prod /-! ### Pullbacks of fiber bundles -/ section variables {B : Type*} (F : Type*) (E : B → Type*) {B' : Type*} (f : B' → B) instance [∀ (x : B), topological_space (E x)] : ∀ (x : B'), topological_space ((f *ᵖ E) x) := by delta_instance bundle.pullback variables [topological_space B'] [topological_space (total_space E)] /-- Definition of `pullback.total_space.topological_space`, which we make irreducible. -/ @[irreducible] def pullback_topology : topological_space (total_space (f *ᵖ E)) := induced total_space.proj ‹topological_space B'› ⊓ induced (pullback.lift f) ‹topological_space (total_space E)› /-- The topology on the total space of a pullback bundle is the coarsest topology for which both the projections to the base and the map to the original bundle are continuous. -/ instance pullback.total_space.topological_space : topological_space (total_space (f *ᵖ E)) := pullback_topology E f lemma pullback.continuous_proj (f : B' → B) : continuous (@total_space.proj _ (f *ᵖ E)) := begin rw [continuous_iff_le_induced, pullback.total_space.topological_space, pullback_topology], exact inf_le_left, end lemma pullback.continuous_lift (f : B' → B) : continuous (@pullback.lift B E B' f) := begin rw [continuous_iff_le_induced, pullback.total_space.topological_space, pullback_topology], exact inf_le_right, end lemma inducing_pullback_total_space_embedding (f : B' → B) : inducing (@pullback_total_space_embedding B E B' f) := begin constructor, simp_rw [prod.topological_space, induced_inf, induced_compose, pullback.total_space.topological_space, pullback_topology], refl end section fiber_bundle variables (F) [topological_space F] [topological_space B] lemma pullback.continuous_total_space_mk [∀ x, topological_space (E x)] [fiber_bundle F E] {f : B' → B} {x : B'} : continuous (@total_space_mk _ (f *ᵖ E) x) := begin simp only [continuous_iff_le_induced, pullback.total_space.topological_space, induced_compose, induced_inf, function.comp, total_space_mk, total_space.proj, induced_const, top_inf_eq, pullback_topology], exact le_of_eq (fiber_bundle.total_space_mk_inducing F E (f x)).induced, end variables {E F} [∀ b, has_zero (E b)] {K : Type*} [continuous_map_class K B' B] /-- A fiber bundle trivialization can be pulled back to a trivialization on the pullback bundle. -/ noncomputable def trivialization.pullback (e : trivialization F (π E)) (f : K) : trivialization F (π ((f : B' → B) *ᵖ E)) := { to_fun := λ z, (z.proj, (e (pullback.lift f z)).2), inv_fun := λ y, @total_space_mk _ (f *ᵖ E) y.1 (e.symm (f y.1) y.2), source := pullback.lift f ⁻¹' e.source, base_set := f ⁻¹' e.base_set, target := (f ⁻¹' e.base_set) ×ˢ univ, map_source' := λ x h, by { simp_rw [e.source_eq, mem_preimage, pullback.proj_lift] at h, simp_rw [prod_mk_mem_set_prod_eq, mem_univ, and_true, mem_preimage, h] }, map_target' := λ y h, by { rw [mem_prod, mem_preimage] at h, simp_rw [e.source_eq, mem_preimage, pullback.proj_lift, h.1] }, left_inv' := λ x h, by { simp_rw [mem_preimage, e.mem_source, pullback.proj_lift] at h, simp_rw [pullback.lift, e.symm_apply_apply_mk h, total_space.eta] }, right_inv' := λ x h, by { simp_rw [mem_prod, mem_preimage, mem_univ, and_true] at h, simp_rw [total_space.proj_mk, pullback.lift_mk, e.apply_mk_symm h, prod.mk.eta] }, open_source := by { simp_rw [e.source_eq, ← preimage_comp], exact ((map_continuous f).comp $ pullback.continuous_proj E f).is_open_preimage _ e.open_base_set }, open_target := ((map_continuous f).is_open_preimage _ e.open_base_set).prod is_open_univ, open_base_set := (map_continuous f).is_open_preimage _ e.open_base_set, continuous_to_fun := (pullback.continuous_proj E f).continuous_on.prod (continuous_snd.comp_continuous_on $ e.continuous_on.comp (pullback.continuous_lift E f).continuous_on subset.rfl), continuous_inv_fun := begin dsimp only, simp_rw [(inducing_pullback_total_space_embedding E f).continuous_on_iff, function.comp, pullback_total_space_embedding, total_space.proj_mk], dsimp only [total_space.proj_mk], refine continuous_on_fst.prod (e.continuous_on_symm.comp ((map_continuous f).prod_map continuous_id).continuous_on subset.rfl) end, source_eq := by { dsimp only, rw e.source_eq, refl, }, target_eq := rfl, proj_to_fun := λ y h, rfl } noncomputable instance fiber_bundle.pullback [∀ x, topological_space (E x)] [fiber_bundle F E] (f : K) : fiber_bundle F ((f : B' → B) *ᵖ E) := { total_space_mk_inducing := λ x, inducing_of_inducing_compose (pullback.continuous_total_space_mk F E) (pullback.continuous_lift E f) (total_space_mk_inducing F E (f x)), trivialization_atlas := {ef | ∃ (e : trivialization F (π E)) [mem_trivialization_atlas e], ef = e.pullback f}, trivialization_at := λ x, (trivialization_at F E (f x)).pullback f, mem_base_set_trivialization_at := λ x, mem_base_set_trivialization_at F E (f x), trivialization_mem_atlas := λ x, ⟨trivialization_at F E (f x), by apply_instance, rfl⟩ } end fiber_bundle end
f1c4c357603edfa1533aa838b7fefdd4c0075e1b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/group_auto.lean
bbe1c3185d36441692b4d70463b330bda8654167
[]
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,322
lean
/- Copyright (c) 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.ring import Mathlib.tactic.doc_commands import Mathlib.PostPort universes u_1 namespace Mathlib /-! # `group` Normalizes expressions in the language of groups. The basic idea is to use the simplifier to put everything into a product of group powers (`gpow` which takes a group element and an integer), then simplify the exponents using the `ring` tactic. The process needs to be repeated since `ring` can normalize an exponent to zero, leading to a factor that can be removed before collecting exponents again. The simplifier step also uses some extra lemmas to avoid some `ring` invocations. ## Tags group_theory -/ -- The next four lemmas are not general purpose lemmas, they are intended for use only by -- the `group` tactic. theorem tactic.group.gpow_trick {G : Type u_1} [group G] (a : G) (b : G) (n : ℤ) (m : ℤ) : a * b ^ n * b ^ m = a * b ^ (n + m) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b ^ n * b ^ m = a * b ^ (n + m))) (mul_assoc a (b ^ n) (b ^ m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b ^ n * b ^ m) = a * b ^ (n + m))) (Eq.symm (gpow_add b n m)))) (Eq.refl (a * b ^ (n + m)))) theorem tactic.group.gpow_trick_one {G : Type u_1} [group G] (a : G) (b : G) (m : ℤ) : a * b * b ^ m = a * b ^ (m + 1) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b * b ^ m = a * b ^ (m + 1))) (mul_assoc a b (b ^ m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b * b ^ m) = a * b ^ (m + 1))) (mul_self_gpow b m))) (Eq.refl (a * b ^ (m + 1)))) theorem tactic.group.gpow_trick_one' {G : Type u_1} [group G] (a : G) (b : G) (n : ℤ) : a * b ^ n * b = a * b ^ (n + 1) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b ^ n * b = a * b ^ (n + 1))) (mul_assoc a (b ^ n) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b ^ n * b) = a * b ^ (n + 1))) (mul_gpow_self b n))) (Eq.refl (a * b ^ (n + 1)))) theorem tactic.group.gpow_trick_sub {G : Type u_1} [group G] (a : G) (b : G) (n : ℤ) (m : ℤ) : a * b ^ n * b ^ (-m) = a * b ^ (n - m) := eq.mpr (id (Eq._oldrec (Eq.refl (a * b ^ n * b ^ (-m) = a * b ^ (n - m))) (mul_assoc a (b ^ n) (b ^ (-m))))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b ^ n * b ^ (-m)) = a * b ^ (n - m))) (Eq.symm (gpow_add b n (-m))))) (Eq.refl (a * b ^ (n + -m)))) namespace tactic /-- Auxilliary tactic for the `group` tactic. Calls the simplifier only. -/ /-- Auxilliary tactic for the `group` tactic. Calls `ring` to normalize exponents. -/ end tactic namespace tactic.interactive /-- Tactic for normalizing expressions in multiplicative groups, without assuming commutativity, using only the group axioms without any information about which group is manipulated. (For additive commutative groups, use the `abel` tactic instead.) Example: ```lean example {G : Type} [group G] (a b c d : G) (h : c = (a*b^2)*((b*b)⁻¹*a⁻¹)*d) : a*c*d⁻¹ = a := begin group at h, -- normalizes `h` which becomes `h : c = d` rw h, -- the goal is now `a*d*d⁻¹ = a` group, -- which then normalized and closed end ``` -/ end tactic.interactive end Mathlib
e5d62ddcbbf38f4eabc5179dfa0f35759f3313c6
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/functor/equivalence.hlean
664920361da55ab9d7f0e09f168ec63a0137ca1c
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
18,912
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Functors which are equivalences or isomorphisms -/ import .adjoint open eq functor iso prod nat_trans is_equiv equiv is_trunc sigma.ops namespace category variables {C D : Precategory} {F : C ⇒ D} {G : D ⇒ C} structure is_equivalence [class] (F : C ⇒ D) extends is_left_adjoint F := mk' :: (is_iso_unit : is_iso η) (is_iso_counit : is_iso ε) abbreviation inverse := @is_equivalence.G postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded (there is no unicode superscript F) postfix [parsing_only] `⁻¹ᴱ`:std.prec.max_plus := inverse definition is_isomorphism [class] (F : C ⇒ D) := fully_faithful F × is_equiv (to_fun_ob F) structure equivalence (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_equivalence to_functor) structure isomorphism (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_isomorphism to_functor) structure weak_equivalence (C D : Precategory) := mk' :: (intermediate : Precategory) (left_functor : intermediate ⇒ C) (right_functor : intermediate ⇒ D) [structl : is_weak_equivalence left_functor] [structr : is_weak_equivalence right_functor] infix ` ≃c `:25 := equivalence infix ` ≅c `:25 := isomorphism infix ` ≃w `:25 := weak_equivalence attribute equivalence.struct isomorphism.struct [instance] [priority 1500] attribute equivalence.to_functor isomorphism.to_functor [coercion] definition is_iso_unit [instance] (F : C ⇒ D) [H : is_equivalence F] : is_iso (unit F) := !is_equivalence.is_iso_unit definition is_iso_counit [instance] (F : C ⇒ D) [H : is_equivalence F] : is_iso (counit F) := !is_equivalence.is_iso_counit definition iso_unit (F : C ⇒ D) [H : is_equivalence F] : F⁻¹ᴱ ∘f F ≅ 1 := (@(iso.mk _) !is_iso_unit)⁻¹ⁱ definition iso_counit (F : C ⇒ D) [H : is_equivalence F] : F ∘f F⁻¹ᴱ ≅ 1 := @(iso.mk _) !is_iso_counit definition split_essentially_surjective_of_is_equivalence [instance] (F : C ⇒ D) [is_equivalence F] : split_essentially_surjective F := begin intro d, fconstructor, { exact F⁻¹ d}, { exact componentwise_iso (@(iso.mk (counit F)) !is_iso_counit) d} end end category namespace category section parameters {C D : Precategory} {F : C ⇒ D} {G : D ⇒ C} (η : G ∘f F ≅ 1) (ε : F ∘f G ≅ 1) private definition ηn : 1 ⟹ G ∘f F := to_inv η private definition εn : F ∘f G ⟹ 1 := to_hom ε private definition ηi (c : C) : G (F c) ≅ c := componentwise_iso η c private definition εi (d : D) : F (G d) ≅ d := componentwise_iso ε d private definition ηi' (c : C) : G (F c) ≅ c := to_fun_iso G (to_fun_iso F (ηi c)⁻¹ⁱ) ⬝i to_fun_iso G (εi (F c)) ⬝i ηi c local attribute ηn εn ηi εi ηi' [reducible] private theorem adj_η_natural {c c' : C} (f : hom c c') : G (F f) ∘ to_inv (ηi' c) = to_inv (ηi' c') ∘ f := let ηi'_nat : G ∘f F ⟹ 1 := calc G ∘f F ⟹ (G ∘f F) ∘f 1 : id_right_natural_rev (G ∘f F) ... ⟹ (G ∘f F) ∘f (G ∘f F) : (G ∘f F) ∘fn ηn ... ⟹ ((G ∘f F) ∘f G) ∘f F : assoc_natural (G ∘f F) G F ... ⟹ (G ∘f (F ∘f G)) ∘f F : assoc_natural_rev G F G ∘nf F ... ⟹ (G ∘f 1) ∘f F : (G ∘fn εn) ∘nf F ... ⟹ G ∘f F : id_right_natural G ∘nf F ... ⟹ 1 : to_hom η in begin refine is_natural_inverse' (G ∘f F) functor.id ηi' ηi'_nat _ f, intro c, esimp, rewrite [+id_left,id_right] end private theorem adjointify_adjH (c : C) : to_hom (εi (F c)) ∘ F (to_hom (ηi' c))⁻¹ = id := begin rewrite [respect_inv], apply comp_inverse_eq_of_eq_comp, rewrite [id_left,↑ηi',+respect_comp,+respect_inv',assoc], apply eq_comp_inverse_of_comp_eq, rewrite [↑εi,-naturality_iso_id ε (F c)], symmetry, exact naturality εn (F (to_hom (ηi c))) end private theorem adjointify_adjK (d : D) : G (to_hom (εi d)) ∘ to_hom (ηi' (G d))⁻¹ⁱ = id := begin apply comp_inverse_eq_of_eq_comp, rewrite [id_left,↑ηi',+respect_inv',assoc], apply eq_comp_inverse_of_comp_eq, rewrite [↑ηi,-naturality_iso_id η (G d),↑εi,naturality_iso_id ε d], exact naturality (to_hom η) (G (to_hom (εi d))), end parameter (G) include η ε definition is_equivalence.mk : is_equivalence F := begin fapply is_equivalence.mk', { exact G}, { fapply nat_trans.mk, { intro c, exact to_inv (ηi' c)}, { intro c c' f, exact adj_η_natural f}}, { exact εn}, { exact adjointify_adjH}, { exact adjointify_adjK}, { exact @(is_natural_iso _) (λc, !is_iso_inverse)}, { unfold εn, apply iso.struct, }, end definition equivalence.MK : C ≃c D := equivalence.mk F is_equivalence.mk end section parameters {C D : Precategory} (F : C ⇒ D) [H₁ : fully_faithful F] [H₂ : split_essentially_surjective F] include H₁ H₂ definition inverse_of_fully_faithful_of_split_essentially_surjective [constructor] : D ⇒ C := begin fapply functor.mk, { exact λd, (H₂ d).1}, { intro d d' g, apply (to_fun_hom F)⁻¹ᶠ, refine to_inv (H₂ d').2 ∘ g ∘ to_hom (H₂ d).2}, { intro d, apply inv_eq_of_eq, rewrite [id_left, respect_id, to_left_inverse]}, { intros d₁ d₂ d₃ g f, apply inv_eq_of_eq, rewrite [respect_comp, +right_inv (to_fun_hom F), +assoc', comp_inverse_cancel_left]} end definition is_equivalence_of_fully_faithful_of_split_essentially_surjective [constructor] : is_equivalence F := begin fapply is_equivalence.mk, { exact inverse_of_fully_faithful_of_split_essentially_surjective}, { fapply natural_iso.mk', { intro c, esimp, apply reflect_iso F, exact (H₂ (F c)).2}, intro c c' f, esimp, apply inj' (to_fun_hom F), rewrite [+respect_comp, +right_inv (to_fun_hom F), comp_inverse_cancel_left]}, { fapply natural_iso.mk', { intro c, esimp, exact (H₂ c).2}, intro c c' f, esimp, rewrite [right_inv (to_fun_hom F), comp_inverse_cancel_left]} end end variables {C D E : Precategory} {F : C ⇒ D} --TODO: add variants definition unit_eq_counit_inv (F : C ⇒ D) [H : is_equivalence F] (c : C) : to_fun_hom F (natural_map (unit F) c) = @(is_iso.inverse (counit F (F c))) (@(componentwise_is_iso (counit F)) !is_iso_counit (F c)) := begin apply eq_inverse_of_comp_eq_id, apply counit_unit_eq end definition fully_faithful_of_is_equivalence [instance] [constructor] (F : C ⇒ D) [H : is_equivalence F] : fully_faithful F := begin intro c c', fapply adjointify, { intro g, exact natural_map (@(iso.inverse (unit F)) !is_iso_unit) c' ∘ F⁻¹ g ∘ unit F c}, { intro g, rewrite [+respect_comp,▸*], xrewrite [natural_map_inverse (unit F) c', respect_inv'], apply inverse_comp_eq_of_eq_comp, rewrite [+unit_eq_counit_inv], esimp, exact naturality (counit F)⁻¹ _}, { intro f, xrewrite [▸*,natural_map_inverse (unit F) c'], apply inverse_comp_eq_of_eq_comp, apply naturality (unit F)}, end definition is_isomorphism.mk [constructor] {F : C ⇒ D} (G : D ⇒ C) (p : G ∘f F = 1) (q : F ∘f G = 1) : is_isomorphism F := begin constructor, { apply fully_faithful_of_is_equivalence, fapply is_equivalence.mk, { exact G}, { apply iso_of_eq p}, { apply iso_of_eq q}}, { fapply adjointify, { exact G}, { exact ap010 to_fun_ob q}, { exact ap010 to_fun_ob p}} end definition isomorphism.MK [constructor] (F : C ⇒ D) (G : D ⇒ C) (p : G ∘f F = 1) (q : F ∘f G = 1) : C ≅c D := isomorphism.mk F (is_isomorphism.mk G p q) definition is_equiv_ob_of_is_isomorphism [instance] [unfold 4] (F : C ⇒ D) [H : is_isomorphism F] : is_equiv (to_fun_ob F) := pr2 H definition fully_faithful_of_is_isomorphism [unfold 4] (F : C ⇒ D) [H : is_isomorphism F] : fully_faithful F := pr1 H section local attribute fully_faithful_of_is_isomorphism [instance] definition strict_inverse [constructor] (F : C ⇒ D) [H : is_isomorphism F] : D ⇒ C := begin fapply functor.mk, { intro d, exact (to_fun_ob F)⁻¹ᶠ d}, { intro d d' g, exact (to_fun_hom F)⁻¹ᶠ (inv_of_eq !right_inv ∘ g ∘ hom_of_eq !right_inv)}, { intro d, apply inv_eq_of_eq, rewrite [respect_id,id_left], apply left_inverse}, { intro d₁ d₂ d₃ g₂ g₁, apply inv_eq_of_eq, rewrite [respect_comp F,+right_inv (to_fun_hom F)], rewrite [+assoc], esimp, /-apply ap (λx, (x ∘ _) ∘ _), FAILS-/ refine ap (λx, (x ∘ _) ∘ _) _, refine !id_right⁻¹ ⬝ _, rewrite [▸*,-+assoc], refine ap (λx, _ ∘ _ ∘ x) _, exact !right_inverse⁻¹}, end postfix /-[parsing-only]-/ `⁻¹ˢ`:std.prec.max_plus := strict_inverse definition strict_right_inverse (F : C ⇒ D) [H : is_isomorphism F] : F ∘f F⁻¹ˢ = 1 := begin fapply functor_eq, { intro d, esimp, apply right_inv}, { intro d d' g, rewrite [▸*, right_inv (to_fun_hom F), +assoc], rewrite [↑[hom_of_eq,inv_of_eq,iso.to_inv], right_inverse], rewrite [id_left], apply comp_inverse_cancel_right}, end definition strict_left_inverse (F : C ⇒ D) [H : is_isomorphism F] : F⁻¹ˢ ∘f F = 1 := begin fapply functor_eq, { intro d, esimp, apply left_inv}, { intro d d' g, esimp, apply comp_eq_of_eq_inverse_comp, apply comp_inverse_eq_of_eq_comp, apply inv_eq_of_eq, rewrite [+respect_comp,-assoc], apply ap011 (λx y, x ∘ F g ∘ y), { rewrite [adj], rewrite [▸*,respect_inv_of_eq F]}, { rewrite [adj,▸*,respect_hom_of_eq F]}}, end end definition is_equivalence_of_is_isomorphism [instance] [constructor] (F : C ⇒ D) [is_isomorphism F] : is_equivalence F := begin fapply is_equivalence.mk, { apply F⁻¹ˢ}, { apply iso_of_eq !strict_left_inverse}, { apply iso_of_eq !strict_right_inverse}, end definition equivalence_of_isomorphism [constructor] (F : C ≅c D) : C ≃c D := equivalence.mk F _ theorem is_prop_is_equivalence [instance] {C : Category} {D : Precategory} (F : C ⇒ D) : is_prop (is_equivalence F) := begin have f : is_equivalence F ≃ Σ(H : is_left_adjoint F), is_iso (unit F) × is_iso (counit F), begin fapply equiv.MK, { intro H, induction H, fconstructor: constructor, repeat (esimp;assumption) }, { intro H, induction H with H1 H2, induction H1, induction H2, constructor, repeat (esimp at *;assumption)}, { intro H, induction H with H1 H2, induction H1, induction H2, reflexivity}, { intro H, induction H, reflexivity} end, exact is_trunc_equiv_closed_rev -1 f _ end theorem is_prop_is_isomorphism [instance] (F : C ⇒ D) : is_prop (is_isomorphism F) := by unfold is_isomorphism; exact _ /- closure properties -/ definition is_isomorphism_id [instance] [constructor] (C : Precategory) : is_isomorphism (1 : C ⇒ C) := is_isomorphism.mk 1 !functor.id_right !functor.id_right definition is_isomorphism_strict_inverse [constructor] (F : C ⇒ D) [K : is_isomorphism F] : is_isomorphism F⁻¹ˢ := is_isomorphism.mk F !strict_right_inverse !strict_left_inverse definition is_isomorphism_compose [constructor] (G : D ⇒ E) (F : C ⇒ D) [H : is_isomorphism G] [K : is_isomorphism F] : is_isomorphism (G ∘f F) := is_isomorphism.mk (F⁻¹ˢ ∘f G⁻¹ˢ) abstract begin rewrite [functor.assoc,-functor.assoc F⁻¹ˢ,strict_left_inverse,functor.id_right, strict_left_inverse] end end abstract begin rewrite [functor.assoc,-functor.assoc G,strict_right_inverse,functor.id_right, strict_right_inverse] end end definition is_equivalence_id [constructor] (C : Precategory) : is_equivalence (1 : C ⇒ C) := _ definition is_equivalence_inverse [constructor] (F : C ⇒ D) [K : is_equivalence F] : is_equivalence F⁻¹ᴱ := is_equivalence.mk F (iso_counit F) (iso_unit F) definition is_equivalence_compose [constructor] (G : D ⇒ E) (F : C ⇒ D) [H : is_equivalence G] [K : is_equivalence F] : is_equivalence (G ∘f F) := is_equivalence.mk (F⁻¹ᴱ ∘f G⁻¹ᴱ) abstract begin rewrite [functor.assoc,-functor.assoc F⁻¹ᴱ], refine ((_ ∘fi !iso_unit) ∘if _) ⬝i _, refine (iso_of_eq !functor.id_right ∘if _) ⬝i _, apply iso_unit end end abstract begin rewrite [functor.assoc,-functor.assoc G], refine ((_ ∘fi !iso_counit) ∘if _) ⬝i _, refine (iso_of_eq !functor.id_right ∘if _) ⬝i _, apply iso_counit end end variable (C) definition equivalence.refl [refl] [constructor] : C ≃c C := equivalence.mk _ !is_equivalence_id definition isomorphism.refl [refl] [constructor] : C ≅c C := isomorphism.mk _ !is_isomorphism_id variable {C} definition equivalence.symm [symm] [constructor] (H : C ≃c D) : D ≃c C := equivalence.mk _ (is_equivalence_inverse H) definition isomorphism.symm [symm] [constructor] (H : C ≅c D) : D ≅c C := isomorphism.mk _ (is_isomorphism_strict_inverse H) definition equivalence.trans [trans] [constructor] (H : C ≃c D) (K : D ≃c E) : C ≃c E := equivalence.mk _ (is_equivalence_compose K H) definition isomorphism.trans [trans] [constructor] (H : C ≅c D) (K : D ≅c E) : C ≅c E := isomorphism.mk _ (is_isomorphism_compose K H) definition equivalence.to_strict_inverse [unfold 3] (H : C ≃c D) : D ⇒ C := H⁻¹ᴱ definition isomorphism.to_strict_inverse [unfold 3] (H : C ≅c D) : D ⇒ C := H⁻¹ˢ definition is_isomorphism_of_is_equivalence [constructor] {C D : Category} (F : C ⇒ D) [H : is_equivalence F] : is_isomorphism F := begin fapply is_isomorphism.mk, { exact F⁻¹ᴱ}, { apply eq_of_iso, apply iso_unit}, { apply eq_of_iso, apply iso_counit}, end definition isomorphism_of_equivalence [constructor] {C D : Category} (F : C ≃c D) : C ≅c D := isomorphism.mk F !is_isomorphism_of_is_equivalence definition equivalence_eq {C : Category} {D : Precategory} {F F' : C ≃c D} (p : equivalence.to_functor F = equivalence.to_functor F') : F = F' := begin induction F, induction F', exact apd011 equivalence.mk p !is_prop.elimo end definition isomorphism_eq {F F' : C ≅c D} (p : isomorphism.to_functor F = isomorphism.to_functor F') : F = F' := begin induction F, induction F', exact apd011 isomorphism.mk p !is_prop.elimo end definition is_equiv_isomorphism_of_equivalence [constructor] (C D : Category) : is_equiv (@equivalence_of_isomorphism C D) := begin fapply adjointify, { exact isomorphism_of_equivalence}, { intro F, apply equivalence_eq, reflexivity}, { intro F, apply isomorphism_eq, reflexivity}, end definition isomorphism_equiv_equivalence [constructor] (C D : Category) : (C ≅c D) ≃ (C ≃c D) := equiv.mk _ !is_equiv_isomorphism_of_equivalence definition isomorphism_of_eq [constructor] {C D : Precategory} (p : C = D) : C ≅c D := isomorphism.MK (functor_of_eq p) (functor_of_eq p⁻¹) (by induction p; reflexivity) (by induction p; reflexivity) definition equiv_ob_of_isomorphism [constructor] {C D : Precategory} (H : C ≅c D) : C ≃ D := equiv.mk H _ definition equiv_hom_of_isomorphism [constructor] {C D : Precategory} (H : C ≅c D) (c c' : C) : c ⟶ c' ≃ H c ⟶ H c' := equiv.mk (to_fun_hom (isomorphism.to_functor H)) _ /- weak equivalences -/ theorem is_prop_is_weak_equivalence [instance] (F : C ⇒ D) : is_prop (is_weak_equivalence F) := by unfold is_weak_equivalence; exact _ definition is_weak_equivalence_of_is_equivalence [instance] (F : C ⇒ D) [is_equivalence F] : is_weak_equivalence F := (_, _) definition fully_faithful_of_is_weak_equivalence.mk [instance] (F : C ⇒ D) [H : is_weak_equivalence F] : fully_faithful F := pr1 H definition essentially_surjective_of_is_weak_equivalence.mk [instance] (F : C ⇒ D) [H : is_weak_equivalence F] : essentially_surjective F := pr2 H definition is_weak_equivalence_compose (G : D ⇒ E) (F : C ⇒ D) [H : is_weak_equivalence G] [K : is_weak_equivalence F] : is_weak_equivalence (G ∘f F) := (fully_faithful_compose G F, essentially_surjective_compose G F) definition weak_equivalence.mk [constructor] (F : C ⇒ D) (H : is_weak_equivalence F) : C ≃w D := weak_equivalence.mk' C 1 F definition weak_equivalence.symm [unfold 3] : C ≃w D → D ≃w C | (@weak_equivalence.mk' _ _ X F₁ F₂ H₁ H₂) := weak_equivalence.mk' X F₂ F₁ /- TODO definition is_equiv_isomorphism_of_eq [constructor] (C D : Precategory) : is_equiv (@isomorphism_of_eq C D) := begin fapply adjointify, { intro H, fapply Precategory_eq_of_equiv, { apply equiv_ob_of_isomorphism H}, { exact equiv_hom_of_isomorphism H}, { /-exact sorry FAILS-/ intros, esimp, apply respect_comp}}, { intro H, apply isomorphism_eq, esimp, fapply functor_eq: esimp, { intro c, exact sorry}, { exact sorry}}, { intro p, induction p, esimp, exact sorry}, end definition eq_equiv_isomorphism [constructor] (C D : Precategory) : (C = D) ≃ (C ≅c D) := equiv.mk _ !is_equiv_isomorphism_of_eq definition equivalence_of_eq [unfold 3] [reducible] {C D : Precategory} (p : C = D) : C ≃c D := equivalence_of_isomorphism (isomorphism_of_eq p) definition eq_equiv_equivalence [constructor] (C D : Category) : (C = D) ≃ (C ≃c D) := !eq_equiv_isomorphism ⬝e !isomorphism_equiv_equivalence definition is_equivalence_equiv [constructor] (F : C ⇒ D) : is_equivalence F ≃ (fully_faithful F × split_essentially_surjective F) := sorry definition is_equivalence_equiv_is_weak_equivalence [constructor] {C D : Category} (F : C ⇒ D) : is_equivalence F ≃ is_weak_equivalence F := sorry -- weak_equivalence.trans -/ /- TODO? definition is_isomorphism_equiv1 (F : C ⇒ D) : is_equivalence F ≃ Σ(G : D ⇒ C) (η : 1 = G ∘f F) (ε : F ∘f G = 1), sorry ⬝ ap (λ(H : C ⇒ C), F ∘f H) η ⬝ sorry = ap (λ(H : D ⇒ D), H ∘f F) ε⁻¹ := sorry definition is_isomorphism_equiv2 (F : C ⇒ D) : is_equivalence F ≃ ∃(G : D ⇒ C), 1 = G ∘f F × F ∘f G = 1 := sorry -/ end category
8cc759d2475b655c24d6e31386276346fdd5f4bb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/discrsIssue.lean
df05f1ce14dfc89bd24fb6c0bf32fae434aab057
[ "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,223
lean
inductive Expr where | nat : Nat → Expr | plus : Expr → Expr → Expr | bool : Bool → Expr | and : Expr → Expr → Expr inductive Ty where | nat | bool deriving DecidableEq inductive HasType : Expr → Ty → Prop | nat : HasType (.nat v) .nat | plus : HasType a .nat → HasType b .nat → HasType (.plus a b) .nat | bool : HasType (.bool v) .bool | and : HasType a .bool → HasType b .bool → HasType (.and a b) .bool theorem HasType.det (h₁ : HasType e t₁) (h₂ : HasType e t₂) : t₁ = t₂ := by cases h₁ <;> cases h₂ <;> rfl inductive Maybe (p : α → Prop) where | found : (a : α) → p a → Maybe p | unknown notation "{{ " x " | " p " }}" => Maybe (fun x => p) def Expr.typeCheck (e : Expr) : {{ ty | HasType e ty }} := match e with | nat .. => .found .nat .nat | bool .. => .found .bool .bool | plus a b => match a.typeCheck, b.typeCheck with | .found .nat h₁, .found .nat h₂ => .found .nat (.plus h₁ h₂) --^ $/lean/plainTermGoal | _, _ => .unknown | and a b => match a.typeCheck, b.typeCheck with | .found .bool h₁, .found .bool h₂ => .found .bool (.and h₁ h₂) | _, _ => .unknown
05b2867d6c7126a22d2ae82b37328b0ade9c3920
618003631150032a5676f229d13a079ac875ff77
/test/fin_cases.lean
c52ba4afc7852f457e21960ea84af94775d71145
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,128
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.fin_cases import data.nat.prime import group_theory.perm.sign example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, simp, assumption, simp, assumption, simp, assumption, end example (x2 : fin 2) (x3 : fin 3) (n : nat) (y : fin n) : x2.val * x3.val = x3.val * x2.val := begin fin_cases x2; fin_cases x3, success_if_fail { fin_cases * }, success_if_fail { fin_cases y }, all_goals { simp }, end open finset example (x : ℕ) (h : x ∈ Ico 2 5) : x = 2 ∨ x = 3 ∨ x = 4 := begin fin_cases h, all_goals { simp } end open nat example (x : ℕ) (h : x ∈ [2,3,5,7]) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h, all_goals { simp } end example (x : ℕ) (h : x ∈ [2,3,5,7]) : true := begin success_if_fail { fin_cases h with [3,3,5,7] }, trivial end example (x : list ℕ) (h : x ∈ [[1],[2]]) : x.length = 1 := begin fin_cases h with [[1],[1+1]], simp, guard_target (list.length [1 + 1] = 1), simp end -- testing that `with` arguments are elaborated with respect to the expected type: example (x : ℤ) (h : x ∈ ([2,3] : list ℤ)) : x = 2 ∨ x = 3 := begin fin_cases h with [2,3], all_goals { simp } end instance (n : ℕ) : decidable (prime n) := decidable_prime_1 n example (x : ℕ) (h : x ∈ (range 10).filter prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := begin fin_cases h; exact dec_trivial end open equiv.perm example (x : (Σ (a : fin 4), fin 4)) (h : x ∈ fin_pairs_lt 4) : x.1.val < 4 := begin fin_cases h; simp, any_goals { exact dec_trivial }, end example (x : fin 3) : x.val < 5 := begin fin_cases x; exact dec_trivial end example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *, all_goals { assumption } end example (n : ℕ) (h : n % 3 ∈ [0,1]) : true := begin fin_cases h, guard_hyp h := n % 3 = 0, trivial, guard_hyp h := n % 3 = 1, trivial, end
da5c9b43ffe3e6b31fda96c63818b8f4da94546d
e2fc96178628c7451e998a0db2b73877d0648be5
/test/demo_context_free.lean
e90ebff11dbf1c9551517470870b24d3a9bbf635
[ "BSD-2-Clause" ]
permissive
madvorak/grammars
cd324ae19b28f7b8be9c3ad010ef7bf0fabe5df2
1447343a45fcb7821070f1e20b57288d437323a6
refs/heads/main
1,692,383,644,884
1,692,032,429,000
1,692,032,429,000
453,948,141
7
0
null
null
null
null
UTF-8
Lean
false
false
25,888
lean
import classes.context_free.basics.toolbox import utilities.list_utils import utilities.written_by_others.trim_assoc private def a_ : fin 3 := 0 private def a : symbol (fin 3) (fin 2) := symbol.terminal a_ private def b_ : fin 3 := 1 private def b : symbol (fin 3) (fin 2) := symbol.terminal b_ private def c_ : fin 3 := 2 private def c : symbol (fin 3) (fin 2) := symbol.terminal c_ private def S_ : fin 2 := 0 private def S : symbol (fin 3) (fin 2) := symbol.nonterminal S_ private def R_ : fin 2 := 1 private def R : symbol (fin 3) (fin 2) := symbol.nonterminal R_ private def gr_add : CF_grammar (fin 3) := CF_grammar.mk (fin 2) S_ [ (S_, [a, S, c]), (S_, [R]), (R_, [b, R, c]), (R_, []) ] example : CF_generates gr_add [a_, a_, b_, c_, c_, c_] := begin unfold gr_add, apply CF_deri_of_tran_deri, { use (S_, [a, S, c]), split_ile, use [[], []], simp, }, apply CF_deri_of_tran_deri, { use (S_, [a, S, c]), split_ile, use [[a], [c]], rw S, simp, }, apply CF_deri_of_tran_deri, { use (S_, [R]), split_ile, use [[a, a], [c, c]], simp, }, apply CF_deri_of_tran_deri, { use (R_, [b, R, c]), split_ile, use [[a, a], [c, c]], rw R, simp, }, apply CF_deri_of_tran, { use (R_, []), split_ile, use [[a, a, b], [c, c, c]], repeat { try {split}, try {refl} }, }, end private def anbmcnm (n m : ℕ) : list (fin 3) := list.repeat a_ n ++ list.repeat b_ m ++ list.repeat c_ (n + m) private def language_add : language (fin 3) := λ x, ∃ n m : ℕ, x = anbmcnm n m example : [a_, a_, b_, c_, c_, c_] ∈ language_add := begin use 2, use 1, refl, end example : CF_language gr_add = language_add := begin ext, split, { -- prove `x ∈ CF_language gr_add → x ∈ language_add` here intro ass, change CF_derives gr_add [S] (list.map symbol.terminal x) at ass, have possib : ∀ w : list (symbol (fin 3) gr_add.nt), CF_derives gr_add [S] w → (∃ i : ℕ, w = list.repeat a i ++ [S] ++ list.repeat c i) ∨ (∃ i j : ℕ, w = list.repeat a i ++ list.repeat b j ++ [R] ++ list.repeat c (i + j)) ∨ (∃ i j : ℕ, w = list.repeat a i ++ list.repeat b j ++ list.repeat c (i + j)), { intros w hyp, induction hyp with y z irr step ih, { left, use 0, refl, }, cases step with rule foo, cases foo with rule_in bar, cases bar with u baz, cases baz with v hyp, cases hyp with hyp_bef hyp_aft, cases ih with case₁ caseᵣ, { -- the case `list.repeat a i ++ [S] ++ list.repeat c i` matches 1st and 2nd rule cases rule_in, { left, cases case₁ with i the_case, rw list.append_assoc at the_case, use i + 1, have almost : z = list.repeat a i ++ [a, S, c] ++ list.repeat c i, { rw hyp_bef at the_case, rw hyp_aft, rw rule_in at *, have u_must : u = list.repeat a i, { dsimp only at *, rw ←S at *, have indexS: (u ++ [S] ++ v).nth u.length = some S, { rw list.append_assoc, rw list.nth_append_right (le_of_eq rfl), rw tsub_self, refl, }, cases @trichotomous ℕ (<) _ (list.length u) i with hlt hge, { exfalso, rw the_case at indexS, rw ←list.nth_take hlt at indexS, rw list.take_append_of_le_length (le_of_eq (list.length_repeat a i).symm) at indexS, rw list.take_repeat at indexS, rw min_self at indexS, rw ←list.length_repeat a i at hlt, have please : (list.repeat a i).nth_le u.length hlt = S, { rw list.nth_le_nth hlt at indexS, injection indexS, }, rw list.nth_le_repeat a hlt at please, injection please, }, cases hge.symm with hgt heq, { exfalso, rw the_case at indexS, have rightend : u.length < (list.repeat a i ++ [S] ++ list.repeat c i).length, { have thelength := congr_arg list.length the_case, rw list.append_assoc at thelength, rw list.length_append at thelength, rw list.append_assoc, rw ←thelength, rw list.length_append, rw list.length_singleton, rw ←add_assoc, apply lt_of_lt_of_le, { exact lt_add_one u.length, }, exact le_self_add, }, rw ←list.append_assoc at indexS, rw list.nth_le_nth rightend at indexS, injection indexS with continue, have mala : (list.repeat a i ++ [S]).length ≤ u.length, { rw list.length_append, rw list.length_singleton, rw list.length_repeat a i, rw ←nat.succ_le_iff at hgt, apply hgt, }, rw list.nth_le_append_right mala at continue, finish, }, rw list.append_assoc at the_case, apply list.append_inj_left the_case, rw heq, finish, }, have v_must : v = list.repeat c i, { rw u_must at the_case, rw list.append_assoc at the_case, rw list.append_right_inj (list.repeat a i) at the_case, rw ←S at the_case, rw list.append_right_inj [S] at the_case, exact the_case, }, rw u_must, rw v_must, }, rw list.repeat_add, change z = list.repeat a i ++ [a] ++ [S] ++ list.repeat c (i + 1), rw add_comm, rw list.repeat_add, change z = list.repeat a i ++ [a] ++ [S] ++ ([c] ++ list.repeat c i), rw ←list.append_assoc, rw list.append_assoc (list.repeat a i) [a], rw list.append_assoc (list.repeat a i) ([a] ++ [S]), convert almost, }, cases rule_in, { right, left, cases case₁ with i the_case, use i, use 0, simp, have u_must : u = list.repeat a i, { have indexS: (u ++ [S] ++ v).nth u.length = some S, { rw list.append_assoc, rw list.nth_append_right (le_of_eq rfl), rw tsub_self, refl, }, cases @trichotomous ℕ (<) _ (list.length u) i with hlt hge, { exfalso, rw hyp_bef at the_case, rw rule_in at *, rw ←list.nth_take hlt at indexS, simp at the_case, change u ++ ([S] ++ v) = list.repeat a i ++ ([S] ++ list.repeat c i) at the_case, rw list.append_assoc at indexS, rw the_case at indexS, rw list.take_append_of_le_length (le_of_eq (list.length_repeat a i).symm) at indexS, rw list.take_repeat at indexS, rw min_self at indexS, rw ←list.length_repeat a i at hlt, have please : (list.repeat a i).nth_le u.length hlt = S, { rw list.nth_le_nth hlt at indexS, injection indexS, }, rw list.nth_le_repeat a hlt at please, injection please, }, cases hge.symm with hgt heq, { exfalso, rw list.append_assoc at the_case, rw hyp_bef at the_case, rw rule_in at *, change u ++ [S] ++ v = list.repeat a i ++ S :: list.repeat c i at the_case, rw the_case at indexS, have rightend : u.length < (list.repeat a i ++ [S] ++ list.repeat c i).length, { have thelength := congr_arg list.length the_case, rw list.append_assoc at thelength, rw list.length_append at thelength, rw list.append_assoc, change u.length < (list.repeat a i ++ S :: list.repeat c i).length, rw ←thelength, rw list.length_append, rw list.length_singleton, rw ←add_assoc, apply lt_of_lt_of_le, { exact lt_add_one u.length, }, exact le_self_add, }, change (list.repeat a i ++ ([S] ++ list.repeat c i)).nth u.length = some S at indexS, rw ←list.append_assoc at indexS, rw list.nth_le_nth rightend at indexS, injection indexS with continue, have mala : (list.repeat a i ++ [S]).length ≤ u.length, { rw list.length_append, rw list.length_singleton, rw list.length_repeat a i, rw ←nat.succ_le_iff at hgt, apply hgt, }, rw list.nth_le_append_right mala at continue, finish, }, rw list.append_assoc at the_case, rw hyp_bef at the_case, rw list.append_assoc at the_case, apply list.append_inj_left the_case, rw heq, rw list.length_repeat a i, }, have v_must : v = list.repeat c i, { rw list.append_assoc at the_case, rw hyp_bef at the_case, rw list.append_assoc at the_case, rw u_must at the_case, rw list.append_right_inj (list.repeat a i) at the_case, rw rule_in at the_case, change [S] ++ v = [S] ++ list.repeat c i at the_case, rw list.append_right_inj [S] at the_case, exact the_case, }, rw hyp_aft, rw u_must, rw v_must, rw rule_in, simp, }, cases rule_in, any_goals { try { cases rule_in }, exfalso, rw rule_in at hyp_bef, simp at hyp_bef, cases case₁ with i the_case, rw the_case at hyp_bef, have contra := congr_arg (λ lis, R ∈ lis) hyp_bef, rw ←R at contra, simp at contra, cases contra, { rw list.mem_repeat at contra, have triv : R ≠ a, { apply symbol.no_confusion, }, exact triv contra.right, }, cases contra, { injection contra with contr, injection contr with cont, simp at cont, exact cont, }, { rw list.mem_repeat at contra, have triv : R ≠ c, { apply symbol.no_confusion, }, exact triv contra.right, }, }, exfalso, exact (list.mem_nil_iff rule).1 rule_in, }, cases caseᵣ with case₂ case₃, { -- the case `list.repeat a i ++ list.repeat b j ++ [R] ++ list.repeat c (i + j)` matches 3rd and 4th rule cases rule_in, any_goals { try { cases rule_in }, exfalso, rw rule_in at hyp_bef, simp at hyp_bef, cases case₂ with i foo, cases foo with j y_eq, rw y_eq at hyp_bef, have contra := congr_arg (λ lis, S ∈ lis) hyp_bef, rw ←S at contra, simp at contra, cases contra, { rw list.mem_repeat at contra, have triv : S ≠ a, { apply symbol.no_confusion, }, exact triv contra.right, }, cases contra, { rw list.mem_repeat at contra, have triv : S ≠ b, { apply symbol.no_confusion, }, exact triv contra.right, }, cases contra, { injection contra with contr, injection contr with cont, simp at cont, exact cont, }, { rw list.mem_repeat at contra, have triv : S ≠ c, { apply symbol.no_confusion, }, exact triv contra.right, }, }, cases rule_in, any_goals { try { cases rule_in }, rw rule_in at *, simp at *, cases case₂ with i foo, cases foo with j y_form, rw y_form at hyp_bef, have indexR: (u ++ [R] ++ v).nth u.length = some R, { rw list.append_assoc, rw list.nth_append_right (le_of_eq rfl), rw tsub_self, refl, }, have u_eq : u = list.repeat a i ++ list.repeat b j, { cases @trichotomous ℕ (<) _ u.length (i + j) with hlt rest, { exfalso, rw ←list.nth_take hlt at indexR, have h_len : u.length < (list.repeat a i ++ list.repeat b j).length, { rw list.length_append, rw list.length_repeat, rw list.length_repeat, exact hlt, }, have propos : (list.repeat a i ++ list.repeat b j).nth_le u.length h_len = R, { change list.repeat a i ++ (list.repeat b j ++ R :: list.repeat c (i + j)) = u ++ ([R] ++ v) at hyp_bef, rw ←list.append_assoc u [R] v at hyp_bef, rw ←hyp_bef at indexR, rw ←list.append_assoc at indexR, have take_beg : list.take (i + j) (list.repeat a i ++ list.repeat b j ++ R :: list.repeat c (i + j)) = (list.repeat a i ++ list.repeat b j), { have len_ij : (list.repeat a i ++ list.repeat b j).length = i + j, { rw list.length_append, rw list.length_repeat, rw list.length_repeat, }, rw list.take_append_of_le_length (le_of_eq len_ij.symm), rw list.take_all_of_le, exact le_of_eq len_ij, }, rw take_beg at indexR, rw list.nth_le_nth h_len at indexR, injection indexR, }, have yes_R : R ∈ (list.repeat a i ++ list.repeat b j), { let positive := list.nth_le_mem (list.repeat a i ++ list.repeat b j) u.length h_len, rw propos at positive, exact positive, }, have not_R : R ∉ (list.repeat a i ++ list.repeat b j), { rw list.mem_append, push_neg, split, { have nidRa : R ≠ a, { apply symbol.no_confusion, }, by_contradiction hyp, rw list.mem_repeat at hyp, exact nidRa hyp.right, }, { have nidRb : R ≠ b, { apply symbol.no_confusion, }, by_contradiction hyp, rw list.mem_repeat at hyp, exact nidRb hyp.right, }, }, exact not_R yes_R, }, cases rest.symm with hgt heq, { exfalso, have yes_Rc : R ∈ list.repeat c (i + j), { change list.repeat a i ++ (list.repeat b j ++ R :: list.repeat c (i + j)) = u ++ ([R] ++ v) at hyp_bef, rw ←list.append_assoc u [R] v at hyp_bef, rw ←hyp_bef at indexR, rw ←list.append_assoc at indexR, change (list.repeat a i ++ list.repeat b j ++ ([R] ++ list.repeat c (i + j))).nth u.length = some R at indexR, rw ←list.append_assoc at indexR, rw list.nth_append_right at indexR, { simp at indexR, have trouble_len : (u.length - (i + (j + 1))) < (list.repeat c (i + j)).length, { rw list.length_repeat, have lengths_sum : u.length ≤ i + j + i + j, { let lengs := congr_arg list.length hyp_bef, repeat { rw list.length_append at lengs, }, rw list.length_repeat at lengs, rw list.length_repeat at lengs, simp at lengs, linarith, }, linarith, }, rw list.nth_le_nth trouble_len at indexR, { finish, }, }, rw list.length_append, rw list.length_append, rw list.length_repeat, rw list.length_repeat, convert hgt, }, have not_Rc : R ∉ list.repeat c (i + j), { by_contradiction hyp, rw list.mem_repeat at hyp, have nidRc : R ≠ c, { apply symbol.no_confusion, }, exact nidRc hyp.right, }, exact not_Rc yes_Rc, }, rw ←list.append_assoc at hyp_bef, have lenlen : (list.repeat a i ++ list.repeat b j).length = u.length, { rw list.length_append, rw list.length_repeat, rw list.length_repeat, exact heq.symm, }, symmetry, exact list.append_inj_left hyp_bef lenlen, }, have v_eq : v = list.repeat c (i + j), { rw u_eq at hyp_bef, rw ←list.append_assoc at hyp_bef, rw list.append_right_inj (list.repeat a i ++ list.repeat b j) at hyp_bef, symmetry, exact list.tail_eq_of_cons_eq hyp_bef, }, rw u_eq at hyp_aft, rw v_eq at hyp_aft, rw hyp_aft, }, { right, left, use i, use j + 1, have bpp : list.repeat b (j + 1) = list.repeat b j ++ [b], { rw list.repeat_add b j 1, refl, }, have cpp : list.repeat c (i + (j + 1)) = [c] ++ list.repeat c (i + j), { rw ←add_assoc, rw add_comm, rw list.repeat_add c 1 (i + j), refl, }, rw bpp, rw cpp, rw list.append_assoc, apply congr_arg (λ lis, list.repeat a i ++ lis), rw list.append_assoc, apply congr_arg (λ lis, list.repeat b j ++ lis), rw list.singleton_append, rw list.singleton_append, }, cases rule_in, { right, right, use i, use j, rw list.append_assoc, }, exfalso, exact (list.mem_nil_iff rule).1 rule_in, }, { -- the remaining case `list.repeat a i ++ list.repeat b j ++ list.repeat c (i + j)` does not match any rule exfalso, rw hyp_bef at case₃, cases case₃ with i foo, cases foo with j the_case, have contra := congr_arg (λ lis, symbol.nonterminal rule.fst ∈ lis) the_case, simp at contra, cases contra, { have neq : symbol.nonterminal rule.fst ≠ a, { apply symbol.no_confusion, }, rw list.mem_repeat at contra, apply neq, exact contra.right, }, cases contra, { have neq : symbol.nonterminal rule.fst ≠ b, { apply symbol.no_confusion, }, rw list.mem_repeat at contra, apply neq, exact contra.right, }, { have neq : symbol.nonterminal rule.fst ≠ c, { apply symbol.no_confusion, }, rw list.mem_repeat at contra, apply neq, exact contra.right, }, }, }, specialize possib (list.map symbol.terminal x) ass, cases possib with imposs rest, { exfalso, cases imposs with i hyp, have contra := congr_arg (λ xs, S ∈ xs) hyp, simp at contra, finish, }, cases rest with imposs' necess, { exfalso, cases imposs' with i rest, cases rest with j hyp, have contra := congr_arg (λ xs, R ∈ xs) hyp, simp at contra, finish, }, cases necess with n foobar, use n, cases foobar with m keyprop, use m, unfold anbmcnm, unfold a b c at keyprop, rw ←list.map_repeat symbol.terminal a_ n at keyprop, rw ←list.map_repeat symbol.terminal b_ m at keyprop, rw ←list.map_repeat symbol.terminal c_ (n + m) at keyprop, rw ←list.map_append at keyprop, rw ←list.map_append at keyprop, ext1 k, have kprop := congr_fun (congr_arg list.nth keyprop) k, rw list.nth_map at kprop, rw list.nth_map at kprop, cases x.nth k, { cases (list.repeat a_ n ++ list.repeat b_ m ++ list.repeat c_ (n + m)).nth k, { refl, }, { exfalso, injection kprop, }, }, { cases (list.repeat a_ n ++ list.repeat b_ m ++ list.repeat c_ (n + m)).nth k, { exfalso, injection kprop, }, { injection kprop, injection h_1, rw h_2, }, }, }, { -- prove `x ∈ CF_language gr_add ← x ∈ language_add` here rintro ⟨n, m, hyp⟩, rw hyp, have epoch_a : ∀ i : ℕ, CF_derives gr_add [S] ((list.repeat a i) ++ [S] ++ (list.repeat c i)), { intro i, induction i with n' ih, { apply CF_deri_self, }, apply CF_deri_of_deri_tran ih, use (S_, [a, S, c]), split_ile, use [list.repeat a n', list.repeat c n'], split, { refl, }, rw [ list.repeat_succ_eq_append_singleton a, list.repeat_succ_eq_singleton_append c, list.append_assoc, list.append_assoc, ←list.append_assoc [S], ←list.append_assoc [a], ←list.append_assoc (list.repeat a n') ], refl, }, have epoch_b : ∀ j : ℕ, CF_derives gr_add [R] ((list.repeat b j) ++ [R] ++ (list.repeat c j)), { intro j, induction j with m' jh, { apply CF_deri_self, }, apply CF_deri_of_deri_tran jh, use (R_, [b, R, c]), split_ile, use [list.repeat b m', list.repeat c m'], split, { refl, }, rw [ list.repeat_succ_eq_append_singleton b, list.repeat_succ_eq_singleton_append c, list.append_assoc, list.append_assoc, ←list.append_assoc [R], ←list.append_assoc [b], ←list.append_assoc (list.repeat b m') ], refl, }, unfold CF_language, rw set.mem_set_of_eq, unfold CF_generates, unfold CF_generates_str, have obtain_sum : CF_derives gr_add [symbol.nonterminal gr_add.initial] ((list.repeat a n) ++ (list.repeat b m) ++ [R] ++ (list.repeat c (n + m))), { have middle_step : CF_derives gr_add ((list.repeat a n) ++ [S] ++ (list.repeat c n)) ((list.repeat a n) ++ [R] ++ (list.repeat c n)), { apply CF_deri_with_prefix_and_postfix, apply CF_deri_of_tran, use (S_, [R]), split_ile, use [[], []], split; refl, }, apply CF_deri_of_deri_deri, { specialize epoch_a n, finish, }, apply CF_deri_of_deri_deri, { finish, }, change CF_derives gr_add (list.repeat a n ++ ([R] ++ list.repeat c n)) (list.repeat a n ++ list.repeat b m ++ [R] ++ list.repeat c (n + m)), rw ←list.append_assoc, have cnm : list.repeat c (n + m) = list.repeat c m ++ list.repeat c n, { rw add_comm, apply list.repeat_add, }, rw cnm, have rebra : (list.repeat a n ++ list.repeat b m ++ [R] ++ (list.repeat c m ++ list.repeat c n)) = (list.repeat a n ++ (list.repeat b m ++ [R] ++ list.repeat c m) ++ list.repeat c n), { simp only [list.append_assoc], }, rw rebra, apply CF_deri_with_prefix_and_postfix, exact epoch_b m, }, apply CF_deri_of_deri_tran obtain_sum, use (R_, []), split_ile, use (list.repeat a n ++ list.repeat b m), use list.repeat c (n + m), split, { refl, }, unfold anbmcnm, rw list.map_append_append, rw list.append_nil, repeat { rw list.map_repeat, }, refl, }, end
f619b329b110662e929c77842a3048a595311737
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/linarith/datatypes.lean
52bc606a08fb86300508a7128e557fffd3c9f456
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,798
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.lemmas import tactic.ring /-! # Datatypes for `linarith` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. This file also contains a few convenient auxiliary functions. -/ declare_trace linarith open native namespace linarith /-- A shorthand for tracing when the `trace.linarith` option is set to true. -/ meta def linarith_trace {α} [has_to_tactic_format α] (s : α) : tactic unit := tactic.when_tracing `linarith (tactic.trace s) /-- A shorthand for tracing the types of a list of proof terms when the `trace.linarith` option is set to true. -/ meta def linarith_trace_proofs (s : string := "") (l : list expr) : tactic unit := tactic.when_tracing `linarith $ do tactic.trace s, l.mmap tactic.infer_type >>= tactic.trace /-! ### Linear expressions -/ /-- A linear expression is a list of pairs of variable indices and coefficients, representing the sum of the products of each coefficient with its corresponding variable. Some functions on `linexp` assume that `n : ℕ` occurs at most once as the first element of a pair, and that the list is sorted in decreasing order of the first argument. This is not enforced by the type but the operations here preserve it. -/ @[reducible] def linexp : Type := list (ℕ × ℤ) namespace linexp /-- Add two `linexp`s together componentwise. Preserves sorting and uniqueness of the first argument. -/ meta def add : linexp → linexp → linexp | [] a := a | a [] := a | (a@(n1,z1)::t1) (b@(n2,z2)::t2) := if n1 < n2 then b::add (a::t1) t2 else if n2 < n1 then a::add t1 (b::t2) else let sum := z1 + z2 in if sum = 0 then add t1 t2 else (n1, sum)::add t1 t2 /-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/ def scale (c : ℤ) (l : linexp) : linexp := if c = 0 then [] else if c = 1 then l else l.map $ λ ⟨n, z⟩, (n, z*c) /-- `l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise. This function assumes that `l` is sorted in decreasing order of the first argument, that is, it will return `none` as soon as it finds a key smaller than `n`. -/ def get (n : ℕ) : linexp → option ℤ | [] := none | ((a, b)::t) := if a < n then none else if a = n then some b else get t /-- `l.contains n` is true iff `n` is the first element of a pair in `l`. -/ def contains (n : ℕ) : linexp → bool := option.is_some ∘ get n /-- `l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise. -/ def zfind (n : ℕ) (l : linexp) : ℤ := match l.get n with | none := 0 | some v := v end /-- `l.vars` returns the list of variables that occur in `l`. -/ def vars (l : linexp) : list ℕ := l.map prod.fst /-- Defines a lex ordering on `linexp`. This function is performance critical. -/ def cmp : linexp → linexp → ordering | [] [] := ordering.eq | [] _ := ordering.lt | _ [] := ordering.gt | ((n1,z1)::t1) ((n2,z2)::t2) := if n1 < n2 then ordering.lt else if n2 < n1 then ordering.gt else if z1 < z2 then ordering.lt else if z2 < z1 then ordering.gt else cmp t1 t2 end linexp /-! ### Inequalities -/ /-- The three-element type `ineq` is used to represent the strength of a comparison between terms. -/ @[derive decidable_eq, derive inhabited] inductive ineq : Type | eq | le | lt namespace ineq /-- `max R1 R2` computes the strength of the sum of two inequalities. If `t1 R1 0` and `t2 R2 0`, then `t1 + t2 (max R1 R2) 0`. -/ def max : ineq → ineq → ineq | lt a := lt | a lt := lt | le a := le | a le := le | eq eq := eq /-- `ineq` is ordered `eq < le < lt`. -/ def cmp : ineq → ineq → ordering | eq eq := ordering.eq | eq _ := ordering.lt | le le := ordering.eq | le lt := ordering.lt | lt lt := ordering.eq | _ _ := ordering.gt /-- Prints an `ineq` as the corresponding infix symbol. -/ def to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" /-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/ meta def to_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq instance : has_to_string ineq := ⟨ineq.to_string⟩ meta instance : has_to_format ineq := ⟨λ i, ineq.to_string i⟩ end ineq /-! ### Comparisons with 0 -/ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.sum (λ ⟨k, v⟩, v * Var[k])`. str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive inhabited] structure comp : Type := (str : ineq) (coeffs : linexp) /-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/ def comp.vars : comp → list ℕ := linexp.vars ∘ comp.coeffs /-- `comp.coeff_of c a` projects the coefficient of variable `a` out of `c`. -/ def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a /-- `comp.scale c n` scales the coefficients of `c` by `n`. -/ def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.scale n } /-- `comp.add c1 c2` adds the expressions represented by `c1` and `c2`. The coefficient of variable `a` in `c1.add c2` is the sum of the coefficients of `a` in `c1` and `c2`. -/ meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ /-- `comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/ meta def comp.cmp : comp → comp → ordering | ⟨str1, coeffs1⟩ ⟨str2, coeffs2⟩ := match str1.cmp str2 with | ordering.lt := ordering.lt | ordering.gt := ordering.gt | ordering.eq := coeffs1.cmp coeffs2 end /-- A `comp` represents a contradiction if its expression has no coefficients and its strength is <, that is, it represents the fact `0 < 0`. -/ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs ++ to_string p.str ++ "0"⟩ /-! ### Parsing into linear form -/ /-! ### Control -/ /-- A preprocessor transforms a proof of a proposition into a proof of a different propositon. The return type is `list expr`, since some preprocessing steps may create multiple new hypotheses, and some may remove a hypothesis from the list. A "no-op" preprocessor should return its input as a singleton list. -/ meta structure preprocessor : Type := (name : string) (transform : expr → tactic (list expr)) /-- Some preprocessors need to examine the full list of hypotheses instead of working item by item. As with `preprocessor`, the input to a `global_preprocessor` is replaced by, not added to, its output. -/ meta structure global_preprocessor : Type := (name : string) (transform : list expr → tactic (list expr)) /-- Some preprocessors perform branching case splits. A `branch` is used to track one of these case splits. The first component, an `expr`, is the goal corresponding to this branch of the split, given as a metavariable. The `list expr` component is the list of hypotheses for `linarith` in this branch. Every `expr` in this list should be type correct in the context of the associated goal. -/ meta def branch : Type := expr × list expr /-- Some preprocessors perform branching case splits. A `global_branching_preprocessor` produces a list of branches to run. Each branch is independent, so hypotheses that appear in multiple branches should be duplicated. The preprocessor is responsible for making sure that each branch contains the correct goal metavariable. -/ meta structure global_branching_preprocessor : Type := (name : string) (transform : list expr → tactic (list branch)) /-- A `preprocessor` lifts to a `global_preprocessor` by folding it over the input list. -/ meta def preprocessor.globalize (pp : preprocessor) : global_preprocessor := { name := pp.name, transform := list.mfoldl (λ ret e, do l' ← pp.transform e, return (l' ++ ret)) [] } /-- A `global_preprocessor` lifts to a `global_branching_preprocessor` by producing only one branch. -/ meta def global_preprocessor.branching (pp : global_preprocessor) : global_branching_preprocessor := { name := pp.name, transform := λ l, do g ← tactic.get_goal, singleton <$> prod.mk g <$> pp.transform l } /-- `process pp l` runs `pp.transform` on `l` and returns the result, tracing the result if `trace.linarith` is on. -/ meta def global_branching_preprocessor.process (pp : global_branching_preprocessor) (l : list expr) : tactic (list branch) := do l ← pp.transform l, when (l.length > 1) $ linarith_trace format!"Preprocessing: {pp.name} has branched, with branches:", l.mmap' $ λ l, tactic.set_goals [l.1] >> linarith_trace_proofs (to_string format!"Preprocessing: {pp.name}") l.2, return l meta instance preprocessor_to_gb_preprocessor : has_coe preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching ∘ preprocessor.globalize⟩ meta instance global_preprocessor_to_gb_preprocessor : has_coe global_preprocessor global_branching_preprocessor := ⟨global_preprocessor.branching⟩ /-- A `certificate_oracle` is a function `produce_certificate : list comp → ℕ → tactic (rb_map ℕ ℕ)`. `produce_certificate hyps max_var` tries to derive a contradiction from the comparisons in `hyps` by eliminating all variables ≤ `max_var`. If successful, it returns a map `coeff : ℕ → ℕ` as a certificate. This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. The default `certificate_oracle` used by `linarith` is `linarith.fourier_motzkin.produce_certificate`. -/ meta def certificate_oracle : Type := list comp → ℕ → tactic (rb_map ℕ ℕ) /-- A configuration object for `linarith`. -/ meta structure linarith_config : Type := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected _ restrict_type . tactic.apply_instance) (exfalso : bool := tt) (transparency : tactic.transparency := reducible) (split_hypotheses : bool := tt) (split_ne : bool := ff) (preprocessors : option (list global_branching_preprocessor) := none) (oracle : option certificate_oracle := none) /-- `cfg.update_reducibility reduce_semi` will change the transparency setting of `cfg` to `semireducible` if `reduce_semi` is true. In this case, it also sets the discharger to `ring!`, since this is typically needed when using stronger unification. -/ meta def linarith_config.update_reducibility (cfg : linarith_config) (reduce_semi : bool) : linarith_config := if reduce_semi then { cfg with transparency := semireducible, discharger := `[ring!] } else cfg /-! ### Auxiliary functions These functions are used by multiple modules, so we put them here for accessibility. -/ open tactic /-- `get_rel_sides e` returns the left and right hand sides of `e` if `e` is a comparison, and fails otherwise. This function is more naturally in the `option` monad, but it is convenient to put in `tactic` for compositionality. -/ meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := tactic.failed /-- `parse_into_comp_and_expr e` checks if `e` is of the form `t < 0`, `t ≤ 0`, or `t = 0`. If it is, it returns the comparison along with `t`. -/ meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none /-- `mk_single_comp_zero_pf c h` assumes that `h` is a proof of `t R 0`. It produces a pair `(R', h')`, where `h'` is a proof of `c*t R' 0`. Typically `R` and `R'` will be the same, except when `c = 0`, in which case `R'` is `=`. If `c = 1`, `h'` is the same as `h` -- specifically, it does *not* change the type to `1*t R 0`. -/ meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h >>= instantiate_mvars, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (ineq.eq, e') else if c = 1 then return (iq, h) else do tp ← (prod.snd <$> (infer_type h >>= instantiate_mvars >>= get_rel_sides)) >>= infer_type, c ← tp.of_nat c, cpos ← to_expr ``(%%c > 0), (_, ex) ← solve_aux cpos `[norm_num, done], e' ← mk_app iq.to_const_mul_nm [h, ex], return (iq, e') end linarith
77797a2ec3e13b945afb4fb3aa16f28ce3ab207a
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/topprover/04.lean
a5b42543ec9c71d3e51176ba55eacf159164e675
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
657
lean
lemma at_most_two : ∀ (f : bool → bool) b x y z, x = f b → y = f x → z = f y → z = x := begin intros f b x y z h1 h2 h3, induction b, induction x, rw ←h1 at h2, rw h2 at h3, simp [h3], rw ←h1, rw h1, induction y, assumption, simp * at *, rw ←h2, induction x, induction y, rw ←h2 at h3, assumption, rw h3, rw ←h1, rw ←h1 at h2, rw [h2, ←h1] at h3, assumption, end example : ∀ (f : bool → bool) b, f (f (f b)) = f b := by intros; apply at_most_two; refl
a5e6071c6a8db7e4e09211a662521e0da8e0b1bd
fe25de614feb5587799621c41487aaee0d083b08
/tests/lean/run/PPTopDownAnalyze.lean
5ce0fc80c0f979b13be733b3e92a3302d6d402c3
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,773
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Lean import Std open Lean Lean.Meta Lean.Elab Lean.Elab.Term Lean.Elab.Command open Lean.PrettyPrinter def checkDelab (e : Expr) (tgt? : Option Syntax) (name? : Option Name := none) : TermElabM Unit := do if e.hasMVar then throwError "[checkDelab] original term has mvars, {e}" let stx ← delab (← getCurrNamespace) (← getOpenDecls) e match tgt? with | some tgt => if toString (← PrettyPrinter.ppTerm stx) != toString (← PrettyPrinter.ppTerm tgt?.get!) then throwError "[checkDelab] missed target\n{← PrettyPrinter.ppTerm stx}\n!=\n{← PrettyPrinter.ppTerm tgt}\n\nExpr: {e}\nType: {← inferType e}" | _ => pure () let e' ← try let e' ← elabTerm stx (some (← inferType e)) synthesizeSyntheticMVarsNoPostponing let e' ← instantiateMVars e' -- let ⟨e', _⟩ ← levelMVarToParam e' throwErrorIfErrors e' catch ex => throwError "[checkDelab] failed to re-elaborate,\n{stx}\n{← ex.toMessageData.toString}" withTheReader Core.Context (fun ctx => { ctx with options := ctx.options.setBool `pp.all true }) do if not (← isDefEq e e') then println! "[checkDelab] {← inferType e} {← inferType e'}" throwError "[checkDelab] roundtrip not structurally equal\n\nOriginal: {e}\n\nSyntax: {stx}\n\nNew: {e'}" let e' ← instantiateMVars e' if e'.hasMVar then throwError "[checkDelab] elaborated term still has mvars\n\nSyntax: {stx}\n\nExpression: {e'}" syntax (name := testDelabTD) "#testDelab " term " expecting " term : command @[commandElab testDelabTD] def elabTestDelabTD : CommandElab | `(#testDelab $stx:term expecting $tgt:term) => liftTermElabM `delabTD do let e ← elabTerm stx none let ⟨e, _⟩ ← levelMVarToParam e let e ← instantiateMVars e checkDelab e (some tgt) | _ => throwUnsupportedSyntax syntax (name := testDelabTDN) "#testDelabN " ident : command @[commandElab testDelabTDN] def elabTestDelabTDN : CommandElab | `(#testDelabN $name:ident) => liftTermElabM `delabTD do let name := name.getId let [name] ← resolveGlobalConst (mkIdent name) | throwError "cannot resolve name" let some cInfo ← (← getEnv).find? name | throwError "no decl for name" let some value ← pure cInfo.value? | throwError "decl has no value" modify fun s => { s with levelNames := cInfo.levelParams } withTheReader Core.Context (fun ctx => { ctx with currNamespace := name.getPrefix, openDecls := [] }) do checkDelab value none | _ => throwUnsupportedSyntax ------------------------------------------------- ------------------------------------------------- ------------------------------------------------- universe u v set_option pp.analyze true set_option pp.analyze.checkInstances true set_option pp.proofs true #testDelab @Nat.brecOn (fun x => Nat) 0 (fun x ih => x) expecting Nat.brecOn (motive := fun x => Nat) 0 fun x ih => x #testDelab @Nat.brecOn (fun x => Nat → Nat) 0 (fun x ih => fun y => y + x) expecting Nat.brecOn (motive := fun x => Nat → Nat) 0 fun x ih y => y + x #testDelab @Nat.brecOn (fun x => Nat → Nat) 0 (fun x ih => fun y => y + x) 0 expecting Nat.brecOn (motive := fun x => Nat → Nat) 0 (fun x ih y => y + x) 0 #testDelab let xs := #[]; xs.push (5 : Nat) expecting let xs : Array Nat := #[]; Array.push xs 5 #testDelab let x := Nat.zero; x + Nat.zero expecting let x := Nat.zero; x + Nat.zero def fHole (α : Type) (x : α) : α := x #testDelab fHole Nat Nat.zero expecting fHole _ Nat.zero def fPoly {α : Type u} (x : α) : α := x #testDelab fPoly Nat.zero expecting fPoly Nat.zero #testDelab fPoly (id Nat.zero) expecting fPoly (id Nat.zero) def fPoly2 {α : Type u} {β : Type v} (x : α) : α := x #testDelab @fPoly2 _ (Type 3) Nat.zero expecting fPoly2 (β := Type 3) Nat.zero def fPolyInst {α : Type u} [Add α] : α → α → α := Add.add #testDelab @fPolyInst Nat ⟨Nat.add⟩ expecting fPolyInst def fPolyNotInst {α : Type u} (inst : Add α) : α → α → α := Add.add #testDelab @fPolyNotInst Nat ⟨Nat.add⟩ expecting fPolyNotInst { add := Nat.add } #testDelab (fun (x : Nat) => x) Nat.zero expecting (fun (x : Nat) => x) Nat.zero #testDelab (fun (α : Type) (x : α) => x) Nat Nat.zero expecting (fun (α : Type) (x : α) => x) _ Nat.zero #testDelab (fun {α : Type} (x : α) => x) Nat.zero expecting (fun {α : Type} (x : α) => x) Nat.zero #testDelab ((@Add.mk Nat Nat.add).1 : Nat → Nat → Nat) expecting Add.add class Foo (α : Type v) where foo : α instance : Foo Bool := ⟨true⟩ #testDelab @Foo.foo Bool ⟨true⟩ expecting Foo.foo #testDelab @Foo.foo Bool ⟨false⟩ expecting Foo.foo (self := { foo := false }) axiom wild {α : Type u} {f : α → Type v} {x : α} [_inst_1 : Foo (f x)] : Nat abbrev nat2bool : Nat → Type := fun _ => Bool #testDelab @wild Nat nat2bool Nat.zero ⟨false⟩ expecting wild (f := nat2bool) (x := Nat.zero) (_inst_1 := { foo := false }) #testDelab @wild Nat (fun (n : Nat) => Bool) Nat.zero ⟨false⟩ expecting wild (f := fun n => Bool) (x := Nat.zero) (_inst_1 := { foo := false }) def takesFooUnnamed {Impl : Type} (Expl : Type) [Foo Nat] (x : Impl) (y : Expl) : Impl × Expl := (x, y) #testDelab @takesFooUnnamed _ Nat (Foo.mk 7) false 5 expecting @takesFooUnnamed _ _ { foo := 7 } false 5 #testDelab (fun {α : Type u} (x : α) => x : ∀ {α : Type u}, α → α) expecting fun {α} x => x #testDelab (fun {α : Type} (x : α) => x) Nat.zero expecting (fun {α : Type} (x : α) => x) Nat.zero #testDelab (fun {α : Type} [Add α] (x : α) => x + x) (0 : Nat) expecting (fun {α : Type} [Add α] (x : α) => x + x) 0 #testDelab (fun {α : Type} [Add α] (x : α) => x + x) Nat.zero expecting (fun {α : Type} [Add α] (x : α) => x + x) Nat.zero #testDelab id id id id Nat.zero expecting id id id id Nat.zero def zzz : Unit := () def Z1.zzz : Unit := () def Z1.Z2.zzz : Unit := () namespace Z1.Z2 #testDelab _root_.zzz expecting _root_.zzz #testDelab Z1.zzz expecting Z1.zzz #testDelab zzz expecting zzz end Z1.Z2 #testDelab fun {σ : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (f : σ → α × σ) (s : σ) => pure (f := m) (f s) expecting fun {σ} {m} [Monad m] {α} f s => pure (f s) set_option pp.analyze.trustSubst false in #testDelab (fun (x y z : Nat) (hxy : x = y) (hyz : x = z) => hxy ▸ hyz : ∀ (x y z : Nat), x = y → x = z → y = z) expecting fun x y z hxy hyz => Eq.ndrec (a := x) (motive := fun x => x = z) hyz hxy set_option pp.analyze.trustSubst true in #testDelab (fun (x y z : Nat) (hxy : x = y) (hyz : x = z) => hxy ▸ hyz : ∀ (x y z : Nat), x = y → x = z → y = z) expecting fun x y z hxy hyz => hxy ▸ hyz set_option pp.analyze.trustId true in #testDelab Sigma.mk (β := fun α => α) Bool true expecting { fst := _, snd := true } set_option pp.analyze.trustId false in #testDelab Sigma.mk (β := fun α => α) Bool true expecting Sigma.mk (β := fun α => α) _ true #testDelab let xs := #[true]; xs expecting let xs := #[true]; xs def fooReadGetModify : ReaderT Unit (StateT Unit IO) Unit := do let _ ← read let _ ← get modify fun s => s #testDelab (do discard read pure () : ReaderT Bool IO Unit) expecting do discard read pure () #testDelab ((do let ctx ← read let s ← get modify fun s => s : ReaderT Bool (StateT Bool IO) Unit)) expecting do let _ ← read let _ ← get modify fun s => s set_option pp.analyze.typeAscriptions true in #testDelab (fun (x : Unit) => @id (ReaderT Bool IO Bool) (do read : ReaderT Bool IO Bool)) () expecting (fun (x : Unit) => (id read : ReaderT Bool IO Bool)) () set_option pp.analyze.typeAscriptions false in #testDelab (fun (x : Unit) => @id (ReaderT Bool IO Bool) (do read : ReaderT Bool IO Bool)) () expecting (fun (x : Unit) => id read) () instance : CoeFun Bool (fun b => Bool → Bool) := { coe := fun b x => b && x } set_option pp.analyze.trustCoe false in #testDelab coeFun true false expecting coeFun (γ := fun b => Bool → Bool) true false set_option pp.analyze.trustCoe true in #testDelab coeFun true false expecting true false #testDelab fun (xs : List Nat) => xs ≠ xs expecting fun xs => xs ≠ xs structure S1 where x : Unit structure S2 where x : Unit #testDelab { x := () : S1 } expecting { x := () } #testDelab (fun (u : Unit) => { x := () : S2 }) () expecting (fun (u : Unit) => { x := () : S2 }) () #testDelab Eq.refl True expecting Eq.refl _ #testDelab (fun (u : Unit) => Eq.refl True) () expecting (fun (u : Unit) => Eq.refl True) () inductive NeedsAnalysis {α : Type} : Prop | mk : NeedsAnalysis set_option pp.proofs false in #testDelab @NeedsAnalysis.mk Unit expecting (_ : NeedsAnalysis (α := Unit)) set_option pp.proofs false in set_option pp.proofs.withType false in #testDelab @NeedsAnalysis.mk Unit expecting _ #testDelab ∀ (α : Type u) (vals vals_1 : List α), { data := vals : Array α } = { data := vals_1 : Array α } expecting ∀ (α : Type u) (vals vals_1 : List α), { data := vals : Array α } = { data := vals_1 } #testDelab (do let ctxCore ← readThe Core.Context; ctxCore.currNamespace : MetaM Name) expecting do let ctxCore ← readThe Core.Context pure ctxCore.currNamespace def stackMkInjEqSnippet := fun {α : Type} (xs : Array α) => Eq.ndrec (motive := fun _ => (Std.Stack.mk xs = Std.Stack.mk xs)) (Eq.refl (Std.Stack.mk xs)) (rfl : xs = xs) #testDelabN stackMkInjEqSnippet def typeAs (α : Type u) (a : α) := () def natIdNat := typeAs Nat (do let x ← pure 1; return x + x) #testDelabN natIdNat #testDelabN Nat.brecOn #testDelabN Nat.below #testDelabN Nat.mod_lt #testDelabN Array.qsort #testDelabN List.partition #testDelabN List.partitionAux #testDelabN StateT.modifyGet #testDelabN Nat.gcd_one_left #testDelabN List.hasDecidableLt #testDelabN Lean.Xml.parse #testDelabN Add.noConfusionType #testDelabN List.filterMapM.loop #testDelabN instMonadReaderOf #testDelabN instInhabitedPUnit #testDelabN Lean.Syntax.getOptionalIdent? #testDelabN Lean.Meta.ppExpr #testDelabN Eq.mprProp #testDelabN MonadLift.noConfusion #testDelabN MonadLift.noConfusionType #testDelabN MonadExcept.noConfusion #testDelabN MonadFinally.noConfusion #testDelabN Lean.Elab.InfoTree.goalsAt?.match_1 #testDelabN Std.ShareCommon.ObjectMap.find? #testDelabN Std.ShareCommon.ObjectMap.insert #testDelabN Std.Stack.mk.injEq #testDelabN Lean.PrefixTree.empty #testDelabN Std.PersistentHashMap.getCollisionNodeSize.match_1 #testDelabN Std.HashMap.size.match_1 -- TODO: for some reason this *only* works when trusting subst set_option pp.analyze.trustSubst true in #testDelabN Lean.Simp.and_false -- TODO: this one prints out a structure instance with keyword field `end` set_option pp.structureInstances false in #testDelabN Lean.Server.FileWorker.handlePlainTermGoal -- TODO: this one desugars to a `doLet` in an assignment set_option pp.notation false in #testDelabN Lean.Server.FileWorker.handlePlainGoal -- TODO: this error occurs because we use a term's type to determine `blockImplicit` (@), -- whereas we should actually use the expected type based on the function being applied. -- #testDelabN HEq.subst -- TODO: this error occurs because it cannot solve the universe constraints -- (unclear if it is too few or too many annotations) -- #testDelabN ExceptT.seqRight_eq -- TODO: this error occurs because a function has explicit binders while its type has -- implicit binders. This may be an issue in the elaborator. -- #testDelabN Char.eqOfVeq
687aa135ca36e9b36095c84d2319120745050ab8
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/free_module.lean
21c0e3e0861a6a62a3ef1229d5eabd59dbcbf4e2
[ "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
17,782
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 linear_algebra.basis import linear_algebra.finsupp_vector_space import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results - `submodule.induction_on_rank`: if `M` is free and finitely generated, if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `M` is free and finitely generated and `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators section comm_ring universes u v variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal lemma eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, fin_cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, exact (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end open submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i).comp b.repr) bot_le) _ ⟨x, hx, rfl⟩ end -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } end comm_ring section integral_domain variables {ι : Type*} {R : Type*} [integral_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, nat.le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end /-- In an `n`-dimensional space, the rank is at most `m`. -/ lemma basis.card_le_card_of_linear_independent_aux {R : Type*} [integral_domain R] (n : ℕ) {m : ℕ} (v : fin m → fin n → R) : linear_independent R v → m ≤ n := begin revert m, refine nat.rec_on n _ _, { intros m v hv, cases m, { refl }, exfalso, have : v 0 = 0, { ext i, exact fin_zero_elim i }, have := hv.ne_zero 0, contradiction }, intros n ih m v hv, cases m, { exact nat.zero_le _ }, -- Induction: try deleting a dimension and a vector. suffices : ∃ (v' : fin m → fin n → R), linear_independent R v', { obtain ⟨v', hv'⟩ := this, exact nat.succ_le_succ (ih v' hv') }, -- Either the `0`th dimension is irrelevant... by_cases this : linear_independent R (λ i, v i ∘ fin.succ), { exact ⟨_, this.comp fin.succ (fin.succ_injective _)⟩ }, -- ... or we can write (x, 0, 0, ...) = ∑ i, c i • v i where c i ≠ 0 for some i. simp only [fintype.linear_independent_iff, not_forall, not_imp] at this, obtain ⟨c, hc, i, hi⟩ := this, have hc : ∀ (j : fin n), ∑ (i : fin m.succ), c i * v i j.succ = 0, { intro j, convert congr_fun hc j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, set x := ∑ i', c i' * v i' 0 with x_eq, -- We'll show each equation of the form (y, 0, 0, ...) = ∑ i', c' i' • v i' must have c' i ≠ 0. use λ i' j', v (i.succ_above i') j'.succ, rw fintype.linear_independent_iff at ⊢ hv, -- Assume that ∑ i, c' i • v i = (y, 0, 0, ...). intros c' hc' i', set y := ∑ i', c' i' * v (i.succ_above i') 0 with y_eq, have hc' : ∀ (j : fin n), (∑ (i' : fin m), c' i' * v (i.succ_above i') j.succ) = 0, { intro j, convert congr_fun hc' j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, -- Combine these equations to get a linear dependence on the full space. have : ∑ i', (y * c i' - x * (@fin.insert_nth _ (λ _, R) i 0 c') i') • v i' = 0, { simp only [sub_smul, mul_smul, finset.sum_sub_distrib, ← finset.smul_sum], ext j, rw [pi.zero_apply, @pi.sub_apply (fin n.succ) (λ _, R) _ _ _ _], simp only [finset.sum_apply, pi.smul_apply, smul_eq_mul, sub_eq_zero], symmetry, rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add, mul_comm], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { simp }, { intro j, rw [hc', hc, zero_mul, mul_zero] } }, have hyc := hv _ this i, simp only [fin.insert_nth_apply_same, mul_zero, sub_zero, mul_eq_zero] at hyc, -- Therefore, either `c i = 0` (which contradicts the assumption on `i`) or `y = 0`. have hy := hyc.resolve_right hi, -- If `y = 0`, then we can extend `c'` to a linear dependence on the full space, -- which implies `c'` is trivial. convert hv (@fin.insert_nth _ (λ _, R) i 0 c') _ (i.succ_above i'), { rw fin.insert_nth_apply_succ_above }, ext j, -- After a bit of calculation, we find that `∑ i, c' i • v i = (y, 0, 0, ...) = 0` as promised. rw [@finset.sum_apply (fin n.succ) (λ _, R) _ _ _, pi.zero_apply], simp only [pi.smul_apply, smul_eq_mul], rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { rw [← y_eq, hy] }, { exact hc' }, end lemma basis.card_le_card_of_linear_independent {R : Type*} [integral_domain R] [module R M] {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) : fintype.card ι' ≤ fintype.card ι := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq ι', let e := fintype.equiv_fin ι, let e' := fintype.equiv_fin ι', let b := b.reindex e, have hv := (linear_independent_equiv e'.symm).mpr hv, have hv := hv.map' _ b.equiv_fun.ker, exact basis.card_le_card_of_linear_independent_aux (fintype.card ι) _ hv, end /-- If we have two bases on the same space, their indices are in bijection. -/ noncomputable def basis.index_equiv {R ι ι' : Type*} [integral_domain R] [module R M] [fintype ι] [fintype ι'] (b : basis ι R M) (b' : basis ι' R M) : ι ≃ ι' := (fintype.card_eq.mp (le_antisymm (b'.card_le_card_of_linear_independent b.linear_independent) (b.card_le_card_of_linear_independent b'.linear_independent))).some /-- If `N` is a submodule in a free, finitely generated module, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank [fintype ι] (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (N : submodule R M) : P N := submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli, by simpa using b.card_le_card_of_linear_independent hli) open submodule.is_principal end integral_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [integral_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open_locale matrix /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis (fin n) R N := begin haveI := classical.dec_eq M, refine N.induction_on_rank b _ _, intros N ih, -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (submodule.range_map_nonempty N), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, use ϕ, intros ψ hψ, exact P_max (N.map ψ) ⟨_, rfl⟩ hψ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `N.map ϕ` is a `R`-submodule of the PID `R`, it is principal and generated by some `a`. have a_mem : generator (N.map ϕ) ∈ N.map ϕ := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥` by_cases N_bot : N = ⊥, { rw N_bot, refine ⟨0, basis.empty _ _⟩, rintro ⟨i, ⟨⟩⟩ }, by_cases a_zero : generator (N.map ϕ) = 0, { have := eq_bot_of_generator_maximal_map_eq_zero b ϕ_max a_zero, contradiction }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. let y := a_mem.some, obtain ⟨y_mem, ϕy_eq⟩ := a_mem.some_spec, have ϕy_ne_zero := λ h, a_zero (ϕy_eq.symm.trans h), -- If `N'` is `ker (ϕ : N → R)`, it is smaller than `N` so by the induction hypothesis, -- it has a basis `bN'`. have N'_le_ker : (ϕ.ker ⊓ N) ≤ ϕ.ker := inf_le_left, have N'_le_N : (ϕ.ker ⊓ N) ≤ N := inf_le_right, -- Note that `y` is orthogonal to `N'`. have y_ortho_N' : ∀ (c : R) (z : M), z ∈ ϕ.ker ⊓ N → c • y + z = 0 → c = 0, { intros c x hx hc, have hx' : x ∈ ϕ.ker := (inf_le_left : _ ⊓ N ≤ _) hx, rw linear_map.mem_ker at hx', simpa [ϕy_ne_zero, hx'] using congr_arg ϕ hc }, obtain ⟨nN', bN'⟩ := ih (ϕ.ker ⊓ N) N'_le_N y y_mem y_ortho_N', use nN'.succ, -- Extend `bN'` with `y`, we'll show it's linear independent and spans `N`. let bN'y : fin (nN'.succ) → N := fin.cons ⟨y, y_mem⟩ (submodule.of_le N'_le_N ∘ bN'), refine @basis.mk _ _ _ bN'y _ _ _ _ _, { apply (bN'.linear_independent .map' (submodule.of_le N'_le_N) (submodule.ker_of_le _ _ _)) .fin_cons' _ _ _, intros c z hc, apply y_ortho_N' c z (submodule.mem_inf.mpr ⟨_, z.1.2⟩) (congr_arg coe hc), have : submodule.span R (set.range (submodule.of_le N'_le_N ∘ bN')) ≤ (ϕ.dom_restrict N).ker, { rw submodule.span_le, rintros _ ⟨i, rfl⟩, exact N'_le_ker (bN' i).2 }, exact this z.2 }, { rw eq_top_iff, rintro x -, rw [fin.range_cons, set.range_comp, submodule.mem_span_insert, submodule.span_image], obtain ⟨b, hb⟩ : _ ∣ ϕ x := generator_map_dvd_of_mem ϕ x.2, refine ⟨b, x - b • ⟨_, y_mem⟩, _, _⟩, { rw submodule.mem_map, refine ⟨⟨x - b • _, _⟩, bN'.mem_span _, rfl⟩, refine submodule.mem_inf.mpr ⟨linear_map.mem_ker.mpr _, N.sub_mem x.2 (N.smul_mem _ y_mem)⟩, dsimp only, rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { ext, simp only [ϕy_eq, add_sub_cancel'_right] } }, end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ this, have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
f14651a09561be05c16ec0aaa697d2d059a03a3f
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/group/hom.lean
61de5aaaf4ccd2f6df08ee4768254690294212fb
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
12,484
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group.commute /-! # monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. ## Notations * `→*` for bundled monoid homs (also use for group homs) * `→+` for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {M : Type*} {N : Type*} {P : Type*} -- monoids {G : Type*} {H : Type*} -- groups /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) infixr ` →+ `:25 := add_monoid_hom /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ @[to_additive add_monoid_hom] structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →* `:25 := monoid_hom @[to_additive] instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) := ⟨_, monoid_hom.to_fun⟩ namespace monoid_hom variables {mM : monoid M} {mN : monoid N} {mP : monoid P} variables [group G] [comm_group H] include mM mN @[simp, to_additive] lemma to_fun_eq_coe (f : M →* N) : f.to_fun = f := rfl @[simp, to_additive] lemma coe_mk (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl @[to_additive] lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[ext, to_additive] lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) attribute [ext] _root_.add_monoid_hom.ext @[to_additive] lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[simp, to_additive] lemma map_one (f : M →* N) : f 1 = 1 := f.map_one' /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ add_decl_doc add_monoid_hom.map_zero /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[simp, to_additive] lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ add_decl_doc add_monoid_hom.map_add @[to_additive] lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← f.map_mul, h, f.map_one] /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ omit mN mM /-- The identity map from a monoid to itself. -/ @[to_additive] def id (M : Type*) [monoid M] : M →* M := { to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The identity map from an additive monoid to itself. -/ add_decl_doc add_monoid_hom.id @[simp, to_additive] lemma id_apply {M : Type*} [monoid M] (x : M) : id M x = x := rfl include mM mN mP /-- Composition of monoid morphisms as a monoid morphism. -/ @[to_additive] def comp (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp } /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ add_decl_doc add_monoid_hom.comp @[simp, to_additive] lemma comp_apply (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive] lemma comp_assoc {Q : Type*} [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma cancel_right {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma cancel_left {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit mP @[simp, to_additive] lemma comp_id (f : M →* N) : f.comp (id M) = f := ext $ λ x, rfl @[simp, to_additive] lemma id_comp (f : M →* N) : (id N).comp f = f := ext $ λ x, rfl variables [mM] [mN] /-- `1` is the monoid homomorphism sending all elements to `1`. -/ @[to_additive] instance : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩ /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ add_decl_doc add_monoid_hom.has_zero @[simp, to_additive] lemma one_apply (x : M) : (1 : M →* N) x = 1 := rfl @[to_additive] instance : inhabited (M →* N) := ⟨1⟩ omit mM mN /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ @[to_additive] instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ add_decl_doc add_monoid_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl /-- (M →* N) is a comm_monoid if N is commutative. -/ @[to_additive add_comm_monoid] instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm } /-- `flip` arguments of `f : M →* N →* P` -/ @[to_additive "`flip` arguments of `f : M →+ N →+ P`"] def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) : N →* M →* P := { to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩, map_one' := ext $ λ x, (f x).map_one, map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ } @[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : f.flip y x = f x y := rfl /-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/ @[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`, then they are equal at `-x`." ] lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) : f x⁻¹ = g x⁻¹ := left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $ h.symm ▸ g.map_mul_eq_one $ mul_inv_self x /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive] theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g /-- Group homomorphisms preserve division. -/ @[simp, to_additive] theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv] /-- A group homomorphism is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff {G H} [group G] [group H] (f : G →* H) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← f.map_one; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← f.map_inv, ← f.map_mul] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ include mM /-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/ @[to_additive] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] } /-- Makes an additive group homomomorphism from a proof that the map preserves multiplication. -/ add_decl_doc add_monoid_hom.mk' @[simp, to_additive] lemma coe_mk' {f : M → G} (map_mul : ∀ a b : M, f (a * b) = f a * f b) : ⇑(mk' f map_mul) = f := rfl omit mM /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive] instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩ /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ add_decl_doc add_monoid_hom.has_neg @[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl /-- If `G` is a commutative group, then `M →* G` a commutative group too. -/ @[to_additive add_comm_group] instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, mul_left_inv := by intros; ext; apply mul_left_inv, ..monoid_hom.comm_monoid } /-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/ add_decl_doc add_monoid_hom.add_comm_group end monoid_hom namespace add_monoid_hom /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {G H} [add_group G] [add_group H] (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) := f.map_add_neg g h end add_monoid_hom section commute variables [monoid M] [monoid N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, f.map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f end commute
431ecb74bdc17299b5711ee26b180f692944e916
abd677583c7e4d55daf9487b82da11b7c5498d8d
/src/exp.lean
7f03a496c1895457267613e68220fb7921b0af83
[ "Apache-2.0" ]
permissive
jesse-michael-han/embed
e9c346918ad58e03933bdaa057a571c0cc4a7641
c2fc188328e871e18e0dcb8258c6d0462c70a8c9
refs/heads/master
1,584,677,705,005
1,528,451,877,000
1,528,451,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,030
lean
import .list .misc variable {α : Type } inductive exp (α : Type) : Type | bvr : nat → exp | fvr : nat → exp | cst : α → exp | lam : exp → exp | app : exp → exp → exp notation `#` n := exp.bvr _ n notation `&` n := exp.fvr _ n def seq (α : Type) : Type := (list (exp α)) × (list (exp α)) def proves (Γ Δ : list (exp α)) : seq α := ⟨Γ,Δ⟩ notation Γ `==>` Δ := proves Γ Δ def fvrs : exp α → list nat | (exp.lam e) := fvrs e | (exp.app e1 e2) := fvrs e1 ++ fvrs e2 | (exp.fvr α k) := [k] | _ := [] def fvrs_list : list (exp α) → list nat | [] := [] | (e::es) := fvrs e ++ fvrs_list es def inst_rec : nat → exp α → exp α → exp α | n t (exp.bvr α m) := if n = m then t else (exp.bvr α m) | n t (exp.lam e) := exp.lam (inst_rec (n+1) t e) | n t (exp.app e1 e2) := exp.app (inst_rec n t e1) (inst_rec n t e2) | _ _ e := e def inst (t e : exp α) : exp α := inst_rec 0 t e instance [decidable_eq α] : decidable_eq (exp α) := by tactic.mk_dec_eq_instance
84617e16e9d35ce17c888d63f4369e3b2cd2687b
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set_like/fintype.lean
1909ca5648ff78ca64653d0a4d6c88f44cdacd03
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
718
lean
/- Copyright (c) 2021 . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.set_like.basic import data.fintype.basic /-! # Set-like fintype This file contains a fintype instance for set-like objects such as subgroups. If `set_like A B` and `fintype B` then `fintype A`. -/ namespace set_like /-- TODO: It should be possible to obtain a computable version of this for most set_like objects. If we add those instances, we should remove this one. -/ @[nolint dangerous_instance, instance, priority 100] noncomputable instance {A B : Type*} [fintype B] [set_like A B] : fintype A := fintype.of_injective coe set_like.coe_injective end set_like
86dbff56a90b519f659258359daca96db3feab64
510e96af568b060ed5858226ad954c258549f143
/algebra/lattice/complete_lattice_experiment.lean
0790e663a0a825a112b9354cb395b867a6feab7f
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
25,285
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 Theory of complete lattices. -/ import .bounded_lattice_experiment data.set set_option old_structure_cmd true universes u v w w₂ variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} /- Note: we can't really experiment with sets, because of the cyclic imports. Let's fake it here by declaring some facts with the same attributes they have in data.set.basic. -/ section open set -- TODO: I had to add ematch here @[simp, ematch] lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl theorem set_eq_def (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, set.ext⟩ theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl @[simp] lemma mem_set_of_eq (a : α) (P : α → Prop) : a ∈ {a : α | P a} = P a := rfl @[simp] lemma nmem_set_of_eq (a : α) (P : α → Prop) : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] lemma set_of_false : {a : α | false} = ∅ := set.ext $ assume a, by simp [mem_empty_eq] attribute [simp] mem_empty_eq empty_subset @[simp] theorem mem_univ_eq (x : α) : x ∈ @univ α = true := rfl @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl attribute [simp] union_self union_empty empty_union -- union_comm union_assoc theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish [set_eq_def] attribute [simp] union_comm union_assoc union_left_comm @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl attribute [simp] inter_self inter_empty empty_inter -- inter_comm inter_assoc theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish [set_eq_def, iff_def] attribute [simp] inter_comm inter_assoc inter_left_comm theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y, assume ys, or.inr ys @[simp] theorem mem_insert_iff (x a : α) (s : set α) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.refl _ @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [set_eq_def, iff_def] theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff (a b : α) : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [set_eq_def, iff_def] -- TODO: old proof in basic.lean: -- ⟨assume eq, eq_of_mem_singleton $ eq ▸ mem_singleton x, by intro; simp [*]⟩ end namespace lattice class has_Sup (α : Type u) := (Sup : set α → α) class has_Inf (α : Type u) := (Inf : set α → α) def Sup [has_Sup α] : set α → α := has_Sup.Sup def Inf [has_Inf α] : set α → α := has_Inf.Inf class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) def supr [complete_lattice α] (s : ι → α) : α := Sup {a : α | ∃i : ι, a = s i} def infi [complete_lattice α] (s : ι → α) : α := Inf {a : α | ∃i : ι, a = s i} notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r section open set variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] lemma le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a lemma Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] lemma Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a lemma le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a lemma le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) lemma Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h lemma Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha) lemma Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha) @[simp] lemma le_Sup_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨suppose Sup s ≤ a, assume b, suppose b ∈ s, le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›, Sup_le⟩ @[simp] lemma Inf_le_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨suppose a ≤ Inf s, assume b, suppose b ∈ s, le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›), le_Inf⟩ -- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`? lemma Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s := by have := le_Sup h; finish --Inf_le_of_le h (le_Sup h) -- TODO: it is weird that we have to add union_def lemma Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := le_antisymm (by finish) (by finish [union_def]) /- old proof: le_antisymm (Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup)) (sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _)) -/ lemma 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)) -/ lemma Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := le_antisymm (by finish [union_def]) (by finish) /- old proof: le_antisymm (le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _)) (le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le)) -/ lemma le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := by finish /- le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t)) -/ @[simp] lemma Sup_empty : Sup ∅ = (⊥ : α) := le_antisymm (by finish) (by finish) -- le_antisymm (Sup_le (assume _, false.elim)) bot_le @[simp] lemma Inf_empty : Inf ∅ = (⊤ : α) := le_antisymm (by finish) (by finish) --le_antisymm le_top (le_Inf (assume _, false.elim)) @[simp] lemma Sup_univ : Sup univ = (⊤ : α) := le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤ --le_antisymm le_top (le_Sup ⟨⟩) @[simp] lemma Inf_univ : Inf univ = (⊥ : α) := le_antisymm (Inf_le ⟨⟩) bot_le @[simp] lemma Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := le_antisymm (by finish) (by finish [insert_def]) /- old proof have Sup {b | b = a} = a, from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl), calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union ... = a ⊔ Sup s : by rw [this] -/ @[simp] lemma Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := le_antisymm (by finish [insert_def]) (by finish) /- old proof have Inf {b | b = a} = a, from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _), calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union ... = a ⊓ Inf s : by rw [this] -/ @[simp] lemma Sup_singleton {a : α} : Sup {a} = a := by finish [singleton_def] --eq.trans Sup_insert $ by simp @[simp] lemma Inf_singleton {a : α} : Inf {a} = a := by finish [singleton_def] --eq.trans Inf_insert $ by simp end /- supr & infi -/ section open set variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] lemma le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] lemma 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] lemma le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) lemma supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq^.symm ▸ h i lemma supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) lemma 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 lemma supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] lemma supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := ⟨suppose supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩ -- TODO: finish doesn't do well here. @[congr] lemma supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq^.mpr x) = f₂ x) : supr f₁ = supr f₂ := le_antisymm (supr_le_supr2 $ assume j, ⟨pq^.mp j, le_of_eq $ f _⟩) (supr_le_supr2 $ assume j, ⟨pq^.mpr j, le_of_eq $ (f j)^.symm⟩) lemma infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] lemma infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ example {f : β → α} (b : β) : (⨅ x, f x) ≤ f b := begin [smt] eblast end /- I wanted to see if this would help for infi_comm; it doesn't. @[ematch] lemma infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) := begin transitivity, apply (infi_le (λ i, ⨅ j, s i j) i), apply infi_le end -/ lemma infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h lemma le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq^.symm ▸ h i lemma infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) lemma 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 lemma infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] lemma le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨suppose a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ @[congr] lemma infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq^.mpr x) = f₂ x) : infi f₁ = infi f₂ := le_antisymm (infi_le_infi2 $ assume j, ⟨pq^.mpr j, le_of_eq $ f j⟩) (infi_le_infi2 $ assume j, ⟨pq^.mp j, le_of_eq $ (f _)^.symm⟩) -- TODO: why isn't this a valid simp lemma? -- @[simp] lemma infi_const {a : α} (b : ι) : (⨅ b:ι, a) = a := le_antisymm (Inf_le ⟨b, rfl⟩) (by finish) -- le_antisymm (Inf_le ⟨b, rfl⟩) (le_Inf $ assume a' ⟨b', h⟩, h^.symm ▸ le_refl _) lemma supr_const {a : α} (b : ι) : (⨆ b:ι, a) = a := le_antisymm (by finish) (le_Sup ⟨b, rfl⟩) --le_antisymm (Sup_le $ assume a' ⟨b', h⟩, h^.symm ▸ le_refl _) (le_Sup ⟨b, rfl⟩) -- TODO: should this be @[simp]? lemma 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]? lemma supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := le_antisymm (supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i) (supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j) @[simp] lemma 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] lemma 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] lemma supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) @[simp] lemma supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) attribute [ematch] le_refl @[ematch] lemma foo {a b : α} (h : a = b) : a ≤ b := by rw h; apply le_refl @[ematch] lemma foo' {a b : α} (h : b = a) : a ≤ b := by rw h; apply le_refl lemma 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 supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ assume i, sup_le (le_sup_left_of_le $ le_supr _ _) (le_sup_right_of_le $ le_supr _ _)) (sup_le (supr_le $ assume i, le_supr_of_le i le_sup_left) (supr_le $ assume i, le_supr_of_le i le_sup_right)) /- supr and infi under Prop -/ @[simp] lemma infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] lemma supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] lemma infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] lemma supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] lemma 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 $ suppose p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] lemma supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ suppose p i, le_supr _ _) lemma infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ : p, ⨅ h₂ : q, 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 _ _) lemma supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ : p, ⨆ h₂ : q, s ⟨h₁, h₂⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) lemma 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) lemma supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := le_antisymm (supr_le $ assume s, match s with | or.inl i := le_sup_left_of_le $ le_supr _ i | or.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩)) lemma Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := le_antisymm (le_infi $ assume b, le_infi $ assume h, Inf_le h) (le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h) lemma 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 Inf_image {s : set β} {f : β → α} : Inf (set.image f s) = (⨅ a ∈ s, f a) := calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi ... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp ... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm] ... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm] ... = (⨅a∈s, f a) : congr_arg infi $ funext $ assume x, by rw [infi_infi_eq_left] lemma Sup_image {s : set β} {f : β → α} : Sup (set.image f s) = (⨆ a ∈ s, f a) := calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr ... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp ... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm] ... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm] ... = (⨆a∈s, f a) : congr_arg supr $ funext $ assume x, by rw [supr_supr_eq_left] /- supr and infi under set constructions -/ /- should work using the simplifier! -/ @[simp] lemma infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := le_antisymm le_top (le_infi $ assume x, le_infi false.elim) @[simp] lemma supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le @[simp] lemma infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x, from congr_arg infi $ funext $ assume x, infi_const ⟨⟩ @[simp] lemma supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x, from congr_arg supr $ funext $ assume x, supr_const ⟨⟩ @[simp] lemma infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or ... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq @[simp] lemma supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq @[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl @[simp] lemma 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 @[simp] lemma 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 @[simp] lemma infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := show (⨅ x ∈ insert b (∅ : set β), f x) = f b, by simp @[simp] lemma supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := show (⨆ x ∈ insert b (∅ : set β), f x) = f b, by simp /- supr and infi under Type -/ @[simp] lemma infi_empty {s : empty → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i) @[simp] lemma supr_empty {s : empty → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le @[simp] lemma infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] lemma supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) lemma 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 $ suppose p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ suppose p i, le_supr _ _) lemma infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ suppose p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ suppose p i, le_supr _ _) lemma infi_prod {γ : Type w} {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 _ _) lemma supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i, ⨆ j, f (i, j)) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) lemma infi_sum {γ : Type w} {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) lemma supr_sum {γ : Type w} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := le_antisymm (supr_le $ assume s, match s with | sum.inl i := le_sup_left_of_le $ le_supr _ i | sum.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩)) end /- Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { lattice.bounded_lattice_Prop with 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 } instance complete_lattice_fun {α : Type u} {β : Type v} [complete_lattice β] : complete_lattice (α → β) := { lattice.bounded_lattice_fun with Sup := λs a, Sup (set.image (λf : α → β, f a) s), le_Sup := assume s f h a, le_Sup ⟨f, h, rfl⟩, Sup_le := assume s f h a, Sup_le $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a, Inf := λs a, Inf (set.image (λf : α → β, f a) s), Inf_le := assume s f h a, Inf_le ⟨f, h, rfl⟩, le_Inf := assume s f h a, le_Inf $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a } section complete_lattice variables [weak_order α] [complete_lattice β] lemma monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h lemma monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h end complete_lattice end lattice /- Classical statements: @[simp] lemma Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := _ @[simp] lemma Sup_eq_bot : Sup s = ⊤ ↔ (∀a∈s, a = ⊥) := _ @[simp] lemma supr_eq_top : supr s = ⊤ ↔ (∀i, s i = ⊥) := _ -/
3144d9ed6ba4a0ba7a710e5ad2e3b6a064051374
4727251e0cd73359b15b664c3170e5d754078599
/src/combinatorics/hales_jewett.lean
bef6e7dab21b86127d36da8c4fe6bd451a91e3b0
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,423
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.fintype.basic import algebra.big_operators.basic /-! # The Hales-Jewett theorem We prove the Hales-Jewett theorem and deduce Van der Waerden's theorem as a corollary. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `combinatorics.line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `combinatorics.line.exists_mono_in_high_dimension'` for details. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `combinatorics.line.exists_mono_in_high_dimension`: the Hales-Jewett theorem. - `combinatorics.exists_mono_homothetic_copy`: a generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `fin n`, `fin (n+1)`, `fin (c^(n^H))`, and `fin (H + H')`. ## Todo - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progession ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open_locale classical open_locale big_operators universes u v namespace combinatorics /-- The type of combinatorial lines. A line `l : line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `λ x, l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `λ x, l x i` is `id` for at least one `i`. Formally, a line is represented by the function `l.idx_fun : ι → option α` which says whether `λ x, l x i` is `id` (corresponding to `l.idx_fun i = none`) or constantly `y` (corresponding to `l.idx_fun i = some y`). When `α` has size `1` there can be many elements of `line α ι` defining the same function. -/ structure line (α ι : Type*) := (idx_fun : ι → option α) (proper : ∃ i, idx_fun i = none) namespace line /- This lets us treat a line `l : line α ι` as a function `α → ι → α`. -/ instance (α ι) : has_coe_to_fun (line α ι) (λ _, α → ι → α) := ⟨λ l x i, (l.idx_fun i).get_or_else x⟩ /-- A line is monochromatic if all its points are the same color. -/ def is_mono {α ι κ} (C : (ι → α) → κ) (l : line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [nonempty ι] : line α ι := { idx_fun := λ _, none, proper := ⟨classical.arbitrary ι, rfl⟩ } instance (α ι) [nonempty ι] : inhabited (line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure almost_mono {α ι κ : Type*} (C : (ι → option α) → κ) := (line : line (option α) ι) (color : κ) (has_color : ∀ x : α, C (line (some x)) = color) instance {α ι κ : Type*} [nonempty ι] [inhabited κ] : inhabited (almost_mono (λ v : ι → option α, (default : κ))) := ⟨{ line := default, color := default, has_color := λ _, rfl }⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure color_focused {α ι κ : Type*} (C : (ι → option α) → κ) := (lines : multiset (almost_mono C)) (focus : ι → option α) (is_focused : ∀ p ∈ lines, almost_mono.line p none = focus) (distinct_colors : (lines.map almost_mono.color).nodup) instance {α ι κ} (C : (ι → option α) → κ) : inhabited (color_focused C) := ⟨⟨0, λ _, none, λ _, false.elim, multiset.nodup_zero⟩⟩ /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i`, `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : line α ι) : line α' ι := { idx_fun := λ i, (l.idx_fun i).map f, proper := ⟨l.proper.some, by rw [l.proper.some_spec, option.map_none'] ⟩ } /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim (some ∘ v) l.idx_fun, proper := ⟨sum.inr l.proper.some, l.proper.some_spec⟩ } /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : line α ι) (v : ι' → α) : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun (some ∘ v), proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : line α ι) (l' : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun l'.idx_fun, proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } lemma apply {α ι} (l : line α ι) (x : α) : l x = λ i, (l.idx_fun i).get_or_else x := rfl lemma apply_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i = none) : l x i = x := by simp only [option.get_or_else_none, h, l.apply] lemma apply_of_ne_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i ≠ none) : some (l x i) = l.idx_fun i := by rw [l.apply, option.get_or_else_of_ne_none h] @[simp] lemma map_apply {α α' ι} (f : α → α') (l : line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [line.apply, line.map, option.get_or_else_map] @[simp] lemma vertical_apply {α ι ι'} (v : ι → α) (l : line α ι') (x : α) : l.vertical v x = sum.elim v (l x) := by { funext i, cases i; refl } @[simp] lemma horizontal_apply {α ι ι'} (l : line α ι) (v : ι' → α) (x : α) : l.horizontal v x = sum.elim (l x) v := by { funext i, cases i; refl } @[simp] lemma prod_apply {α ι ι'} (l : line α ι) (l' : line α ι') (x : α) : l.prod l' x = sum.elim (l x) (l' x) := by { funext i, cases i; refl } @[simp] lemma diagonal_apply {α ι} [nonempty ι] (x : α) : line.diagonal α ι x = λ i, x := by simp_rw [line.apply, line.diagonal, option.get_or_else_none] /-- The Hales-Jewett theorem. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [fintype α] (κ : Type (max v u)) [fintype κ], ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := -- The proof proceeds by induction on `α`. fintype.induction_empty_option -- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. (λ α α' e, forall_imp $ λ κ, forall_imp $ λ _, Exists.imp $ λ ι, Exists.imp $ λ _ h C, let ⟨l, c, lc⟩ := h (λ v, C (e ∘ v)) in ⟨l.map e, c, e.forall_congr_left.mp $ λ x, by rw [←lc x, line.map_apply]⟩) begin -- This deals with the degenerate case where `α` is empty. introsI κ _, by_cases h : nonempty κ, { resetI, exact ⟨unit, infer_instance, λ C, ⟨default, classical.arbitrary _, pempty.rec _⟩⟩, }, { exact ⟨empty, infer_instance, λ C, (h ⟨C (empty.rec _)⟩).elim⟩, } end begin -- Now we have to show that the theorem holds for `option α` if it holds for `α`. introsI α _ ihα κ _, -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is empty. -- Then `option α` has only one element, so any line is monochromatic. by_cases h : nonempty α, work_on_goal 2 { refine ⟨unit, infer_instance, λ C, ⟨diagonal _ _, C (λ _, none), _⟩⟩, rintros (_ | ⟨a⟩), refl, exact (h ⟨a⟩).elim, }, -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → (option α)) → κ, (∃ s : color_focused C, s.lines.card = r) ∨ (∃ l, is_mono C l), -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors so -- we must be in the second case, where there is a monochromatic line. { obtain ⟨ι, _inst, hι⟩ := key (fintype.card κ + 1), refine ⟨ι, _inst, λ C, (hι C).resolve_left _⟩, rintro ⟨s, sr⟩, apply nat.not_succ_le_self (fintype.card κ), rw [←nat.add_one, ←sr, ←multiset.card_map, ←finset.card_mk], exact finset.card_le_univ ⟨_, s.distinct_colors⟩ }, -- We now prove the key claim, by induction on `r`. intro r, induction r with r ihr, -- The base case `r = 0` is trivial as the empty collection is color-focused. { exact ⟨empty, infer_instance, λ C, or.inl ⟨default, multiset.card_zero⟩⟩, }, -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high enough -- dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr, resetI, -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such that -- `ι' → α` always has a monochromatic line whenever it is `(ι → option α) → κ`-colored. specialize ihα ((ι → option α) → κ), obtain ⟨ι', _inst, hι'⟩ := ihα, resetI, -- We claim that `ι ⊕ ι'` works for `option α` and `κ`-coloring. refine ⟨ι ⊕ ι', infer_instance, _⟩, intro C, -- A `κ`-coloring of `ι ⊕ ι' → option α` induces an `(ι → option α) → κ`-coloring of `ι' → α`. specialize hι' (λ v' v, C (sum.elim v (some ∘ v'))), -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι', -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, is_mono C' l) → (∃ l, is_mono C l), { rintro ⟨l, c, hl⟩, refine ⟨l.horizontal (some ∘ l' (classical.arbitrary α)), c, λ x, _⟩, rw [line.horizontal_apply, ←hl, ←hl'], }, -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C', rcases hι with ⟨s, sr⟩ | _, -- By above, we are done if `C'` has a monochromatic line. work_on_goal 2 { exact or.inr (mono_of_mono hι) }, -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether one of -- these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : almost_mono _).color = C' s.focus, -- If so then this is a `C'`-monochromatic line and we are done. { obtain ⟨p, p_mem, hp⟩ := h, refine or.inr (mono_of_mono ⟨p.line, p.color, _⟩), rintro (_ | _), rw [hp, s.is_focused p p_mem], apply p.has_color, }, -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` and -- adding to this the vertical line obtained by the focus point and `l`. refine or.inl ⟨⟨(s.lines.map _).cons ⟨(l'.map some).vertical s.focus, C' s.focus, λ x, _⟩, sum.elim s.focus (l'.map some none), _, _⟩, _⟩, -- The vertical line is almost monochromatic. { rw [vertical_apply, ←congr_fun (hl' x), line.map_apply], }, { refine λ p, ⟨p.line.prod (l'.map some), p.color, λ x, _⟩, -- The product lines are almost monochromatic. rw [line.prod_apply, line.map_apply, ←p.has_color, ←congr_fun (hl' x)], }, -- Our `r+1` lines have the same endpoint. { simp_rw [multiset.mem_cons, multiset.mem_map], rintros _ (rfl | ⟨q, hq, rfl⟩), { rw line.vertical_apply, }, { rw [line.prod_apply, s.is_focused q hq], }, }, -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). { rw [multiset.map_cons, multiset.map_map, multiset.nodup_cons, multiset.mem_map], exact ⟨λ ⟨q, hq, he⟩, h ⟨q, hq, he⟩, s.distinct_colors⟩, }, -- Finally, we really do have `r+1` lines! { rw [multiset.card_cons, multiset.card_map, sr], }, end /-- The Hales-Jewett theorem: for any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [fintype α] (κ : Type v) [fintype κ] : ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension' α (ulift κ) in ⟨ι, ιfin, λ C, let ⟨l, c, hc⟩ := hι (ulift.up ∘ C) in ⟨l, c.down, λ x, by rw ←hc⟩ ⟩ end line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ} [add_comm_monoid M] (S : finset M) [fintype κ] (C : M → κ) : ∃ (a > 0) (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := begin obtain ⟨ι, _inst, hι⟩ := line.exists_mono_in_high_dimension S κ, resetI, specialize hι (λ v, C $ ∑ i, v i), obtain ⟨l, c, hl⟩ := hι, set s : finset ι := { i ∈ finset.univ | l.idx_fun i = none } with hs, refine ⟨s.card, finset.card_pos.mpr ⟨l.proper.some, _⟩, ∑ i in sᶜ, ((l.idx_fun i).map coe).get_or_else 0, c, _⟩, { rw [hs, finset.sep_def, finset.mem_filter], exact ⟨finset.mem_univ _, l.proper.some_spec⟩, }, intros x xs, rw ←hl ⟨x, xs⟩, clear hl, congr, rw ←finset.sum_add_sum_compl s, congr' 1, { rw ←finset.sum_const, apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.mem_filter] at hi, rw [l.apply_none _ _ hi.right, subtype.coe_mk], }, { apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.compl_filter, finset.mem_filter] at hi, obtain ⟨y, hy⟩ := option.ne_none_iff_exists.mp hi.right, simp_rw [line.apply, ←hy, option.map_some', option.get_or_else_some], }, end end combinatorics
579d633509e07ba5d9c46129486d7911b75a39ce
680b0d1592ce164979dab866b232f6fa743f2cc8
/hott/types/bool.hlean
4e947756d0d1cd4f8df4de3c18bc07ee605d7555
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
4,765
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Floris van Doorn Partially ported from the standard library -/ open eq eq.ops decidable namespace bool local attribute bor [reducible] local attribute band [reducible] theorem dichotomy (b : bool) : b = ff ⊎ b = tt := bool.cases_on b (sum.inl rfl) (sum.inr rfl) theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff : Π {a : bool}, a ≠ ff → a = tt | @eq_tt_of_ne_ff tt H := rfl | @eq_tt_of_ne_ff ff H := absurd rfl H theorem eq_ff_of_ne_tt : Π {a : bool}, a ≠ tt → a = ff | @eq_ff_of_ne_tt tt H := absurd rfl H | @eq_ff_of_ne_tt ff H := rfl theorem absurd_of_eq_ff_of_eq_tt {B : Type} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt theorem tt_bor (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor_tt (a : bool) : a || tt = tt := bool.cases_on a rfl rfl theorem ff_bor (a : bool) : ff || a = a := bool.cases_on a rfl rfl theorem bor_ff (a : bool) : a || ff = a := bool.cases_on a rfl rfl theorem bor_self (a : bool) : a || a = a := bool.cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := by cases a; repeat (cases b | reflexivity) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := match a with | ff := by rewrite *ff_bor | tt := by rewrite *tt_bor end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ⊎ b = tt := bool.rec_on a (suppose ff || b = tt, have b = tt, from !ff_bor ▸ this, sum.inr this) (suppose tt || b = tt, sum.inl rfl) theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rewrite H theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := bool.rec_on a (by rewrite H) (by rewrite H) theorem ff_band (a : bool) : ff && a = ff := rfl theorem tt_band (a : bool) : tt && a = a := bool.cases_on a rfl rfl theorem band_ff (a : bool) : a && ff = ff := bool.cases_on a rfl rfl theorem band_tt (a : bool) : a && tt = a := bool.cases_on a rfl rfl theorem band_self (a : bool) : a && a = a := bool.cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := match a with | ff := by rewrite *ff_band | tt := by rewrite *tt_band end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := sum.elim (dichotomy a) (suppose a = ff, absurd (calc ff = ff && b : ff_band ... = a && b : this ... = tt : H) ff_ne_tt) (suppose a = tt, this) theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by rewrite [H₁, H₂] theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := band_elim_left (!band.comm ⬝ H) theorem bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl theorem bnot_empty : bnot ff = tt := rfl theorem bnot_unit : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := bool.cases_on a (by contradiction) (λ h, rfl) theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := bool.cases_on a (λ h, rfl) (by contradiction) definition bxor (x:bool) (y:bool) := cond x (bnot y) y /- HoTT-related stuff -/ open is_equiv equiv function is_trunc option unit decidable definition is_equiv_bnot [constructor] [instance] [priority 500] : is_equiv bnot := begin fapply is_equiv.mk, exact bnot, all_goals (intro b;cases b), do 6 reflexivity -- all_goals (focus (intro b;cases b;all_goals reflexivity)), end definition bnot_ne : Π(b : bool), bnot b ≠ b | bnot_ne tt := ff_ne_tt | bnot_ne ff := ne.symm ff_ne_tt definition equiv_bnot [constructor] : bool ≃ bool := equiv.mk bnot _ definition eq_bnot : bool = bool := ua equiv_bnot definition eq_bnot_ne_idp : eq_bnot ≠ idp := assume H : eq_bnot = idp, assert H2 : bnot = id, from !cast_ua_fn⁻¹ ⬝ ap cast H, absurd (ap10 H2 tt) ff_ne_tt definition bool_equiv_option_unit : bool ≃ option unit := begin fapply equiv.MK, { intro b, cases b, exact none, exact some star}, { intro u, cases u, exact ff, exact tt}, { intro u, cases u with u, reflexivity, cases u, reflexivity}, { intro b, cases b, reflexivity, reflexivity}, end definition tbool [constructor] : hset := trunctype.mk bool _ end bool
2606d278d2175376a644c881ed8fab213c487894
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/sup_inf/supProdSets.lean
3fbb463b9974cc311935afc6cbda66ae4eb3f69e
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,924
lean
import .lub_prodSets namespace xena -- hide /- # Chapter 3 : Sup and Inf ## Level 10 -/ -- main result in lemma sup_mem_prod_of_sets -- hide --def mem_prod_sets (A : set ℝ) (B : set ℝ) := { x : ℝ | ∃ y ∈ A, ∃ z ∈ B, x = y * z} /- Intermediary result `zero_in_prod` proved in sets_level08. Intermediary result `mem_prod_sets_lub_proof` in previous level. -/ /- Lemma For two non-empty sets of reals $A$ and $B$, it is not in general true that $$ \textrm{sup} (A \cdot B) = \textrm{sup} (A) \cdot \textrm{sup}(B)$$ where $A \cdot B$ is defined pointwise as above. -/ lemma sup_mem_prod_of_sets : ¬ ( ∀ (A B : set ℝ) (a b : ℝ), A.nonempty ∧ B.nonempty → bdd_below A ∧ bdd_below B → is_lub A a ∧ is_lub B b → is_lub (mem_prod_sets A B) (a * b) ) := begin intro H, -- do an example with A = [-2,-1], B = [0,3] set A1 : set ℝ := set.Icc (-2:ℝ) (-1:ℝ) with hA, set B1 : set ℝ := set.Icc (0:ℝ) (3:ℝ) with hB, set a : ℝ := (-1:ℝ) with ha, set b : ℝ := (3 : ℝ) with hb, have G := H A1 B1, have h1A : A1.nonempty, simp, norm_num, have h1B : B1.nonempty, simp, norm_num, have F := G a b (and.intro h1A h1B), have h11 : ((-2:ℝ) ≤ -1), norm_num, have h21 : (0:ℝ) ≤ (3:ℝ), norm_num, have h2A : bdd_below A1, -- use the definition in bounds.lean have h12 := is_glb_Icc h11, cases h12 with hh hhh, existsi (-2:ℝ), exact hh, have h2B : bdd_below B1, have h22 := is_glb_Icc h21, cases h22 with hh hhh, existsi (0:ℝ), exact hh, have E := F (and.intro h2A h2B), have h1 : is_lub A1 a, exact is_lub_Icc h11, have h2 : is_lub B1 b, exact is_lub_Icc h21, have D := E (and.intro h1 h2), rw ha at h1, rw hb at h2, rw ha at D, rw hb at D, have E : is_lub (mem_prod_sets A1 B1) 0, exact mem_prod_sets_lub_proof, have E1 := is_lub.unique D E, linarith, done end end xena -- hide
845c67fea799d1b5139fd01e3e85784c3774d52b
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/linear_algebra/basis.lean
39b3847bc1067e773018fd0730f4e54efa552db4
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
53,096
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.basic linear_algebra.finsupp order.zorn /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where M is the module or vectorspace and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linear independent * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linear independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linear independent and spans the entire space * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type ι. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function lattice set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} include R variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = s.sum (λ j, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j))) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = s.sum (λ j, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /- The following lemmas use the subtype defined by a set in M as the index set ι. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ subtype.val_injective }, intros i hi, rw mem_image, use subtype.mk i (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ s) hi), rw mem_preimage, exact ⟨hi, rfl⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], apply subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply set.inj_on_of_injective _ (linear_independent.injective zero_eq_one hv) }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (function.restrict v s) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint_mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine disjoint_mono (le_refl _) _ (hd i _ _ his), { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (inj_on_of_injective _ (assume i j, plift.up.inj)) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv` -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp, by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_mono _ _ disjoint_inl_inr, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action L L; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y = s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _ ... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib ... = (g a * a x * a y + s.sum (λ i, g i * i x * i y)) - (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub ... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) : by rw [finset.sum_insert has, finset.sum_insert has] ... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, a x * (g i * i y)) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y) - a x * (insert a s).sum (λ i, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (insert a s).sum (λ i, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp` -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M M'} [comm_ring R] [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] {v : ι → R} {f : ι → M'} {a : R} (hv : is_basis R v) {b : M} : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [inhabited ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules M and M' with respective bases v and v' and a bijection between the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} {f : M → M'} {g : M' → M} (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over R with a finite basis is linearly equivalent to functions from its basis to R. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun end module section vector_space variables {v : ι → V} [discrete_field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section set_option class.instance_max_depth 36 lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul _ (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span K b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by rw [finset.union_comm] at hb₂t'; simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : V →ₗ[K] V'} (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → V), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : V →ₗ[K] V'} (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (function.restrict (inv_fun f) C : C → V), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end set_option class.instance_max_depth 49 open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.copair p.subtype) (p.mkq.pair (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := begin apply exists.elim (exists_is_basis K V), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact module.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] [fintype η] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, refine disjoint_mono h₁ h₂ (disjoint_std_basis_std_basis _ _ _ _ h₃), } end lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R ι) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis R (λ (i : η), R) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _), end lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply is_basis.comp (is_basis_fun₀ R) (λ i, ⟨i, punit.star⟩) , { apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] }, apply_instance end end end module end pi
e04e260ef67e993d44af632611e0e866a5edfb12
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/number_theory/class_number/finite.lean
1244ed387a64484db6a7555612babda4322c445e
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,912
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.free_module.pid import linear_algebra.matrix.absolute_value import number_theory.class_number.admissible_absolute_value import number_theory.function_field import number_theory.number_field import ring_theory.class_group import ring_theory.norm /-! # Class numbers of global fields In this file, we use the notion of "admissible absolute value" to prove finiteness of the class group for number fields and function fields, and define `class_number` as the order of this group. ## Main definitions - `class_group.fintype_of_admissible`: if `R` has an admissible absolute value, its integral closure has a finite class group -/ open_locale big_operators open_locale non_zero_divisors namespace class_group open ring open_locale big_operators section euclidean_domain variables (R S K L : Type*) [euclidean_domain R] [comm_ring S] [integral_domain S] variables [field K] [field L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] [is_separable K L] variables [algRL : algebra R L] [is_scalar_tower R K L] variables [algebra R S] [algebra S L] variables [ist : is_scalar_tower R S L] [iic : is_integral_closure S R L] variables {R S} (abv : absolute_value R ℤ) variables {ι : Type*} [decidable_eq ι] [fintype ι] (bS : basis ι R S) /-- If `b` is an `R`-basis of `S` of cardinality `n`, then `norm_bound abv b` is an integer such that for every `R`-integral element `a : S` with coordinates `≤ y`, we have algebra.norm a ≤ norm_bound abv b * y ^ n`. (See also `norm_le` and `norm_lt`). -/ noncomputable def norm_bound : ℤ := let n := fintype.card ι, i : ι := nonempty.some bS.index_nonempty, m : ℤ := finset.max' (finset.univ.image (λ (ijk : ι × ι × ι), abv (algebra.left_mul_matrix bS (bS ijk.1) ijk.2.1 ijk.2.2))) ⟨_, finset.mem_image.mpr ⟨⟨i, i, i⟩, finset.mem_univ _, rfl⟩⟩ in nat.factorial n • (n • m) ^ n lemma norm_bound_pos : 0 < norm_bound abv bS := begin obtain ⟨i, j, k, hijk⟩ : ∃ i j k, algebra.left_mul_matrix bS (bS i) j k ≠ 0, { by_contra h, push_neg at h, obtain ⟨i⟩ := bS.index_nonempty, apply bS.ne_zero i, apply (algebra.left_mul_matrix bS).injective_iff.mp (algebra.left_mul_matrix_injective bS), ext j k, simp [h, dmatrix.zero_apply] }, simp only [norm_bound, algebra.smul_def, ring_hom.eq_nat_cast, int.nat_cast_eq_coe_nat], refine mul_pos (int.coe_nat_pos.mpr (nat.factorial_pos _)) _, refine pow_pos (mul_pos (int.coe_nat_pos.mpr (fintype.card_pos_iff.mpr ⟨i⟩)) _) _, refine lt_of_lt_of_le (abv.pos hijk) (finset.le_max' _ _ _), exact finset.mem_image.mpr ⟨⟨i, j, k⟩, finset.mem_univ _, rfl⟩ end /-- If the `R`-integral element `a : S` has coordinates `≤ y` with respect to some basis `b`, its norm is less than `norm_bound abv b * y ^ dim S`. -/ lemma norm_le (a : S) {y : ℤ} (hy : ∀ k, abv (bS.repr a k) ≤ y) : abv (algebra.norm R a) ≤ norm_bound abv bS * y ^ fintype.card ι := begin conv_lhs { rw ← bS.sum_repr a }, rw [algebra.norm_apply, ← linear_map.det_to_matrix bS], simp only [algebra.norm_apply, alg_hom.map_sum, alg_hom.map_smul, linear_equiv.map_sum, linear_equiv.map_smul, algebra.to_matrix_lmul_eq, norm_bound, smul_mul_assoc, ← mul_pow], convert matrix.det_sum_smul_le finset.univ _ hy using 3, { rw [finset.card_univ, smul_mul_assoc, mul_comm] }, { intros i j k, apply finset.le_max', exact finset.mem_image.mpr ⟨⟨i, j, k⟩, finset.mem_univ _, rfl⟩ }, end /-- If the `R`-integral element `a : S` has coordinates `< y` with respect to some basis `b`, its norm is strictly less than `norm_bound abv b * y ^ dim S`. -/ lemma norm_lt {T : Type*} [linear_ordered_comm_ring T] (a : S) {y : T} (hy : ∀ k, (abv (bS.repr a k) : T) < y) : (abv (algebra.norm R a) : T) < norm_bound abv bS * y ^ fintype.card ι := begin obtain ⟨i⟩ := bS.index_nonempty, have him : (finset.univ.image (λ k, abv (bS.repr a k))).nonempty := ⟨_, finset.mem_image.mpr ⟨i, finset.mem_univ _, rfl⟩⟩, set y' : ℤ := finset.max' _ him with y'_def, have hy' : ∀ k, abv (bS.repr a k) ≤ y', { intro k, exact finset.le_max' _ _ (finset.mem_image.mpr ⟨k, finset.mem_univ _, rfl⟩) }, have : (y' : T) < y, { rw [y'_def, ← finset.max'_image (show monotone (coe : ℤ → T), from λ x y h, int.cast_le.mpr h)], apply (finset.max'_lt_iff _ (him.image _)).mpr, simp only [finset.mem_image, exists_prop], rintros _ ⟨x, ⟨k, -, rfl⟩, rfl⟩, exact hy k }, have y'_nonneg : 0 ≤ y' := le_trans (abv.nonneg _) (hy' i), apply (int.cast_le.mpr (norm_le abv bS a hy')).trans_lt, simp only [int.cast_mul, int.cast_pow], apply mul_lt_mul' (le_refl _), { exact pow_lt_pow_of_lt_left this (int.cast_nonneg.mpr y'_nonneg) (fintype.card_pos_iff.mpr ⟨i⟩) }, { exact pow_nonneg (int.cast_nonneg.mpr y'_nonneg) _ }, { exact int.cast_pos.mpr (norm_bound_pos abv bS) }, { apply_instance } end /-- A nonzero ideal has an element of minimal norm. -/ lemma exists_min (I : (ideal S)⁰) : ∃ b ∈ (I : ideal S), b ≠ 0 ∧ ∀ c ∈ (I : ideal S), abv (algebra.norm R c) < abv (algebra.norm R b) → c = (0 : S) := begin obtain ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩, min⟩ := @int.exists_least_of_bdd (λ a, ∃ b ∈ (I : ideal S), b ≠ (0 : S) ∧ abv (algebra.norm R b) = a) _ _, { refine ⟨b, b_mem, b_ne_zero, _⟩, intros c hc lt, contrapose! lt with c_ne_zero, exact min _ ⟨c, hc, c_ne_zero, rfl⟩ }, { use 0, rintros _ ⟨b, b_mem, b_ne_zero, rfl⟩, apply abv.nonneg }, { obtain ⟨b, b_mem, b_ne_zero⟩ := (I : ideal S).ne_bot_iff.mp (non_zero_divisors.coe_ne_zero I), exact ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩⟩ } end section is_admissible variables (L) {abv} (adm : abv.is_admissible) include adm /-- If we have a large enough set of elements in `R^ι`, then there will be a pair whose remainders are close together. We'll show that all sets of cardinality at least `cardM bS adm` elements satisfy this condition. The value of `cardM` is not at all optimal: for specific choices of `R`, the minimum cardinality can be exponentially smaller. -/ noncomputable def cardM : ℕ := adm.card (norm_bound abv bS ^ (-1 / (fintype.card ι) : ℝ)) ^ fintype.card ι variables [infinite R] /-- In the following results, we need a large set of distinct elements of `R`. -/ noncomputable def distinct_elems : fin (cardM bS adm).succ ↪ R := function.embedding.trans (fin.coe_embedding _).to_embedding (infinite.nat_embedding R) variables [decidable_eq R] /-- `finset_approx` is a finite set such that each fractional ideal in the integral closure contains an element close to `finset_approx`. -/ noncomputable def finset_approx : finset R := ((finset.univ.product finset.univ) .image (λ (xy : _ × _), distinct_elems bS adm xy.1 - distinct_elems bS adm xy.2)) .erase 0 lemma finset_approx.zero_not_mem : (0 : R) ∉ finset_approx bS adm := finset.not_mem_erase _ _ @[simp] lemma mem_finset_approx {x : R} : x ∈ finset_approx bS adm ↔ ∃ i j, i ≠ j ∧ distinct_elems bS adm i - distinct_elems bS adm j = x := begin simp only [finset_approx, finset.mem_erase, finset.mem_image], split, { rintros ⟨hx, ⟨i, j⟩, _, rfl⟩, refine ⟨i, j, _, rfl⟩, rintro rfl, simpa using hx }, { rintros ⟨i, j, hij, rfl⟩, refine ⟨_, ⟨i, j⟩, finset.mem_product.mpr ⟨finset.mem_univ _, finset.mem_univ _⟩, rfl⟩, rw [ne.def, sub_eq_zero], exact λ h, hij ((distinct_elems bS adm).injective h) } end section real open real local attribute [-instance] real.decidable_eq /-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/ theorem exists_mem_finset_approx (a : S) {b} (hb : b ≠ (0 : R)) : ∃ (q : S) (r ∈ finset_approx bS adm), abv (algebra.norm R (r • a - b • q)) < abv (algebra.norm R (algebra_map R S b)) := begin have dim_pos := fintype.card_pos_iff.mpr bS.index_nonempty, set ε : ℝ := norm_bound abv bS ^ (-1 / (fintype.card ι) : ℝ) with ε_eq, have hε : 0 < ε := real.rpow_pos_of_pos (int.cast_pos.mpr (norm_bound_pos abv bS)) _, have ε_le : (norm_bound abv bS : ℝ) * (abv b • ε) ^ fintype.card ι ≤ (abv b ^ fintype.card ι), { have := norm_bound_pos abv bS, have := abv.nonneg b, rw [ε_eq, algebra.smul_def, ring_hom.eq_int_cast, ← rpow_nat_cast, mul_rpow, ← rpow_mul, div_mul_cancel, rpow_neg_one, mul_left_comm, mul_inv_cancel, mul_one, rpow_nat_cast]; try { norm_cast, linarith }, { apply rpow_nonneg_of_nonneg, norm_cast, linarith } }, let μ : fin (cardM bS adm).succ ↪ R := distinct_elems bS adm, set s := bS.repr a, have s_eq : ∀ i, s i = bS.repr a i := λ i, rfl, set qs := λ j i, (μ j * s i) / b, have q_eq : ∀ j i, qs j i = (μ j * s i) / b := λ i j, rfl, set rs := λ j i, (μ j * s i) % b with r_eq, have r_eq : ∀ j i, rs j i = (μ j * s i) % b := λ i j, rfl, have μ_eq : ∀ i j, μ j * s i = b * qs j i + rs j i, { intros i j, rw [q_eq, r_eq, euclidean_domain.div_add_mod], }, have μ_mul_a_eq : ∀ j, μ j • a = b • ∑ i, qs j i • bS i + ∑ i, rs j i • bS i, { intro j, rw ← bS.sum_repr a, simp only [finset.smul_sum, ← finset.sum_add_distrib], refine finset.sum_congr rfl (λ i _, _), rw [← s_eq, ← mul_smul, μ_eq, add_smul, mul_smul] }, obtain ⟨j, k, j_ne_k, hjk⟩ := adm.exists_approx hε hb (λ j i, μ j * s i), have hjk' : ∀ i, (abv (rs k i - rs j i) : ℝ) < abv b • ε, { simpa only [r_eq] using hjk }, set q := ∑ i, (qs k i - qs j i) • bS i with q_eq, set r := μ k - μ j with r_eq, refine ⟨q, r, (mem_finset_approx bS adm).mpr _, _⟩, { exact ⟨k, j, j_ne_k.symm, rfl⟩ }, have : r • a - b • q = (∑ (x : ι), (rs k x • bS x - rs j x • bS x)), { simp only [r_eq, sub_smul, μ_mul_a_eq, q_eq, finset.smul_sum, ← finset.sum_add_distrib, ← finset.sum_sub_distrib, smul_sub], refine finset.sum_congr rfl (λ x _, _), ring }, rw [this, algebra.norm_algebra_map_of_basis bS, abv.map_pow], refine int.cast_lt.mp ((norm_lt abv bS _ (λ i, lt_of_le_of_lt _ (hjk' i))).trans_le _), { apply le_of_eq, congr, simp_rw [linear_equiv.map_sum, linear_equiv.map_sub, linear_equiv.map_smul, finset.sum_apply', finsupp.sub_apply, finsupp.smul_apply, finset.sum_sub_distrib, basis.repr_self_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq', finset.mem_univ, if_true] }, { exact_mod_cast ε_le }, end include ist iic /-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/ theorem exists_mem_finset_approx' (h : algebra.is_algebraic R L) (a : S) {b : S} (hb : b ≠ 0) : ∃ (q : S) (r ∈ finset_approx bS adm), abv (algebra.norm R (r • a - q * b)) < abv (algebra.norm R b) := begin have inj : function.injective (algebra_map R L), { rw is_scalar_tower.algebra_map_eq R S L, exact (is_integral_closure.algebra_map_injective S R L).comp bS.algebra_map_injective }, obtain ⟨a', b', hb', h⟩ := is_integral_closure.exists_smul_eq_mul h inj a hb, obtain ⟨q, r, hr, hqr⟩ := exists_mem_finset_approx bS adm a' hb', refine ⟨q, r, hr, _⟩, refine lt_of_mul_lt_mul_left _ (show 0 ≤ abv (algebra.norm R (algebra_map R S b')), from abv.nonneg _), refine lt_of_le_of_lt (le_of_eq _) (mul_lt_mul hqr (le_refl _) (abv.pos ((algebra.norm_ne_zero_iff_of_basis bS).mpr hb)) (abv.nonneg _)), rw [← abv.map_mul, ← monoid_hom.map_mul, ← abv.map_mul, ← monoid_hom.map_mul, ← algebra.smul_def, smul_sub b', sub_mul, smul_comm, h, mul_comm b a', algebra.smul_mul_assoc r a' b, algebra.smul_mul_assoc b' q b] end end real lemma prod_finset_approx_ne_zero : algebra_map R S (∏ m in finset_approx bS adm, m) ≠ 0 := begin refine mt ((ring_hom.injective_iff _).mp bS.algebra_map_injective _) _, simp only [finset.prod_eq_zero_iff, not_exists], rintros x hx rfl, exact finset_approx.zero_not_mem bS adm hx end lemma ne_bot_of_prod_finset_approx_mem (J : ideal S) (h : algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ J) : J ≠ ⊥ := (submodule.ne_bot_iff _).mpr ⟨_, h, prod_finset_approx_ne_zero _ _⟩ include ist iic /-- Each class in the class group contains an ideal `J` such that `M := Π m ∈ finset_approx` is in `J`. -/ theorem exists_mk0_eq_mk0 [is_dedekind_domain S] [is_fraction_ring S L] (h : algebra.is_algebraic R L) (I : (ideal S)⁰) : ∃ (J : (ideal S)⁰), class_group.mk0 L I = class_group.mk0 L J ∧ algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ (J : ideal S) := begin set M := ∏ m in finset_approx bS adm, m with M_eq, have hM : algebra_map R S M ≠ 0 := prod_finset_approx_ne_zero bS adm, obtain ⟨b, b_mem, b_ne_zero, b_min⟩ := exists_min abv I, suffices : ideal.span {b} ∣ ideal.span {algebra_map _ _ M} * I.1, { obtain ⟨J, hJ⟩ := this, refine ⟨⟨J, _⟩, _, _⟩, { rw mem_non_zero_divisors_iff_ne_zero, rintro rfl, rw [ideal.zero_eq_bot, ideal.mul_bot] at hJ, exact hM (ideal.span_singleton_eq_bot.mp (I.2 _ hJ)) }, { rw class_group.mk0_eq_mk0_iff, exact ⟨algebra_map _ _ M, b, hM, b_ne_zero, hJ⟩ }, rw [← set_like.mem_coe, ← set.singleton_subset_iff, ← ideal.span_le, ← ideal.dvd_iff_le], refine (mul_dvd_mul_iff_left _).mp _, swap, { exact mt ideal.span_singleton_eq_bot.mp b_ne_zero }, rw [subtype.coe_mk, ideal.dvd_iff_le, ← hJ, mul_comm], apply ideal.mul_mono le_rfl, rw [ideal.span_le, set.singleton_subset_iff], exact b_mem }, rw [ideal.dvd_iff_le, ideal.mul_le], intros r' hr' a ha, rw ideal.mem_span_singleton at ⊢ hr', obtain ⟨q, r, r_mem, lt⟩ := exists_mem_finset_approx' L bS adm h a b_ne_zero, apply @dvd_of_mul_left_dvd _ _ q, simp only [algebra.smul_def] at lt, rw ← sub_eq_zero.mp (b_min _ (I.1.sub_mem (I.1.mul_mem_left _ ha) (I.1.mul_mem_left _ b_mem)) lt), refine mul_dvd_mul_right (dvd_trans (ring_hom.map_dvd _ _) hr') _, exact multiset.dvd_prod (multiset.mem_map.mpr ⟨_, r_mem, rfl⟩) end omit iic ist /-- `class_group.mk_M_mem` is a specialization of `class_group.mk0` to (the finite set of) ideals that contain `M := ∏ m in finset_approx L f abs, m`. By showing this function is surjective, we prove that the class group is finite. -/ noncomputable def mk_M_mem [is_fraction_ring S L] [is_dedekind_domain S] (J : {J : ideal S // algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ J}) : class_group S L := class_group.mk0 _ ⟨J.1, mem_non_zero_divisors_iff_ne_zero.mpr (ne_bot_of_prod_finset_approx_mem bS adm J.1 J.2)⟩ include iic ist lemma mk_M_mem_surjective [is_fraction_ring S L] [is_dedekind_domain S] (h : algebra.is_algebraic R L) : function.surjective (class_group.mk_M_mem L bS adm) := begin intro I', obtain ⟨⟨I, hI⟩, rfl⟩ := class_group.mk0_surjective I', obtain ⟨J, mk0_eq_mk0, J_dvd⟩ := exists_mk0_eq_mk0 L bS adm h ⟨I, hI⟩, exact ⟨⟨J, J_dvd⟩, mk0_eq_mk0.symm⟩ end open_locale classical /-- The main theorem: the class group of an integral closure `S` of `R` in an algebraic extension `L` is finite if there is an admissible absolute value. See also `class_group.fintype_of_admissible_of_finite` where `L` is a finite extension of `K = Frac(R)`, supplying most of the required assumptions automatically. -/ noncomputable def fintype_of_admissible_of_algebraic [is_fraction_ring S L] [is_dedekind_domain S] (h : algebra.is_algebraic R L) : fintype (class_group S L) := @fintype.of_surjective _ _ _ (@fintype.of_equiv _ {J // J ∣ ideal.span ({algebra_map R S (∏ (m : R) in finset_approx bS adm, m)} : set S)} (unique_factorization_monoid.fintype_subtype_dvd _ (by { rw [ne.def, ideal.zero_eq_bot, ideal.span_singleton_eq_bot], exact prod_finset_approx_ne_zero bS adm })) ((equiv.refl _).subtype_equiv (λ I, ideal.dvd_iff_le.trans (by rw [equiv.refl_apply, ideal.span_le, set.singleton_subset_iff])))) (class_group.mk_M_mem L bS adm) (class_group.mk_M_mem_surjective L bS adm h) /-- The main theorem: the class group of an integral closure `S` of `R` in a finite extension `L` of `K = Frac(R)` is finite if there is an admissible absolute value. See also `class_group.fintype_of_admissible_of_algebraic` where `L` is an algebraic extension of `R`, that includes some extra assumptions. -/ noncomputable def fintype_of_admissible_of_finite [is_dedekind_domain R] : fintype (@class_group S L _ _ _ (is_integral_closure.is_fraction_ring_of_finite_extension R K L S)) := begin letI := classical.dec_eq L, letI := is_integral_closure.is_fraction_ring_of_finite_extension R K L S, letI := is_integral_closure.is_dedekind_domain R K L S, choose s b hb_int using finite_dimensional.exists_is_basis_integral R K L, obtain ⟨n, b⟩ := submodule.basis_of_pid_of_le_span _ (is_integral_closure.range_le_span_dual_basis S b hb_int), let bS := b.map ((linear_map.quot_ker_equiv_range _).symm ≪≫ₗ _), refine fintype_of_admissible_of_algebraic L bS adm (λ x, (is_fraction_ring.is_algebraic_iff R K).mpr (algebra.is_algebraic_of_finite x)), { rw linear_map.ker_eq_bot.mpr, { exact submodule.quot_equiv_of_eq_bot _ rfl }, { exact is_integral_closure.algebra_map_injective _ R _ } }, { refine (basis.linear_independent _).restrict_scalars _, simp only [algebra.smul_def, mul_one], apply is_fraction_ring.injective } end end is_admissible end euclidean_domain end class_group
307446d928049846fecba307a974c342102d4611
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/quandle.lean
baa05dc737daeef080a51381a803f2398bc5e6de
[ "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
24,719
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.zmod.basic import data.equiv.mul_add import tactic.group /-! # Racks and Quandles This file defines racks and quandles, algebraic structures for sets that bijectively act on themselves with a self-distributivity property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action, then the self-distributivity is, equivalently, that ``` act (act x y) = act x * act y * (act x)⁻¹ ``` where multiplication is composition in `R ≃ R` as a group. Quandles are racks such that `act x x = x` for all `x`. One example of a quandle (not yet in mathlib) is the action of a Lie algebra on itself, defined by `act x y = Ad (exp x) y`. Quandles and racks were independently developed by multiple mathematicians. David Joyce introduced quandles in his thesis [Joyce1982] to define an algebraic invariant of knot and link complements that is analogous to the fundamental group of the exterior, and he showed that the quandle associated to an oriented knot is invariant up to orientation-reversed mirror image. Racks were used by Fenn and Rourke for framed codimension-2 knots and links.[FennRourke1992] The name "rack" came from wordplay by Conway and Wraith for the "wrack and ruin" of forgetting everything but the conjugation operation for a group. ## Main definitions * `shelf` is a type with a self-distributive action * `rack` is a shelf whose action for each element is invertible * `quandle` is a rack whose action for an element fixes that element * `quandle.conj` defines a quandle of a group acting on itself by conjugation. * `shelf_hom` is homomorphisms of shelves, racks, and quandles. * `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle. * `rack.opp` gives the rack with the action replaced by its inverse. ## Main statements * `rack.envel_group` is left adjoint to `quandle.conj` (`to_envel_group.map`). The universality statements are `to_envel_group.univ` and `to_envel_group.univ_uniq`. ## Notation The following notation is localized in `quandles`: * `x ◃ y` is `shelf.act x y` * `x ◃⁻¹ y` is `rack.inv_act x y` * `S →◃ S'` is `shelf_hom S S'` Use `open_locale quandles` to use these. ## Todo * If `g` is the Lie algebra of a Lie group `G`, then `(x ◃ y) = Ad (exp x) x` forms a quandle. * If `X` is a symmetric space, then each point has a corresponding involution that acts on `X`, forming a quandle. * Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements of a module over `Z[t,t⁻¹]`. * If `G` is a group, `H` a subgroup, and `z` in `H`, then there is a quandle `(G/H;z)` defined by `yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle `Q` whose automorphism group acts transitively on `Q` as a set) is isomorphic to such a quandle. There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982]. ## Tags rack, quandle -/ open mul_opposite universes u v /-- A *shelf* is a structure with a self-distributive binary operation. The binary operation is regarded as a left action of the type on itself. -/ class shelf (α : Type u) := (act : α → α → α) (self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z)) /-- The type of homomorphisms between shelves. This is also the notion of rack and quandle homomorphisms. -/ @[ext] structure shelf_hom (S₁ : Type*) (S₂ : Type*) [shelf S₁] [shelf S₂] := (to_fun : S₁ → S₂) (map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y)) /-- A *rack* is an automorphic set (a set with an action on itself by bijections) that is self-distributive. It is a shelf such that each element's action is invertible. The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the inverse action, respectively, and they are right associative. -/ class rack (α : Type u) extends shelf α := (inv_act : α → α → α) (left_inv : ∀ x, function.left_inverse (inv_act x) (act x)) (right_inv : ∀ x, function.right_inverse (inv_act x) (act x)) localized "infixr ` ◃ `:65 := shelf.act" in quandles localized "infixr ` ◃⁻¹ `:65 := rack.inv_act" in quandles localized "infixr ` →◃ `:25 := shelf_hom" in quandles open_locale quandles namespace rack variables {R : Type*} [rack R] lemma self_distrib {x y z : R} : x ◃ (y ◃ z) = (x ◃ y) ◃ (x ◃ z) := shelf.self_distrib /-- A rack acts on itself by equivalences. -/ def act (x : R) : R ≃ R := { to_fun := shelf.act x, inv_fun := inv_act x, left_inv := left_inv x, right_inv := right_inv x } @[simp] lemma act_apply (x y : R) : act x y = x ◃ y := rfl @[simp] lemma act_symm_apply (x y : R) : (act x).symm y = x ◃⁻¹ y := rfl @[simp] lemma inv_act_apply (x y : R) : (act x)⁻¹ y = x ◃⁻¹ y := rfl @[simp] lemma inv_act_act_eq (x y : R) : x ◃⁻¹ x ◃ y = y := left_inv x y @[simp] lemma act_inv_act_eq (x y : R) : x ◃ x ◃⁻¹ y = y := right_inv x y lemma left_cancel (x : R) {y y' : R} : x ◃ y = x ◃ y' ↔ y = y' := by { split, apply (act x).injective, rintro rfl, refl } lemma left_cancel_inv (x : R) {y y' : R} : x ◃⁻¹ y = x ◃⁻¹ y' ↔ y = y' := by { split, apply (act x).symm.injective, rintro rfl, refl } lemma self_distrib_inv {x y z : R} : x ◃⁻¹ y ◃⁻¹ z = (x ◃⁻¹ y) ◃⁻¹ (x ◃⁻¹ z) := begin rw [←left_cancel (x ◃⁻¹ y), right_inv, ←left_cancel x, right_inv, self_distrib], repeat {rw right_inv }, end /-- The *adjoint action* of a rack on itself is `op'`, and the adjoint action of `x ◃ y` is the conjugate of the action of `y` by the action of `x`. It is another way to understand the self-distributivity axiom. This is used in the natural rack homomorphism `to_conj` from `R` to `conj (R ≃ R)` defined by `op'`. -/ lemma ad_conj {R : Type*} [rack R] (x y : R) : act (x ◃ y) = act x * act y * (act x)⁻¹ := begin apply @mul_right_cancel _ _ _ (act x), ext z, simp only [inv_mul_cancel_right], apply self_distrib.symm, end /-- The opposite rack, swapping the roles of `◃` and `◃⁻¹`. -/ instance opposite_rack : rack Rᵐᵒᵖ := { act := λ x y, op (inv_act (unop x) (unop y)), self_distrib := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, mul_opposite.rec $ λ z, begin simp only [unop_op, op_inj], exact self_distrib_inv, end, inv_act := λ x y, op (shelf.act (unop x) (unop y)), left_inv := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, by simp, right_inv := mul_opposite.rec $ λ x, mul_opposite.rec $ λ y, by simp } @[simp] lemma op_act_op_eq {x y : R} : (op x) ◃ (op y) = op (x ◃⁻¹ y) := rfl @[simp] lemma op_inv_act_op_eq {x y : R} : (op x) ◃⁻¹ (op y) = op (x ◃ y) := rfl @[simp] lemma self_act_act_eq {x y : R} : (x ◃ x) ◃ y = x ◃ y := by { rw [←right_inv x y, ←self_distrib] } @[simp] lemma self_inv_act_inv_act_eq {x y : R} : (x ◃⁻¹ x) ◃⁻¹ y = x ◃⁻¹ y := by { have h := @self_act_act_eq _ _ (op x) (op y), simpa using h } @[simp] lemma self_act_inv_act_eq {x y : R} : (x ◃ x) ◃⁻¹ y = x ◃⁻¹ y := by { rw ←left_cancel (x ◃ x), rw right_inv, rw self_act_act_eq, rw right_inv } @[simp] lemma self_inv_act_act_eq {x y : R} : (x ◃⁻¹ x) ◃ y = x ◃ y := by { have h := @self_act_inv_act_eq _ _ (op x) (op y), simpa using h } lemma self_act_eq_iff_eq {x y : R} : x ◃ x = y ◃ y ↔ x = y := begin split, swap, rintro rfl, refl, intro h, transitivity (x ◃ x) ◃⁻¹ (x ◃ x), rw [←left_cancel (x ◃ x), right_inv, self_act_act_eq], rw [h, ←left_cancel (y ◃ y), right_inv, self_act_act_eq], end lemma self_inv_act_eq_iff_eq {x y : R} : x ◃⁻¹ x = y ◃⁻¹ y ↔ x = y := by { have h := @self_act_eq_iff_eq _ _ (op x) (op y), simpa using h } /-- The map `x ↦ x ◃ x` is a bijection. (This has applications for the regular isotopy version of the Reidemeister I move for knot diagrams.) -/ def self_apply_equiv (R : Type*) [rack R] : R ≃ R := { to_fun := λ x, x ◃ x, inv_fun := λ x, x ◃⁻¹ x, left_inv := λ x, by simp, right_inv := λ x, by simp } /-- An involutory rack is one for which `rack.op R x` is an involution for every x. -/ def is_involutory (R : Type*) [rack R] : Prop := ∀ x : R, function.involutive (shelf.act x) lemma involutory_inv_act_eq_act {R : Type*} [rack R] (h : is_involutory R) (x y : R) : x ◃⁻¹ y = x ◃ y := begin rw [←left_cancel x, right_inv], exact ((h x).left_inverse y).symm, end /-- An abelian rack is one for which the mediality axiom holds. -/ def is_abelian (R : Type*) [rack R] : Prop := ∀ (x y z w : R), (x ◃ y) ◃ (z ◃ w) = (x ◃ z) ◃ (y ◃ w) /-- Associative racks are uninteresting. -/ lemma assoc_iff_id {R : Type*} [rack R] {x y z : R} : x ◃ y ◃ z = (x ◃ y) ◃ z ↔ x ◃ z = z := by { rw self_distrib, rw left_cancel } end rack namespace shelf_hom variables {S₁ : Type*} {S₂ : Type*} {S₃ : Type*} [shelf S₁] [shelf S₂] [shelf S₃] instance : has_coe_to_fun (S₁ →◃ S₂) (λ _, S₁ → S₂) := ⟨shelf_hom.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : S₁ →◃ S₂) : f.to_fun = f := rfl @[simp] lemma map_act (f : S₁ →◃ S₂) {x y : S₁} : f (x ◃ y) = f x ◃ f y := map_act' f /-- The identity homomorphism -/ def id (S : Type*) [shelf S] : S →◃ S := { to_fun := id, map_act' := by simp } instance inhabited (S : Type*) [shelf S] : inhabited (S →◃ S) := ⟨id S⟩ /-- The composition of shelf homomorphisms -/ def comp (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) : S₁ →◃ S₃ := { to_fun := g.to_fun ∘ f.to_fun, map_act' := by simp } @[simp] lemma comp_apply (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) (x : S₁) : (g.comp f) x = g (f x) := rfl end shelf_hom /-- A quandle is a rack such that each automorphism fixes its corresponding element. -/ class quandle (α : Type*) extends rack α := (fix : ∀ {x : α}, act x x = x) namespace quandle open rack variables {Q : Type*} [quandle Q] attribute [simp] fix @[simp] lemma fix_inv {x : Q} : x ◃⁻¹ x = x := by { rw ←left_cancel x, simp } instance opposite_quandle : quandle Qᵐᵒᵖ := { fix := λ x, by { induction x using mul_opposite.rec, simp } } /-- The conjugation quandle of a group. Each element of the group acts by the corresponding inner automorphism. -/ @[nolint has_inhabited_instance] def conj (G : Type*) := G instance conj.quandle (G : Type*) [group G] : quandle (conj G) := { act := (λ x, @mul_aut.conj G _ x), self_distrib := λ x y z, begin dsimp only [mul_equiv.coe_to_equiv, mul_aut.conj_apply, conj], group, end, inv_act := (λ x, (@mul_aut.conj G _ x).symm), left_inv := λ x y, by { dsimp [act, conj], group }, right_inv := λ x y, by { dsimp [act, conj], group }, fix := λ x, by simp } @[simp] lemma conj_act_eq_conj {G : Type*} [group G] (x y : conj G) : x ◃ y = ((x : G) * (y : G) * (x : G)⁻¹ : G) := rfl lemma conj_swap {G : Type*} [group G] (x y : conj G) : x ◃ y = y ↔ y ◃ x = x := begin dsimp, split, repeat { intro h, conv_rhs { rw eq_mul_inv_of_mul_eq (eq_mul_inv_of_mul_eq h) }, simp, }, end /-- `conj` is functorial -/ def conj.map {G : Type*} {H : Type*} [group G] [group H] (f : G →* H) : conj G →◃ conj H := { to_fun := f, map_act' := by simp } instance {G : Type*} {H : Type*} [group G] [group H] : has_lift (G →* H) (conj G →◃ conj H) := { lift := conj.map } /-- The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips. Used for Fox n-colorings of knots. -/ @[nolint has_inhabited_instance] def dihedral (n : ℕ) := zmod n /-- The operation for the dihedral quandle. It does not need to be an equivalence because it is an involution (see `dihedral_act.inv`). -/ def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n := λ b, 2 * a - b lemma dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) := by { intro b, dsimp [dihedral_act], ring } instance (n : ℕ) : quandle (dihedral n) := { act := dihedral_act n, self_distrib := λ x y z, begin dsimp [function.involutive.to_equiv, dihedral_act], ring, end, inv_act := dihedral_act n, left_inv := λ x, (dihedral_act.inv n x).left_inverse, right_inv := λ x, (dihedral_act.inv n x).right_inverse, fix := λ x, begin dsimp [function.involutive.to_equiv, dihedral_act], ring, end } end quandle namespace rack /-- This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R` that acts on the rack. -/ def to_conj (R : Type*) [rack R] : R →◃ quandle.conj (R ≃ R) := { to_fun := act, map_act' := ad_conj } section envel_group /-! ### Universal enveloping group of a rack The universal enveloping group `envel_group R` of a rack `R` is the universal group such that every rack homomorphism `R →◃ conj G` is induced by a unique group homomorphism `envel_group R →* G`. For quandles, Joyce called this group `AdConj R`. The `envel_group` functor is left adjoint to the `conj` forgetful functor, and the way we construct the enveloping group is via a technique that should work for left adjoints of forgetful functors in general. It involves thinking a little about 2-categories, but the payoff is that the map `envel_group R →* G` has a nice description. Let's think of a group as being a one-object category. The first step is to define `pre_envel_group`, which gives formal expressions for all the 1-morphisms and includes the unit element, elements of `R`, multiplication, and inverses. To introduce relations, the second step is to define `pre_envel_group_rel'`, which gives formal expressions for all 2-morphisms between the 1-morphisms. The 2-morphisms include associativity, multiplication by the unit, multiplication by inverses, compatibility with multiplication and inverses (`congr_mul` and `congr_inv`), the axioms for an equivalence relation, and, importantly, the relationship between conjugation and the rack action (see `rack.ad_conj`). None of this forms a 2-category yet, for example due to lack of associativity of `trans`. The `pre_envel_group_rel` relation is a `Prop`-valued version of `pre_envel_group_rel'`, and making it `Prop`-valued essentially introduces enough 3-isomorphisms so that every pair of compatible 2-morphisms is isomorphic. Now, while composition in `pre_envel_group` does not strictly satisfy the category axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak 2-category. Since we just want a 1-category, the last step is to quotient `pre_envel_group` by `pre_envel_group_rel'`, and the result is the group `envel_group`. For a homomorphism `f : R →◃ conj G`, how does `envel_group.map f : envel_group R →* G` work? Let's think of `G` as being a 2-category with one object, a 1-morphism per element of `G`, and a single 2-morphism called `eq.refl` for each 1-morphism. We define the map using a "higher `quotient.lift`" -- not only do we evaluate elements of `pre_envel_group` as expressions in `G` (this is `to_envel_group.map_aux`), but we evaluate elements of `pre_envel_group'` as expressions of 2-morphisms of `G` (this is `to_envel_group.map_aux.well_def`). That is to say, `to_envel_group.map_aux.well_def` recursively evaluates formal expressions of 2-morphisms as equality proofs in `G`. Now that all morphisms are accounted for, the map descends to a homomorphism `envel_group R →* G`. Note: `Type`-valued relations are not common. The fact it is `Type`-valued is what makes `to_envel_group.map_aux.well_def` have well-founded recursion. -/ /-- Free generators of the enveloping group. -/ inductive pre_envel_group (R : Type u) : Type u | unit : pre_envel_group | incl (x : R) : pre_envel_group | mul (a b : pre_envel_group) : pre_envel_group | inv (a : pre_envel_group) : pre_envel_group instance pre_envel_group.inhabited (R : Type u) : inhabited (pre_envel_group R) := ⟨pre_envel_group.unit⟩ open pre_envel_group /-- Relations for the enveloping group. This is a type-valued relation because `to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map` is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version, which is used to define `envel_group` itself. -/ inductive pre_envel_group_rel' (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Type u | refl {a : pre_envel_group R} : pre_envel_group_rel' a a | symm {a b : pre_envel_group R} (hab : pre_envel_group_rel' a b) : pre_envel_group_rel' b a | trans {a b c : pre_envel_group R} (hab : pre_envel_group_rel' a b) (hbc : pre_envel_group_rel' b c) : pre_envel_group_rel' a c | congr_mul {a b a' b' : pre_envel_group R} (ha : pre_envel_group_rel' a a') (hb : pre_envel_group_rel' b b') : pre_envel_group_rel' (mul a b) (mul a' b') | congr_inv {a a' : pre_envel_group R} (ha : pre_envel_group_rel' a a') : pre_envel_group_rel' (inv a) (inv a') | assoc (a b c : pre_envel_group R) : pre_envel_group_rel' (mul (mul a b) c) (mul a (mul b c)) | one_mul (a : pre_envel_group R) : pre_envel_group_rel' (mul unit a) a | mul_one (a : pre_envel_group R) : pre_envel_group_rel' (mul a unit) a | mul_left_inv (a : pre_envel_group R) : pre_envel_group_rel' (mul (inv a) a) unit | act_incl (x y : R) : pre_envel_group_rel' (mul (mul (incl x) (incl y)) (inv (incl x))) (incl (x ◃ y)) instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] : inhabited (pre_envel_group_rel' R unit unit) := ⟨pre_envel_group_rel'.refl⟩ /-- The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`. -/ inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop | rel {a b : pre_envel_group R} (r : pre_envel_group_rel' R a b) : pre_envel_group_rel a b /-- A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`. -/ lemma pre_envel_group_rel'.rel {R : Type u} [rack R] {a b : pre_envel_group R} : pre_envel_group_rel' R a b → pre_envel_group_rel R a b := pre_envel_group_rel.rel @[refl] lemma pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} : pre_envel_group_rel R a a := pre_envel_group_rel.rel pre_envel_group_rel'.refl @[symm] lemma pre_envel_group_rel.symm {R : Type u} [rack R] {a b : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b a | ⟨r⟩ := r.symm.rel @[trans] lemma pre_envel_group_rel.trans {R : Type u} [rack R] {a b c : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c | ⟨rab⟩ ⟨rbc⟩ := (rab.trans rbc).rel instance pre_envel_group.setoid (R : Type*) [rack R] : setoid (pre_envel_group R) := { r := pre_envel_group_rel R, iseqv := begin split, apply pre_envel_group_rel.refl, split, apply pre_envel_group_rel.symm, apply pre_envel_group_rel.trans end } /-- The universal enveloping group for the rack R. -/ def envel_group (R : Type*) [rack R] := quotient (pre_envel_group.setoid R) -- Define the `group` instances in two steps so `inv` can be inferred correctly. -- TODO: is there a non-invasive way of defining the instance directly? instance (R : Type*) [rack R] : div_inv_monoid (envel_group R) := { mul := λ a b, quotient.lift_on₂ a b (λ a b, ⟦pre_envel_group.mul a b⟧) (λ a b a' b' ⟨ha⟩ ⟨hb⟩, quotient.sound (pre_envel_group_rel'.congr_mul ha hb).rel), one := ⟦unit⟧, inv := λ a, quotient.lift_on a (λ a, ⟦pre_envel_group.inv a⟧) (λ a a' ⟨ha⟩, quotient.sound (pre_envel_group_rel'.congr_inv ha).rel), mul_assoc := λ a b c, quotient.induction_on₃ a b c (λ a b c, quotient.sound (pre_envel_group_rel'.assoc a b c).rel), one_mul := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.one_mul a).rel), mul_one := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_one a).rel),} instance (R : Type*) [rack R] : group (envel_group R) := { mul_left_inv := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_left_inv a).rel), .. envel_group.div_inv_monoid _ } instance envel_group.inhabited (R : Type*) [rack R] : inhabited (envel_group R) := ⟨1⟩ /-- The canonical homomorphism from a rack to its enveloping group. Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`. -/ def to_envel_group (R : Type*) [rack R] : R →◃ quandle.conj (envel_group R) := { to_fun := λ x, ⟦incl x⟧, map_act' := λ x y, quotient.sound (pre_envel_group_rel'.act_incl x y).symm.rel } /-- The preliminary definition of the induced map from the enveloping group. See `to_envel_group.map`. -/ def to_envel_group.map_aux {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) : pre_envel_group R → G | unit := 1 | (incl x) := f x | (mul a b) := to_envel_group.map_aux a * to_envel_group.map_aux b | (inv a) := (to_envel_group.map_aux a)⁻¹ namespace to_envel_group.map_aux open pre_envel_group_rel' /-- Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms. -/ lemma well_def {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) : Π {a b : pre_envel_group R}, pre_envel_group_rel' R a b → to_envel_group.map_aux f a = to_envel_group.map_aux f b | a b refl := rfl | a b (symm h) := (well_def h).symm | a b (trans hac hcb) := eq.trans (well_def hac) (well_def hcb) | _ _ (congr_mul ha hb) := by { simp [to_envel_group.map_aux, well_def ha, well_def hb] } | _ _ (congr_inv ha) := by { simp [to_envel_group.map_aux, well_def ha] } | _ _ (assoc a b c) := by { apply mul_assoc } | _ _ (one_mul a) := by { simp [to_envel_group.map_aux] } | _ _ (mul_one a) := by { simp [to_envel_group.map_aux] } | _ _ (mul_left_inv a) := by { simp [to_envel_group.map_aux] } | _ _ (act_incl x y) := by { simp [to_envel_group.map_aux] } end to_envel_group.map_aux /-- Given a map from a rack to a group, lift it to being a map from the enveloping group. More precisely, the `envel_group` functor is left adjoint to `quandle.conj`. -/ def to_envel_group.map {R : Type*} [rack R] {G : Type*} [group G] : (R →◃ quandle.conj G) ≃ (envel_group R →* G) := { to_fun := λ f, { to_fun := λ x, quotient.lift_on x (to_envel_group.map_aux f) (λ a b ⟨hab⟩, to_envel_group.map_aux.well_def f hab), map_one' := begin change quotient.lift_on ⟦unit⟧ (to_envel_group.map_aux f) _ = 1, simp [to_envel_group.map_aux], end, map_mul' := λ x y, quotient.induction_on₂ x y (λ x y, begin change quotient.lift_on ⟦mul x y⟧ (to_envel_group.map_aux f) _ = _, simp [to_envel_group.map_aux], end) }, inv_fun := λ F, (quandle.conj.map F).comp (to_envel_group R), left_inv := λ f, by { ext, refl }, right_inv := λ F, monoid_hom.ext $ λ x, quotient.induction_on x $ λ x, begin induction x, { exact F.map_one.symm, }, { refl, }, { have hm : ⟦x_a.mul x_b⟧ = @has_mul.mul (envel_group R) _ ⟦x_a⟧ ⟦x_b⟧ := rfl, rw [hm, F.map_mul, monoid_hom.map_mul, ←x_ih_a, ←x_ih_b] }, { have hm : ⟦x_a.inv⟧ = @has_inv.inv (envel_group R) _ ⟦x_a⟧ := rfl, rw [hm, F.map_inv, monoid_hom.map_inv, x_ih], } end, } /-- Given a homomorphism from a rack to a group, it factors through the enveloping group. -/ lemma to_envel_group.univ (R : Type*) [rack R] (G : Type*) [group G] (f : R →◃ quandle.conj G) : (quandle.conj.map (to_envel_group.map f)).comp (to_envel_group R) = f := to_envel_group.map.symm_apply_apply f /-- The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative triangle in `to_envel_group.univ`. -/ lemma to_envel_group.univ_uniq (R : Type*) [rack R] (G : Type*) [group G] (f : R →◃ quandle.conj G) (g : envel_group R →* G) (h : f = (quandle.conj.map g).comp (to_envel_group R)) : g = to_envel_group.map f := h.symm ▸ (to_envel_group.map.apply_symm_apply g).symm /-- The induced group homomorphism from the enveloping group into bijections of the rack, using `rack.to_conj`. Satisfies the property `envel_action_prop`. This gives the rack `R` the structure of an augmented rack over `envel_group R`. -/ def envel_action {R : Type*} [rack R] : envel_group R →* (R ≃ R) := to_envel_group.map (to_conj R) @[simp] lemma envel_action_prop {R : Type*} [rack R] (x y : R) : envel_action (to_envel_group R x) y = x ◃ y := rfl end envel_group end rack
c8701e2fd418c8e9e74e9fb578651b5a114bab5d
5719a16e23dfc08cdea7a5bf035b81690f307965
/src/Init/Lean/Parser/Term.lean
3e0f5593aee38e884d23bcd3aacf83e6f74ed583
[ "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
13,361
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Parser.Parser import Init.Lean.Parser.Level namespace Lean namespace Parser @[init] def regBuiltinTacticParserAttr : IO Unit := let leadingIdentAsSymbol := true; registerBuiltinParserAttribute `builtinTacticParser `tactic leadingIdentAsSymbol @[init] def regTacticParserAttribute : IO Unit := registerBuiltinDynamicParserAttribute `tacticParser `tactic @[inline] def tacticParser (rbp : Nat := 0) : Parser := categoryParser `tactic rbp def Tactic.seq : Parser := node `Lean.Parser.Tactic.seq $ sepBy tacticParser "; " true def Tactic.nonEmptySeq : Parser := node `Lean.Parser.Tactic.seq $ sepBy1 tacticParser "; " true def darrow : Parser := "=>" namespace Term /- Helper functions for defining simple parsers -/ def unicodeInfixR (sym : String) (asciiSym : String) (lbp : Nat) : TrailingParser := unicodeSymbol sym asciiSym lbp >> termParser (lbp - 1) def infixR (sym : String) (lbp : Nat) : TrailingParser := symbol sym lbp >> termParser (lbp - 1) def unicodeInfixL (sym : String) (asciiSym : String) (lbp : Nat) : TrailingParser := unicodeSymbol sym asciiSym lbp >> termParser lbp def infixL (sym : String) (lbp : Nat) : TrailingParser := symbol sym lbp >> termParser lbp def leadPrec := appPrec - 1 /- Built-in parsers -/ -- NOTE: `checkNoWsBefore` should be used *before* `parser!` so that it is also applied to the generated -- antiquotation. def explicitUniv := checkNoWsBefore "no space before '.{'" >> parser! ".{" >> sepBy1 levelParser ", " >> "}" def namedPattern := checkNoWsBefore "no space before '@'" >> parser! "@" >> termParser appPrec @[builtinTermParser] def id := parser! ident >> optional (explicitUniv <|> namedPattern) @[builtinTermParser] def num : Parser := parser! numLit @[builtinTermParser] def str : Parser := parser! strLit @[builtinTermParser] def char : Parser := parser! charLit @[builtinTermParser] def type := parser! symbol "Type" appPrec @[builtinTermParser] def sort := parser! symbol "Sort" appPrec @[builtinTermParser] def prop := parser! symbol "Prop" appPrec @[builtinTermParser] def hole := parser! symbol "_" appPrec @[builtinTermParser] def namedHole := parser! symbol "?" appPrec >> ident @[builtinTermParser] def «sorry» := parser! symbol "sorry" appPrec @[builtinTermParser] def cdot := parser! symbol "·" appPrec @[builtinTermParser] def emptyC := parser! symbol "∅" appPrec def typeAscription := parser! " : " >> termParser def tupleTail := parser! ", " >> sepBy1 termParser ", " def parenSpecial : Parser := optional (tupleTail <|> typeAscription) @[builtinTermParser] def paren := parser! symbol "(" appPrec >> optional (termParser >> parenSpecial) >> ")" @[builtinTermParser] def anonymousCtor := parser! symbol "⟨" appPrec >> sepBy termParser ", " >> "⟩" def optIdent : Parser := optional (try (ident >> " : ")) @[builtinTermParser] def «if» := parser! symbol "if " leadPrec >> optIdent >> termParser >> " then " >> termParser >> " else " >> termParser def fromTerm := parser! " from " >> termParser def haveAssign := parser! " := " >> termParser @[builtinTermParser] def «have» := parser! symbol "have " leadPrec >> optIdent >> termParser >> (haveAssign <|> fromTerm) >> "; " >> termParser @[builtinTermParser] def «suffices» := parser! symbol "suffices " leadPrec >> optIdent >> termParser >> fromTerm >> "; " >> termParser @[builtinTermParser] def «show» := parser! symbol "show " leadPrec >> termParser >> fromTerm def structInstArrayRef := parser! "[" >> termParser >>"]" def structInstLVal := (ident <|> fieldIdx <|> structInstArrayRef) >> many (group ("." >> (ident <|> fieldIdx)) <|> structInstArrayRef) def structInstField := parser! structInstLVal >> " := " >> termParser def structInstSource := parser! ".." >> optional termParser @[builtinTermParser] def structInst := parser! symbol "{" appPrec >> optional (try (ident >> checkWsBefore "expected space '.'" >> " . ")) >> sepBy (structInstField <|> structInstSource) ", " true >> "}" def typeSpec := parser! " : " >> termParser def optType : Parser := optional typeSpec @[builtinTermParser] def subtype := parser! "{" >> ident >> optType >> " // " >> termParser >> "}" @[builtinTermParser] def listLit := parser! symbol "[" appPrec >> sepBy termParser "," true >> "]" @[builtinTermParser] def arrayLit := parser! symbol "#[" appPrec >> sepBy termParser "," true >> "]" @[builtinTermParser] def explicit := parser! symbol "@" appPrec >> termParser appPrec @[builtinTermParser] def inaccessible := parser! symbol ".(" appPrec >> termParser >> ")" def binderIdent : Parser := ident <|> hole def binderType (requireType := false) : Parser := if requireType then group (" : " >> termParser) else optional (" : " >> termParser) def binderTactic := parser! try (" := " >> " by ") >> Tactic.nonEmptySeq def binderDefault := parser! " := " >> termParser def explicitBinder (requireType := false) := parser! "(" >> many1 binderIdent >> binderType requireType >> optional (binderTactic <|> binderDefault) >> ")" def implicitBinder (requireType := false) := parser! "{" >> many1 binderIdent >> binderType requireType >> "}" def instBinder := parser! "[" >> optIdent >> termParser >> "]" def bracketedBinder (requireType := false) := explicitBinder requireType <|> implicitBinder requireType <|> instBinder @[builtinTermParser] def depArrow := parser! bracketedBinder true >> checkRBPGreater 25 "expected parentheses around dependent arrow" >> unicodeSymbol " → " " -> " >> termParser def simpleBinder := parser! many1 binderIdent @[builtinTermParser] def «forall» := parser! unicodeSymbol "∀" "forall" leadPrec >> many1 (simpleBinder <|> bracketedBinder) >> ", " >> termParser def funBinder : Parser := implicitBinder <|> instBinder <|> termParser appPrec @[builtinTermParser] def «fun» := parser! unicodeSymbol "λ" "fun" leadPrec >> many1 funBinder >> darrow >> termParser def matchAlt : Parser := nodeWithAntiquot "matchAlt" `Lean.Parser.Term.matchAlt $ sepBy1 termParser ", " >> darrow >> termParser def matchAlts (optionalFirstBar := true) : Parser := withPosition $ fun pos => (if optionalFirstBar then optional "|" else "|") >> sepBy1 matchAlt (checkColGe pos.column "alternatives must be indented" >> "|") @[builtinTermParser] def «match» := parser! symbol "match " leadPrec >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermParser] def «nomatch» := parser! symbol "nomatch " leadPrec >> termParser @[builtinTermParser] def «parser!» := parser! symbol "parser! " leadPrec >> termParser @[builtinTermParser] def «tparser!» := parser! symbol "tparser! " leadPrec >> termParser @[builtinTermParser] def borrowed := parser! symbol "@&" appPrec >> termParser (appPrec - 1) @[builtinTermParser] def quotedName := parser! nameLit -- NOTE: syntax quotations are defined in Init.Lean.Parser.Command @[builtinTermParser] def «match_syntax» := parser! symbol "match_syntax" leadPrec >> termParser >> " with " >> matchAlts /- Remark: we use `checkWsBefore` to ensure `let x[i] := e; b` is not parsed as `let x [i] := e; b` where `[i]` is an `instBinder`. -/ def letIdLhs : Parser := ident >> checkWsBefore "expected space before binders" >> many bracketedBinder >> optType def letIdDecl : Parser := nodeWithAntiquot "letDecl" `Lean.Parser.Term.letDecl $ try (letIdLhs >> " := ") >> termParser def letPatDecl : Parser := node `Lean.Parser.Term.letDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser def letEqnsDecl : Parser := node `Lean.Parser.Term.letDecl $ letIdLhs >> matchAlts false def letDecl := letIdDecl <|> letPatDecl <|> letEqnsDecl @[builtinTermParser] def «let» := parser! symbol "let " leadPrec >> letDecl >> "; " >> termParser @[builtinTermParser] def «let!» := parser! symbol "let! " leadPrec >> letDecl >> "; " >> termParser def leftArrow : Parser := unicodeSymbol " ← " " <- " def doLet := parser! "let " >> letDecl def doId := parser! try (ident >> optType >> leftArrow) >> termParser def doPat := parser! try (termParser >> leftArrow) >> termParser >> optional (" | " >> termParser) def doExpr := parser! termParser def doElem := doLet <|> doId <|> doPat <|> doExpr def doSeq := sepBy1 doElem "; " def bracketedDoSeq := parser! "{" >> doSeq >> "}" @[builtinTermParser] def liftMethod := parser! leftArrow >> termParser @[builtinTermParser] def «do» := parser! symbol "do " leadPrec >> (bracketedDoSeq <|> doSeq) @[builtinTermParser] def nativeRefl := parser! "nativeRefl! " >> termParser appPrec @[builtinTermParser] def nativeDecide := parser! "nativeDecide! " >> termParser appPrec @[builtinTermParser] def decide := parser! "decide! " >> termParser appPrec @[builtinTermParser] def not := parser! symbol "¬" appPrec >> termParser 40 @[builtinTermParser] def bnot := parser! symbol "!" appPrec >> termParser 40 @[builtinTermParser] def uminus := parser! "-" >> termParser 100 def namedArgument := parser! try ("(" >> ident >> " := ") >> termParser >> ")" @[builtinTermParser] def app := tparser! many1 (namedArgument <|> termParser appPrec) def checkIsSort := checkStackTop (fun stx => stx.isOfKind `Lean.Parser.Term.type || stx.isOfKind `Lean.Parser.Term.sort) @[builtinTermParser] def sortApp := tparser! checkIsSort >> levelParser appPrec @[builtinTermParser] def proj := tparser! symbolNoWs "." (appPrec+1) >> (fieldIdx <|> ident) @[builtinTermParser] def arrow := tparser! unicodeInfixR " → " " -> " 25 @[builtinTermParser] def arrayRef := tparser! symbolNoWs "[" (appPrec+1) >> termParser >>"]" @[builtinTermParser] def dollar := tparser! try (dollarSymbol >> checkWsBefore "space expected") >> termParser 0 @[builtinTermParser] def dollarProj := tparser! symbol "$." 1 >> (fieldIdx <|> ident) @[builtinTermParser] def «where» := tparser! symbol " where " 1 >> sepBy1 letDecl (group ("; " >> " where ")) @[builtinTermParser] def fcomp := tparser! infixR " ∘ " 90 @[builtinTermParser] def prod := tparser! infixR " × " 35 @[builtinTermParser] def add := tparser! infixL " + " 65 @[builtinTermParser] def sub := tparser! infixL " - " 65 @[builtinTermParser] def mul := tparser! infixL " * " 70 @[builtinTermParser] def div := tparser! infixL " / " 70 @[builtinTermParser] def mod := tparser! infixL " % " 70 @[builtinTermParser] def modN := tparser! infixL " %ₙ " 70 @[builtinTermParser] def pow := tparser! infixR " ^ " 80 @[builtinTermParser] def le := tparser! unicodeInfixL " ≤ " " <= " 50 @[builtinTermParser] def ge := tparser! unicodeInfixL " ≥ " " >= " 50 @[builtinTermParser] def lt := tparser! infixL " < " 50 @[builtinTermParser] def gt := tparser! infixL " > " 50 @[builtinTermParser] def eq := tparser! infixL " = " 50 @[builtinTermParser] def ne := tparser! infixL " ≠ " 50 @[builtinTermParser] def beq := tparser! infixL " == " 50 @[builtinTermParser] def bne := tparser! infixL " != " 50 @[builtinTermParser] def heq := tparser! unicodeInfixL " ≅ " " ~= " 50 @[builtinTermParser] def equiv := tparser! infixL " ≈ " 50 @[builtinTermParser] def subst := tparser! symbol " ▸ " 75 >> sepBy1 (termParser 75) " ▸ " @[builtinTermParser] def and := tparser! unicodeInfixR " ∧ " " /\\ " 35 @[builtinTermParser] def or := tparser! unicodeInfixR " ∨ " " \\/ " 30 @[builtinTermParser] def iff := tparser! unicodeInfixL " ↔ " " <-> " 20 @[builtinTermParser] def band := tparser! infixL " && " 35 @[builtinTermParser] def bor := tparser! infixL " || " 30 @[builtinTermParser] def append := tparser! infixL " ++ " 65 @[builtinTermParser] def cons := tparser! infixR " :: " 67 @[builtinTermParser] def orelse := tparser! infixR " <|> " 2 @[builtinTermParser] def orM := tparser! infixR " <||> " 30 @[builtinTermParser] def andM := tparser! infixR " <&&> " 35 @[builtinTermParser] def andthen := tparser! infixR " >> " 60 @[builtinTermParser] def bindOp := tparser! infixR " >>= " 55 @[builtinTermParser] def mapRev := tparser! infixR " <&> " 100 @[builtinTermParser] def seq := tparser! infixL " <*> " 60 @[builtinTermParser] def seqLeft := tparser! infixL " <* " 60 @[builtinTermParser] def seqRight := tparser! infixR " *> " 60 @[builtinTermParser] def map := tparser! infixR " <$> " 100 @[builtinTermParser] def mapConst := tparser! infixR " <$ " 100 @[builtinTermParser] def mapConstRev := tparser! infixR " $> " 100 @[builtinTermParser] def tacticBlock := parser! symbol "begin " appPrec >> Tactic.seq >> "end" @[builtinTermParser] def byTactic := parser! symbol "by " leadPrec >> Tactic.nonEmptySeq -- Use `unboxSingleton` trick similar to the one used at Command.lean for `Term.stxQuot` @[builtinTermParser] def tacticStxQuot : Parser := node `Lean.Parser.Term.stxQuot $ symbol "`(tactic|" appPrec >> sepBy1 tacticParser "; " true true >> ")" @[builtinTermParser] def levelStxQuot : Parser := node `Lean.Parser.Term.stxQuot $ symbol "`(level|" appPrec >> levelParser >> ")" @[builtinTermParser] def funBinderStxQuot : Parser := node `Lean.Parser.Term.stxQuot $ symbol "`(funBinder|" appPrec >> funBinder >> ")" end Term end Parser end Lean
e4ebc2d6c33641c97912e33a36997f378b599143
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/real/cardinality.lean
01b2b377f62417248aa941859ef6b88c602a13da
[ "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
4,890
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The cardinality of the reals. -/ import data.real.basic set_theory.ordinal analysis.specific_limits data.rat.denumerable open nat set noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, _root_.pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply (summable_geometric h1 h2).summable_of_eq_zero_or_self, intro n, cases h : f n; simp [h] end def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑ n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl end lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply lt_trans h2, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max), apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c / (1 - c) < 1, { rw [div_lt_one_iff_lt, lt_sub_iff_add_lt], { convert add_lt_add h2 h2, norm_num }, rwa sub_pos }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ←tsum_geometric (le_of_lt h1) h3], apply zero_add }, { apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }}, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end lemma injective_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end lemma mk_real : mk ℝ = 2 ^ omega.{0} := begin apply le_antisymm, { dsimp [real], apply le_trans mk_quotient_le, apply le_trans (mk_subtype_le _), rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] }, { convert mk_le_of_injective (injective_cantor_function _ _), rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num } end lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [countable_iff, not_le, mk_univ, mk_real], apply cantor } end cardinal
6e721543c2f71137fa309ac690198c349d89ef80
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/order/hom/esakia.lean
ad18a06dbb155b574834062caeea130dbc13dc4b
[ "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
11,487
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.hom.bounded import topology.order.hom.basic /-! # Esakia morphisms This file defines pseudo-epimorphisms and Esakia morphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `pseudo_epimorphism`: Pseudo-epimorphisms. Maps `f` such that `f a ≤ b` implies the existence of `a'` such that `a ≤ a'` and `f a' = b`. * `esakia_hom`: Esakia morphisms. Continuous pseudo-epimorphisms. ## Typeclasses * `pseudo_epimorphism_class` * `esakia_hom_class` ## References * [Wikipedia, *Esakia space*](https://en.wikipedia.org/wiki/Esakia_space) -/ open function variables {F α β γ δ : Type*} /-- The type of pseudo-epimorphisms, aka p-morphisms, aka bounded maps, from `α` to `β`. -/ structure pseudo_epimorphism (α β : Type*) [preorder α] [preorder β] extends α →o β := (exists_map_eq_of_map_le' ⦃a : α⦄ ⦃b : β⦄ : to_fun a ≤ b → ∃ c, a ≤ c ∧ to_fun c = b) /-- The type of Esakia morphisms, aka continuous pseudo-epimorphisms, from `α` to `β`. -/ structure esakia_hom (α β : Type*) [topological_space α] [preorder α] [topological_space β] [preorder β] extends α →Co β := (exists_map_eq_of_map_le' ⦃a : α⦄ ⦃b : β⦄ : to_fun a ≤ b → ∃ c, a ≤ c ∧ to_fun c = b) section set_option old_structure_cmd true /-- `pseudo_epimorphism_class F α β` states that `F` is a type of `⊔`-preserving morphisms. You should extend this class when you extend `pseudo_epimorphism`. -/ class pseudo_epimorphism_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] extends rel_hom_class F ((≤) : α → α → Prop) ((≤) : β → β → Prop) := (exists_map_eq_of_map_le (f : F) ⦃a : α⦄ ⦃b : β⦄ : f a ≤ b → ∃ c, a ≤ c ∧ f c = b) /-- `esakia_hom_class F α β` states that `F` is a type of lattice morphisms. You should extend this class when you extend `esakia_hom`. -/ class esakia_hom_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [preorder α] [topological_space β] [preorder β] extends continuous_order_hom_class F α β := (exists_map_eq_of_map_le (f : F) ⦃a : α⦄ ⦃b : β⦄ : f a ≤ b → ∃ c, a ≤ c ∧ f c = b) end export pseudo_epimorphism_class (exists_map_eq_of_map_le) @[priority 100] -- See note [lower instance priority] instance pseudo_epimorphism_class.to_top_hom_class [partial_order α] [order_top α] [preorder β] [order_top β] [pseudo_epimorphism_class F α β] : top_hom_class F α β := { map_top := λ f, let ⟨b, h⟩ := exists_map_eq_of_map_le f (@le_top _ _ _ $ f ⊤) in by rw [←top_le_iff.1 h.1, h.2] .. ‹pseudo_epimorphism_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_pseudo_epimorphism_class [preorder α] [preorder β] [order_iso_class F α β] : pseudo_epimorphism_class F α β := { exists_map_eq_of_map_le := λ f a b h, ⟨equiv_like.inv f b, (le_map_inv_iff f).2 h, equiv_like.right_inv _ _⟩, .. order_iso_class.to_order_hom_class } @[priority 100] -- See note [lower instance priority] instance esakia_hom_class.to_pseudo_epimorphism_class [topological_space α] [preorder α] [topological_space β] [preorder β] [esakia_hom_class F α β] : pseudo_epimorphism_class F α β := { .. ‹esakia_hom_class F α β› } instance [preorder α] [preorder β] [pseudo_epimorphism_class F α β] : has_coe_t F (pseudo_epimorphism α β) := ⟨λ f, ⟨f, exists_map_eq_of_map_le f⟩⟩ instance [topological_space α] [preorder α] [topological_space β] [preorder β] [esakia_hom_class F α β] : has_coe_t F (esakia_hom α β) := ⟨λ f, ⟨f, exists_map_eq_of_map_le f⟩⟩ /-! ### Pseudo-epimorphisms -/ namespace pseudo_epimorphism variables [preorder α] [preorder β] [preorder γ] [preorder δ] instance : pseudo_epimorphism_class (pseudo_epimorphism α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_rel := λ f, f.monotone', exists_map_eq_of_map_le := pseudo_epimorphism.exists_map_eq_of_map_le' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (pseudo_epimorphism α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : pseudo_epimorphism α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : pseudo_epimorphism α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `pseudo_epimorphism` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : pseudo_epimorphism α β) (f' : α → β) (h : f' = f) : pseudo_epimorphism α β := ⟨f.to_order_hom.copy f' h, by simpa only [h.symm, to_fun_eq_coe] using f.exists_map_eq_of_map_le'⟩ @[simp] lemma coe_copy (f : pseudo_epimorphism α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : pseudo_epimorphism α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `pseudo_epimorphism`. -/ protected def id : pseudo_epimorphism α α := ⟨order_hom.id, λ a b h, ⟨b, h, rfl⟩⟩ instance : inhabited (pseudo_epimorphism α α) := ⟨pseudo_epimorphism.id α⟩ @[simp] lemma coe_id : ⇑(pseudo_epimorphism.id α) = id := rfl @[simp] lemma coe_id_order_hom : (pseudo_epimorphism.id α : α →o α) = order_hom.id := rfl variables {α} @[simp] lemma id_apply (a : α) : pseudo_epimorphism.id α a = a := rfl /-- Composition of `pseudo_epimorphism`s as a `pseudo_epimorphism`. -/ def comp (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) : pseudo_epimorphism α γ := ⟨g.to_order_hom.comp f.to_order_hom, λ a b h₀, begin obtain ⟨b, h₁, rfl⟩ := g.exists_map_eq_of_map_le' h₀, obtain ⟨b, h₂, rfl⟩ := f.exists_map_eq_of_map_le' h₁, exact ⟨b, h₂, rfl⟩, end⟩ @[simp] lemma coe_comp (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) : (g.comp f : α → γ) = g ∘ f := rfl @[simp] lemma coe_comp_order_hom (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) : (g.comp f : α →o γ) = (g : β →o γ).comp f := rfl @[simp] lemma comp_apply (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) (a : α) : (g.comp f) a = g (f a) := rfl @[simp] lemma comp_assoc (h : pseudo_epimorphism γ δ) (g : pseudo_epimorphism β γ) (f : pseudo_epimorphism α β) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma comp_id (f : pseudo_epimorphism α β) : f.comp (pseudo_epimorphism.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : pseudo_epimorphism α β) : (pseudo_epimorphism.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : pseudo_epimorphism β γ} {f : pseudo_epimorphism α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : pseudo_epimorphism β γ} {f₁ f₂ : pseudo_epimorphism α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end pseudo_epimorphism /-! ### Esakia morphisms -/ namespace esakia_hom variables [topological_space α] [preorder α] [topological_space β] [preorder β] [topological_space γ] [preorder γ] [topological_space δ] [preorder δ] /-- Reinterpret an `esakia_hom` as a `pseudo_epimorphism`. -/ def to_pseudo_epimorphism (f : esakia_hom α β) : pseudo_epimorphism α β := { ..f } instance : esakia_hom_class (esakia_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f, obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g, congr' }, map_rel := λ f, f.monotone', map_continuous := λ f, f.continuous_to_fun, exists_map_eq_of_map_le := λ f, f.exists_map_eq_of_map_le' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (esakia_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : esakia_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : esakia_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of an `esakia_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : esakia_hom α β) (f' : α → β) (h : f' = f) : esakia_hom α β := ⟨f.to_continuous_order_hom.copy f' h, by simpa only [h.symm, to_fun_eq_coe] using f.exists_map_eq_of_map_le'⟩ @[simp] lemma coe_copy (f : esakia_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : esakia_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as an `esakia_hom`. -/ protected def id : esakia_hom α α := ⟨continuous_order_hom.id α, λ a b h, ⟨b, h, rfl⟩⟩ instance : inhabited (esakia_hom α α) := ⟨esakia_hom.id α⟩ @[simp] lemma coe_id : ⇑(esakia_hom.id α) = id := rfl @[simp] lemma coe_id_continuous_order_hom : (esakia_hom.id α : α →Co α) = continuous_order_hom.id α := rfl @[simp] lemma coe_id_pseudo_epimorphism : (esakia_hom.id α : pseudo_epimorphism α α) = pseudo_epimorphism.id α := rfl variables {α} @[simp] lemma id_apply (a : α) : esakia_hom.id α a = a := rfl /-- Composition of `esakia_hom`s as an `esakia_hom`. -/ def comp (g : esakia_hom β γ) (f : esakia_hom α β) : esakia_hom α γ := ⟨g.to_continuous_order_hom.comp f.to_continuous_order_hom, λ a b h₀, begin obtain ⟨b, h₁, rfl⟩ := g.exists_map_eq_of_map_le' h₀, obtain ⟨b, h₂, rfl⟩ := f.exists_map_eq_of_map_le' h₁, exact ⟨b, h₂, rfl⟩, end⟩ @[simp] lemma coe_comp (g : esakia_hom β γ) (f : esakia_hom α β) : (g.comp f : α → γ) = g ∘ f := rfl @[simp] lemma comp_apply (g : esakia_hom β γ) (f : esakia_hom α β) (a : α) : (g.comp f) a = g (f a) := rfl @[simp] lemma coe_comp_continuous_order_hom (g : esakia_hom β γ) (f : esakia_hom α β) : (g.comp f : α →Co γ) = (g : β →Co γ).comp f := rfl @[simp] lemma coe_comp_pseudo_epimorphism (g : esakia_hom β γ) (f : esakia_hom α β) : (g.comp f : pseudo_epimorphism α γ) = (g : pseudo_epimorphism β γ).comp f := rfl @[simp] lemma comp_assoc (h : esakia_hom γ δ) (g : esakia_hom β γ) (f : esakia_hom α β) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma comp_id (f : esakia_hom α β) : f.comp (esakia_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : esakia_hom α β) : (esakia_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : esakia_hom β γ} {f : esakia_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : esakia_hom β γ} {f₁ f₂ : esakia_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end esakia_hom
97f025f8eee95df8ffb837a2a03cf96d834b72e9
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/path_connected.lean
cb698e7f8079ea761c681899eae1b87374825870
[ "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
36,578
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.unit_interval import topology.algebra.ordered.proj_Icc import topology.continuous_function.basic /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `set.Icc_extend` that will extend any continuous map `γ : I → X` into a continuous map `Icc_extend zero_le_one γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter unit_interval open filter set function unit_interval variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) extends C(I, X) := (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, λ p, p.to_fun⟩ @[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨⟨x, h11⟩, h12, h13⟩ ⟨⟨.(x), h21⟩, h22, h23⟩ rfl := rfl namespace path @[simp] lemma coe_mk (f : I → X) (h₁ h₂ h₃) : ⇑(mk ⟨f, h₁⟩ h₂ h₃ : path x y) = f := rfl variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous_to_fun @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply : I → X := γ initialize_simps_projections path (to_continuous_map_to_fun → simps.apply, -to_continuous_map) @[simp] lemma coe_to_continuous_map : ⇑γ.to_continuous_map = γ := rfl /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl, simps] def refl (x : X) : path x x := { to_fun := λ t, x, continuous_to_fun := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm, simps] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous_to_fun := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma symm_symm {γ : path x y} : γ.symm.symm = γ := by { ext, simp } @[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [mem_range, path.symm, has_coe_to_fun.coe, coe_fn, unit_interval.symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, mem_iff_one_sub_mem.mp hy, _⟩; convert hxy, simp end /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := Icc_extend zero_le_one γ @[continuity] lemma continuous_extend : continuous γ.extend := γ.continuous.Icc_extend @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := Icc_extend_of_mem _ γ ht lemma extend_zero : γ.extend 0 = x := by simp lemma extend_one : γ.extend 1 = y := by simp @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend t = γ t := Icc_extend_coe _ γ t @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := Icc_extend_range _ γ lemma extend_of_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := (Icc_extend_of_le_left _ _ ht).trans γ.source lemma extend_of_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := (Icc_extend_of_right_le _ _ ht).trans γ.target @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous_to_fun := hf.comp_continuous continuous_subtype_coe subtype.prop, source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous_to_fun := begin refine (continuous.if_le _ _ continuous_id continuous_const (by norm_num)).comp continuous_subtype_coe, -- TODO: the following are provable by `continuity` but it is too slow exacts [γ.continuous_extend.comp (continuous_const.mul continuous_id), γ'.continuous_extend.comp ((continuous_const.mul continuous_id).sub continuous_const)] end, source' := by norm_num, target' := by norm_num } lemma trans_apply (γ : path x y) (γ' : path y z) (t : I) : (γ.trans γ') t = if h : (t : ℝ) ≤ 1/2 then γ ⟨2 * t, (mul_pos_mem_iff zero_lt_two).2 ⟨t.2.1, h⟩⟩ else γ' ⟨2 * t - 1, two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, t.2.2⟩⟩ := show ite _ _ _ = _, by split_ifs; rw extend_extends @[simp] lemma trans_symm (γ : path x y) (γ' : path y z) : (γ.trans γ').symm = γ'.symm.trans γ.symm := begin ext t, simp only [trans_apply, one_div, symm_apply, not_le, comp_app], split_ifs with h h₁ h₂ h₃ h₄; rw [coe_symm_eq] at h, { have ht : (t : ℝ) = 1/2, { linarith [unit_interval.nonneg t, unit_interval.le_one t] }, norm_num [ht] }, { refine congr_arg _ (subtype.ext _), norm_num [sub_sub_assoc_swap, mul_sub] }, { refine congr_arg _ (subtype.ext _), have h : 2 - 2 * (t : ℝ) - 1 = 1 - 2 * t, by linarith, norm_num [mul_sub, h] }, { exfalso, linarith [unit_interval.nonneg t, unit_interval.le_one t] } end @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring_nf, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _ _)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring_nf, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous_to_fun := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous_to_fun := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl @[continuity] lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_symm) @[continuity] lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_Icc) @[continuity] lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp only [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans, (∘)], refine continuous.if_le _ _ (continuous_subtype_coe.comp continuous_snd) continuous_const _, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, { rintros st hst, simp [hst, mul_inv_cancel (@two_ne_zero ℝ _ _)] } end /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous_to_fun := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin simp only [min_def, max_def], norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_of_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_of_le_zero h₄, γ.extend_of_le_zero h₁] }, all_goals { refl } end, target' := begin simp only [min_def, max_def], norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_of_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_of_one_le h₄, γ.extend_of_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ @[continuity] lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := γ.continuous_extend.comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ @[continuity] lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min_def, max_def], split_ifs with h₁ h₂; congr, exact le_antisymm ‹_› ‹_› end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, rw [truncate, coe_mk, max_eq_left this.1, min_eq_left this.2, extend_extends'] end /-! #### Reparametrising a path -/ /-- Given a path `γ` and a function `f : I → I` where `f 0 = 0` and `f 1 = 1`, `γ.reparam f` is the path defined by `γ ∘ f`. -/ def reparam (γ : path x y) (f : I → I) (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : path x y := { to_fun := γ ∘ f, continuous_to_fun := by continuity, source' := by simp [hf₀], target' := by simp [hf₁] } @[simp] lemma coe_to_fun (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : ⇑(γ.reparam f hfcont hf₀ hf₁) = γ ∘ f := rfl @[simp] lemma reparam_id (γ : path x y) : γ.reparam id continuous_id rfl rfl = γ := by { ext, refl } lemma range_reparam (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : range ⇑(γ.reparam f hfcont hf₀ hf₁) = range γ := begin change range (γ ∘ f) = range γ, have : range f = univ, { rw range_iff_surjective, intro t, have h₁ : continuous (Icc_extend (@zero_le_one ℝ _) f), { continuity }, have := intermediate_value_Icc (@zero_le_one ℝ _) h₁.continuous_on, { rw [Icc_extend_left, Icc_extend_right] at this, change Icc (f 0) (f 1) ⊆ _ at this, rw [hf₀, hf₁] at this, rcases this t.2 with ⟨w, hw₁, hw₂⟩, rw Icc_extend_of_mem _ _ hw₁ at hw₂, use [⟨w, hw₁⟩, hw₂] } }, rw [range_comp, this, image_univ], end lemma refl_reparam {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : (refl x).reparam f hfcont hf₀ hf₁ = refl x := begin ext, simp, end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous_to_fun := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, (is_connected_range h.some_path.continuous).subset_connected_component ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use path.refl (p' 0), { split, { rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, congr, ext, rw fin.coe_coe_of_lt hi, norm_cast end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_mem_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_mem_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (is_open.mem_nhds h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_of_mem_comap (is_open.mem_nhds h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
c86d969cf807ec9fadcbf8ecd4f6c3b4d29d1925
9631e35ca5dd719ccc7d3a57ec322fd93d6a0776
/src/noneuclidean_maze/solutions/definition.lean
342c7785b689e243eed64ffd1e14ac9dc90837d8
[]
no_license
kbuzzard/maze-game
123fa47e0262edb6d147178d239a345d847ff147
362ab394ae5218c43b24232aaeef08efc0067eab
refs/heads/master
1,670,131,466,823
1,598,546,702,000
1,598,546,702,000
290,744,081
5
1
null
1,598,546,703,000
1,598,523,538,000
Lean
UTF-8
Lean
false
false
2,071
lean
import tactic /- WWW WABCW WDEFW WGHIW WWW and secret room J -- start in room A -- have to find the secret and get to room J -- W is a temp wall room which we never go into. Can people write computer programs in Lean which solve levels like this? Can people write computer programs in Python which design levels like this? The below is Lean 3 code. Can stuff like this be made to work in Lean 4? I have Lean 4 working on my laptop, it's usable, but you have to learn the emacs interface. Is there any way to make this easier for people wanting to transition from VS Code? -/ /-- Solver docs : Terms of type `maze` are rooms in the game. -/ inductive maze : Type | A /- start -/ | B | C | D | E | F | G | H | I -- other rooms | J -- exit room | W /- temp wall term for when a player hits a wall-/ @[derive has_reflect] inductive direction : Type | north | east | south | west namespace maze /- ABC DEF GHI -/ /-- This is basically the map of the maze -/ def go (d : direction) (m : maze) : maze := direction.rec_on d (maze.rec_on m W W W A B C D E F J W) (maze.rec_on m B C W E F W H I W J W) (maze.rec_on m D E F G H I W W W J W) (maze.rec_on m W A B W D E W J H J W) /-- The predicate of being able to escape from the maze -/ inductive can_escape : maze → Prop | exit : can_escape J | go : ∀ d x, can_escape (go d x) → can_escape x end maze open maze direction open tactic meta def go (d : direction) : tactic unit := `[apply can_escape.go %%d, unfold maze.go, fail_if_success { guard_target can_escape W } <|> fail "You hit a wall!" ] meta def tactic.interactive.n := `[go north] meta def tactic.interactive.s := `[go south] meta def tactic.interactive.e := `[go east] meta def tactic.interactive.w := `[go west] open tactic meta def out : tactic unit := `[apply can_escape.exit <|> fail "you are not at the exit level J"] -- theorem solve : can_escape A := -- begin -- s, -- sorry, -- end -- I have no solver -- meta def xyzzy : tactic unit := sorry -- --`[ {e,n,e,e,out} <|> {n,e,e,out} <|> {e,e,out} <|> {e,out} <|> {out} ]
acdf330f24182bf1945ca8f96494336bbb541a2d
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/wf.lean
d4845d530ade5118f53df78617d82b02d7b5141f
[ "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
9,307
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.relation init.nat init.prod universe variables u v inductive acc {A : Type u} (R : A → A → Prop) : A → Prop | intro : ∀ x, (∀ y, R y x → acc y) → acc x namespace acc variables {A : Type u} {R : A → A → Prop} definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y := acc.rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂ -- dependent elimination for acc attribute [recursor] protected definition drec {C : Π (a : A), acc R a → Type v} (h₁ : Π (x : A) (acx : Π (y : A), R y x → acc R y), (Π (y : A) (ryx : R y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : A} (h₂ : acc R a) : C a h₂ := @acc.rec _ _ (λ (a : A), Π (x : @acc A R a), C a x) (λ x acx ih h₂, h₁ x acx (λ y ryx, ih y ryx (acx y ryx))) _ h₂ h₂ end acc inductive well_founded {A : Type u} (R : A → A → Prop) : Prop | intro : (∀ a, acc R a) → well_founded namespace well_founded definition apply {A : Type u} {R : A → A → Prop} (wf : well_founded R) : ∀ a, acc R a := take a, well_founded.rec_on wf (λ p, p) a section parameters {A : Type u} {R : A → A → Prop} local infix `≺`:50 := R hypothesis Hwf : well_founded R theorem recursion {C : A → Type v} (a : A) (H : Π x, (Π y, y ≺ x → C y) → C x) : C a := acc.rec_on (apply Hwf a) (λ x₁ ac₁ iH, H x₁ iH) theorem induction {C : A → Prop} (a : A) (H : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a := recursion a H variable {C : A → Type v} variable F : Π x, (Π y, y ≺ x → C y) → C x definition fix_F (x : A) (a : acc R x) : C x := acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH) theorem fix_F_eq (x : A) (r : acc R x) : fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)) := acc.drec (λ x r ih, rfl) r end variables {A : Type u} {C : A → Type v} {R : A → A → Prop} -- Well-founded fixpoint definition fix (Hwf : well_founded R) (F : Π x, (Π y, R y x → C y) → C x) (x : A) : C x := fix_F F x (apply Hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq (Hwf : well_founded R) (F : Π x, (Π y, R y x → C y) → C x) (x : A) : fix Hwf F x = F x (λ y h, fix Hwf F y) := fix_F_eq F x (apply Hwf x) end well_founded open well_founded -- Empty relation is well-founded definition empty_wf {A : Type u} : well_founded empty_relation := well_founded.intro (λ (a : A), acc.intro a (λ (b : A) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {A : Type u} {R Q : A → A → Prop} parameters (H₁ : subrelation Q R) parameters (H₂ : well_founded R) definition accessible {a : A} (ac : acc R a) : acc Q a := acc.rec_on ac (λ x ax ih, acc.intro x (λ (y : A) (lt : Q y x), ih y (H₁ lt))) definition wf : well_founded Q := well_founded.intro (λ a, accessible (apply H₂ a)) end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {A : Type u} {B : Type v} {R : B → B → Prop} parameters (f : A → B) parameters (H : well_founded R) private definition acc_aux : ∀ {b : B}, @acc B R b → (∀ (x : A), @eq B (f x) b → @acc A (@inv_image A B R f) x) := @acc.rec B R (λ (b : B), ∀ (x : A), f x = b → acc (inv_image R f) x) (λ (x : B) (acx : ∀ (y : B), R y x → acc R y) (ih : ∀ (y : B), R y x → (λ (b : B), ∀ (x : A), f x = b → acc (inv_image R f) x) y) (z : A) (e : f z = x), acc.intro z (λ (y : A) (lt : inv_image R f y z), @eq.rec B (f z) (λ (x : B), (∀ (y : B), R y x → acc R y) → (∀ (y : B), R y x → (λ (b : B), ∀ (x : A), f x = b → acc (inv_image R f) x) y) → acc (inv_image R f) y) (λ (acx : ∀ (y : B), R y (f z) → @acc B R y) (ih : ∀ (y : B), R y (f z) → (λ (b : B), ∀ (x : A), f x = b → acc (inv_image R f) x) y), ih (f y) lt y (@rfl B (f y))) x e acx ih)) definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a := acc_aux ac a rfl definition wf : well_founded (inv_image R f) := well_founded.intro (λ a, accessible (apply H (f a))) end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {A : Type u} {R : A → A → Prop} local notation `R⁺` := tc R definition accessible : ∀ {z : A}, acc R z → acc (tc R) z := @acc.rec A R (acc (tc R)) (λ (x : A) (acx : ∀ (y : A), R y x → acc R y) (ih : ∀ (y : A), R y x → acc (tc R) y), @acc.intro A (tc R) x (λ (y : A) (rel : tc R y x), @tc.rec A R (λ (y x : A), (∀ (y : A), R y x → acc R y) → (∀ (y : A), R y x → acc (tc R) y) → acc (tc R) y) (λ (a b : A) (rab : R a b) (acx : ∀ (y : A), R y b → acc R y) (ih : ∀ (y : A), R y b → acc (tc R) y), ih a rab) (λ (a b c : A) (rab : tc R a b) (rbc : tc R b c) (ih₁ : (∀ (y : A), R y b → acc R y) → (∀ (y : A), R y b → acc (tc R) y) → acc (tc R) a) (ih₂ : (∀ (y : A), R y c → acc R y) → (∀ (y : A), R y c → acc (tc R) y) → acc (tc R) b) (acx : ∀ (y : A), R y c → acc R y) (ih : ∀ (y : A), R y c → acc (tc R) y), @acc.inv A (@tc A R) b a (ih₂ acx ih) rab) y x rel acx ih)) definition wf (H : well_founded R) : well_founded R⁺ := well_founded.intro (λ a, accessible (apply H a)) end end tc -- less-than is well-founded definition nat.lt_wf : well_founded nat.lt := well_founded.intro (nat.rec (acc.intro 0 (λ n H, absurd H (nat.not_lt_zero n))) (λ n IH, acc.intro (nat.succ n) (λ m H, or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ H)) (λ e, eq.substr e IH) (acc.inv IH)))) definition measure {A : Type u} : (A → ℕ) → A → A → Prop := inv_image lt definition measure_wf {A : Type u} (f : A → ℕ) : well_founded (measure f) := inv_image.wf f nat.lt_wf namespace prod open well_founded section variables {A : Type u} {B : Type v} variable (Ra : A → A → Prop) variable (Rb : B → B → Prop) -- Lexicographical order based on Ra and Rb inductive lex : A × B → A × B → Prop | left : ∀ {a₁ b₁} a₂ b₂, Ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂) | right : ∀ a {b₁ b₂}, Rb b₁ b₂ → lex (a, b₁) (a, b₂) -- Relational product based on Ra and Rb inductive rprod : A × B → A × B → Prop | intro : ∀ {a₁ b₁ a₂ b₂}, Ra a₁ a₂ → Rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂) end section parameters {A : Type u} {B : Type v} parameters {Ra : A → A → Prop} {Rb : B → B → Prop} local infix `≺`:50 := lex Ra Rb definition lex_accessible {a} (aca : acc Ra a) (acb : ∀ b, acc Rb b): ∀ b, acc (lex Ra Rb) (a, b) := acc.rec_on aca (λ xa aca (iHa : ∀ y, Ra y xa → ∀ b, acc (lex Ra Rb) (y, b)), λ b, acc.rec_on (acb b) (λ xb acb (iHb : ∀ y, Rb y xb → acc (lex Ra Rb) (xa, y)), acc.intro (xa, xb) (λ p (lt : p ≺ (xa, xb)), have aux : xa = xa → xb = xb → acc (lex Ra Rb) p, from @prod.lex.rec_on A B Ra Rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex Ra Rb) p₁) p (xa, xb) lt (λ a₁ b₁ a₂ b₂ (H : Ra a₁ a₂) (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a₁, b₁), from have Ra₁ : Ra a₁ xa, from eq.rec_on eq₂ H, iHa a₁ Ra₁ b₁) (λ a b₁ b₂ (H : Rb b₁ b₂) (eq₂ : a = xa) (eq₃ : b₂ = xb), show acc (lex Ra Rb) (a, b₁), from have Rb₁ : Rb b₁ xb, from eq.rec_on eq₃ H, have eq₂' : xa = a, from eq.rec_on eq₂ rfl, eq.rec_on eq₂' (iHb b₁ Rb₁)), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded definition lex_wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (lex Ra Rb) := well_founded.intro (λ p, destruct p (λ a b, lex_accessible (apply Ha a) (well_founded.apply Hb) b)) -- Relational product is a subrelation of the lex definition rprod_sub_lex : ∀ a b, rprod Ra Rb a b → lex Ra Rb a b := λ a b H, prod.rprod.rec_on H (λ a₁ b₁ a₂ b₂ H₁ H₂, lex.left Rb a₂ b₂ H₁) -- The relational product of well founded relations is well-founded definition rprod_wf (Ha : well_founded Ra) (Hb : well_founded Rb) : well_founded (rprod Ra Rb) := subrelation.wf (rprod_sub_lex) (lex_wf Ha Hb) end end prod
85d6a8ebb6a85a2ae0e7d988e207339f4dad79e1
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/number_theory/padics/ring_homs.lean
d134deb8712aa3360d21d5d4240aedb727a69946
[ "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
24,643
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import number_theory.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical namespace padic_int open nat local_ring padic variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.1.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.1.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.nat_cast_mod p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring_nf ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← pow_succ'], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_nat_of_le_succ, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, nat.sub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, gpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw [zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0 } } } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat i j h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ i > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩, simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.1.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := ⟨pow_pos hp_prime.1.pos n⟩, rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← (to_zmod_pow n).map_nat_cast, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
08375ba0cab992d1046d853f725dae38714f8095
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/ext.lean
ecfc27cd9ea66d83e2de4ad3517dd660442ed48c
[ "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
20,008
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Jesse Michael Han -/ import tactic.rcases import data.sum import logic.function.basic universes u₁ u₂ open interactive interactive.types section ext open lean.parser nat tactic declare_trace ext /-- `derive_struct_ext_lemma n` generates two extensionality lemmas based on the equality of all non-propositional projections. On the following: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` `derive_struct_lemma` generates: ```lean lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= open_pis, let args := args.map expr.to_implicit_local_const, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ λ f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s ≠ `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, eq_t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) eq_t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (λ _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", add_decl (declaration.thm decl_n d.univ_params t pr), bs ← bs.mmap infer_type, let rhs := expr.mk_and_lst bs, iff_t ← mk_app `iff [eq_t,rhs], t ← pis (args ++ [x,y]) iff_t, pr ← run_async $ do { (_,pr) ← solve_aux t $ do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, split, solve1 $ do { h ← intro1, hs ← injection h, subst_vars, repeat (refine ``( and.intro _ _ ) >> reflexivity ), done <|> reflexivity }, solve1 $ do { repeat (do refine ``(and_imp.mpr _), h ← intro1, cases h, skip ), h ← intro1, cases h, reflexivity } }, instantiate_mvars pr }, add_decl (declaration.thm (n <.> "ext_iff") d.univ_params t pr), pure decl_n meta def get_ext_subject : expr → tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}" open native meta def saturate_fun : name → tactic expr | (name.mk_numeral 0 name.anonymous) := do v₀ ← mk_mvar, v₁ ← mk_mvar, return $ v₀.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" section performance_hack /-- For performance reasons, it is inadvisable to use `user_attribute.get_param`. The parameter is stored as a reflected expression. When calling `get_param`, the stored parameter is evaluated using `eval_expr`, which first compiles the expression into VM bytecode. The unevaluated expression is available using `user_attribute.get_param_untyped`. In particular, `user_attribute.get_param` MUST NEVER BE USED in the implementation of an attribute cache. This is because calling `eval_expr` disables the attribute cache. There are several possible workarounds: 1. Set a different attribute depending on the parameter. 2. Use your own evaluation function instead of `eval_expr`, such as e.g. `expr.to_nat`. 3. Write your own `has_reflect Param` instance (using a more efficient serialization format). The `user_attribute` code unfortunately checks whether the expression has the correct type, but you can use `` `(id %%e : Param) `` to pretend that your expression `e` has type `Param`. -/ library_note "user attribute parameters" /-! For performance reasons, the parameters of the `@[ext]` attribute are stored in two auxiliary attributes: ```lean attribute [ext thunk] funext -- is turned into attribute [_ext_core (@id name @funext)] thunk attribute [_ext_lemma_core] funext ``` see Note [user attribute parameters] -/ local attribute [semireducible] reflected local attribute [instance, priority 9000] private meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) @[user_attribute] private meta def ext_attr_core : user_attribute (name_map name) name := { name := `_ext_core, descr := "(internal attribute used by ext)", cache_cfg := { dependencies := [], mk_cache := λ ns, ns.mfoldl (λ m n, do ext_l ← ext_attr_core.get_param_untyped n, pure (m.insert n ext_l.app_arg.const_name)) mk_name_map }, parser := failure } end performance_hack /-- Private attribute used to tag extensionality lemmas. -/ @[user_attribute] private meta def ext_lemma_attr_core : user_attribute := { name := `_ext_lemma_core, descr := "(internal attribute used by ext)", parser := failure } /-- Returns the extensionality lemmas in the environment, as a map from structure name to lemma name. -/ meta def get_ext_lemmas : tactic (name_map name) := ext_attr_core.get_cache /-- Returns the extensionality lemmas in the environment, as a list of lemma names. -/ meta def get_ext_lemma_names : tactic (list name) := attribute.get_instances ext_lemma_attr_core.name /-- Marks `lem` as an extensionality lemma corresponding to type constructor `constr`; if `persistent` is true then this is a global attribute, else local. -/ meta def add_ext_lemma (constr lem : name) (persistent : bool) : tactic unit := ext_attr_core.set constr lem persistent >> ext_lemma_attr_core.set lem () persistent /-- Tag lemmas of the form: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ```lean attribute [ext thunk, ext stream] funext ``` Also, the following: ```lean @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ```lean @[ext my_collection] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that is referred to in the lemma statement. ```lean @[ext, ext my_type_synonym] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The `ext` attribute can be applied to a structure to generate its extensionality lemmas: ```lean @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` will generate: ```lean @[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y lemma foo.ext_iff : ∀ {α : Type u_1} (x y : foo α), x = y ↔ x.x = y.x ∧ x.y = y.y ∧ x.z == y.z ∧ x.k = y.k ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute unit (option name) := { name := `ext, descr := "lemmas usable by `ext` tactic", parser := optional ident, before_unset := some $ λ _ _, pure (), after_set := some $ λ n _ b, do add ← extensional_attribute.get_param n, unset_attribute `ext n, e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, match add with | none := add_ext_lemma s n b | some add := equiv_type_constr s add >> add_ext_lemma add n b end } add_tactic_doc { name := "ext", category := doc_category.attr, decl_names := [`extensional_attribute], tags := ["rewrite", "logic"] } /-- When possible, `ext` lemmas are stated without a full set of arguments. As an example, for bundled homs `f`, `g`, and `of`, `f.comp of = g.comp of → f = g` is a better `ext` lemma than `(∀ x, f (of x) = g (of x)) → f = g`, as the former allows a second type-specific extensionality lemmas to be applied to `f.comp of = g.comp of`. If the domain of `of` is `ℕ` or `ℤ` and `of` is a `ring_hom`, such a lemma could then make the goal `f (of 1) = g (of 1)`. For bundled morphisms, there is a `ext` lemma that always applies of the form `(∀ x, ⇑f x = ⇑g x) → f = g`. When adding type-specific `ext` lemmas like the one above, we want these to be tried first. This happens automatically since the type-specific lemmas are inevitably defined later. -/ library_note "partially-applied ext lemmas" -- We mark some existing extensionality lemmas. attribute [ext] array.ext propext function.hfunext attribute [ext thunk] _root_.funext -- This line is equivalent to: -- attribute [ext (→)] _root_.funext -- but (→) is not actually a binary relation with a constant at the head, -- so we use the special name [anon].0 to represent (→). run_cmd add_ext_lemma (name.mk_numeral 0 name.anonymous) ``_root_.funext tt -- We create some extensionality lemmas for existing structures. attribute [ext] ulift namespace plift -- This is stronger than the one generated automatically. @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift -- Conservatively, we'll only add extensionality lemmas for `has_*` structures -- as they become useful. attribute [ext] has_zero @[ext] lemma unit.ext {x y : unit} : x = y := by { cases x, cases y, refl, } @[ext] lemma punit.ext {x y : punit} : x = y := by { cases x, cases y, refl, } namespace tactic /-- Helper structure for `ext` and `ext1`. `lemmas` keeps track of extensionality lemmas applied so far. -/ meta structure ext_state : Type := (patts : list rcases_patt := []) (trace_msg : list string := []) (fuel : option ℕ := none) /-- Helper function for `try_intros`. Additionally populates the `trace_msg` field of `ext_state`. -/ private meta def try_intros_core : state_t ext_state tactic unit := do ⟨patts, trace_msg, fuel⟩ ← get, match patts with | [] := do { es ← state_t.lift intros, when (es.length > 0) $ do let msg := "intros " ++ (" ".intercalate (es.map (λ e, e.local_pp_name.to_string))), modify (λ ⟨patts, trace_msg, fuel⟩, ⟨patts, trace_msg ++ [msg], fuel⟩) } <|> pure () | (x::xs) := do tgt ← state_t.lift (target >>= whnf), when tgt.is_pi $ do state_t.lift (rintro [x]), msg ← state_t.lift (((++) "rintro ") <$> format.to_string <$> x.format ff), modify (λ ⟨_, trace_msg, fuel⟩, ⟨xs, trace_msg ++ [msg], fuel⟩), try_intros_core end /-- Try to introduce as many arguments as possible, using the given patterns to destruct the introduced variables. Returns the unused patterns. -/ meta def try_intros (patts : list rcases_patt) : tactic (list rcases_patt) := let σ := ext_state.mk patts [] none in (ext_state.patts ∘ prod.snd) <$> state_t.run try_intros_core σ /-- Apply one extensionality lemma, and destruct the arguments using the patterns in the ext_state. -/ meta def ext1_core (cfg : apply_cfg := {}) : state_t ext_state tactic unit := do ⟨patts, trace_msg, _⟩ ← get, (new_msgs) ← state_t.lift $ focus1 $ do { m ← get_ext_lemmas, tgt ← target, when_tracing `ext $ trace!"[ext] goal: {tgt}", subject ← get_ext_subject tgt, new_trace_msg ← do { rule ← (m.find subject), if is_trace_enabled_for `ext then trace!"[ext] matched goal to rule: {rule}" >> timetac "[ext] application attempt time" (applyc rule cfg) else applyc rule cfg, pure (["apply " ++ rule.to_string]) } <|> do { ls ← get_ext_lemma_names, let nms := ls.map name.to_string, rule ← (ls.any_of (λ n, (if is_trace_enabled_for `ext then trace!"[ext] trying to apply ext lemma: {n}" >> timetac "[ext] application attempt time" (applyc n cfg) else applyc n cfg) *> pure n)), pure (["apply " ++ rule.to_string]) } <|> (fail format!"no applicable extensionality rule found for {subject}"), pure new_trace_msg }, modify (λ ⟨patts, trace_msg, fuel⟩, ⟨patts, trace_msg ++ new_msgs, fuel⟩), try_intros_core /-- Apply multiple extensionality lemmas, destructing the arguments using the given patterns. -/ meta def ext_core (cfg : apply_cfg := {}) : state_t ext_state tactic unit := do acc@⟨_, _, fuel⟩ ← get, match fuel with | (some 0) := pure () | n := do { ext1_core cfg, modify (λ ⟨patts, lemmas, _⟩, ⟨patts, lemmas, nat.pred <$> n⟩), ext_core <|> pure () } end /-- Apply one extensionality lemma, and destruct the arguments using the given patterns. Returns the unused patterns. -/ meta def ext1 (xs : list rcases_patt) (cfg : apply_cfg := {}) (trace : bool := ff) : tactic (list rcases_patt) := do ⟨_, σ⟩ ← state_t.run (ext1_core cfg) {patts := xs}, when trace $ tactic.trace $ "Try this: " ++ ", ".intercalate σ.trace_msg, pure σ.patts /-- Apply multiple extensionality lemmas, destructing the arguments using the given patterns. `ext ps (some n)` applies at most `n` extensionality lemmas. Returns the unused patterns. -/ meta def ext (xs : list rcases_patt) (fuel : option ℕ) (cfg : apply_cfg := {}) (trace : bool := ff): tactic (list rcases_patt) := do ⟨_, σ⟩ ← state_t.run (ext_core cfg) {patts := xs, fuel := fuel}, when trace $ tactic.trace $ "Try this: " ++ ", ".intercalate σ.trace_msg, pure σ.patts local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. Placing a `?` after `ext1` (e.g. `ext1? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext1`. -/ meta def interactive.ext1 (trace : parse (tk "?")?) (xs : parse rcases_patt_parse_hi*) : tactic unit := ext1 xs {} trace.is_some $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. - `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. - Placing a `?` after `ext` (e.g. `ext? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext`. - `set_option trace.ext true` will trace every attempted lemma application, along with the time it takes for the application to succeed or fail. This is useful for debugging slow `ext` calls. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. In the previous example, applying `ext? ⟨a,b⟩` will produce the trace message: ```lean Try this: apply funext, rintro ⟨a, b⟩ ``` A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : (parse $ (tk "?")?) → parse rcases_patt_parse_hi* → parse (tk ":" *> small_nat)? → tactic unit | trace [] (some n) := iterate_range 1 n (ext1 [] {} trace.is_some $> ()) | trace [] none := repeat1 (ext1 [] {} trace.is_some $> ()) | trace xs n := ext xs n {} trace.is_some $> () /-- * `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. * `ext` applies as many extensionality lemmas as possible; * `ext ids`, with `ids` a list of identifiers, finds extensionality lemmas and applies them until it runs out of identifiers in `ids` to name the local constants. * `ext` can also be given an `rcases` pattern in place of an identifier. This will destruct the introduced local constant. - Placing a `?` after `ext`/`ext1` (e.g. `ext? i ⟨a,b⟩ : 3`) will display a sequence of tactic applications that can replace the call to `ext`/`ext1`. - `set_option trace.ext true` will trace every attempted lemma application, along with the time it takes for the application to succeed or fail. This is useful for debugging slow `ext` calls. When trying to prove: ```lean α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ```lean α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ g x ``` by applying functional extensionality and set extensionality. When trying to prove: ```lean α β γ : Type f g : α × β → γ ⊢ f = g ``` applying `ext ⟨a, b⟩` yields: ```lean α β γ : Type, f g : α × β → γ, a : α, b : β ⊢ f (a, b) = g (a, b) ``` by applying functional extensionality and destructing the introduced pair. In the previous example, applying `ext? ⟨a,b⟩` will produce the trace message: ```lean Try this: apply funext, rintro ⟨a, b⟩ ``` A maximum depth can be provided with `ext x y z : 3`. -/ add_tactic_doc { name := "ext1 / ext", category := doc_category.tactic, decl_names := [`tactic.interactive.ext1, `tactic.interactive.ext], tags := ["rewriting", "logic"] } end tactic end ext
8195c9638100b6f7aede367627c847050b8a7a26
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0210.lean
e163f34fd1177747f46719c4582d51a22a8c7c6e
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
569
lean
variables x y z : ℤ example (x y z : ℕ) : x * (y + z) = x * y + x * z := mul_add x y z example (x y z : ℕ) : (x + y) * z = x * z + y * z := add_mul x y z example (x y z : ℕ) : x + y + z = x + (y + z) := add_assoc x y z example (x y : ℕ) : (x + y) * (x + y) = x * x + y * x + x * y + y * y := have h1 : (x + y) * (x + y) = (x + y) * x + (x + y) * y, from mul_add (x + y) x y, have h2 : (x + y) * (x + y) = x * x + y * x + (x * y + y * y), from add_mul x y x ▸ add_mul x y y ▸ h1, h2.trans (add_assoc (x * x + y * x) (x * y) (y * y)).symm
a34b61ea3e4b7bd2d8ec2e29a3cb026b8322b277
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cases_bug2.lean
32d7012e543e1e59370c09d955f28e4011ff22e4
[ "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
89
lean
open tactic example (a : nat) : 0 = nat.succ a → false := by do h ← intro1, cases h
0825a20b0ea2d0269aa38a9fbb6bc4a68697102a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/geometry/manifold/times_cont_mdiff_map.lean
2829e517c69a9635dbaa7090a8e0266e1e8e7cf3
[ "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
3,949
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.times_cont_mdiff import topology.continuous_function.basic /-! # Smooth bundled map In this file we define the type `times_cont_mdiff_map` of `n` times continuously differentiable bundled maps. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] (M' : Type*) [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] (n : with_top ℕ) /-- Bundled `n` times continuously differentiable maps. -/ @[protect_proj] structure times_cont_mdiff_map := (to_fun : M → M') (times_cont_mdiff_to_fun : times_cont_mdiff I I' n to_fun) /-- Bundled smooth maps. -/ @[reducible] def smooth_map := times_cont_mdiff_map I I' M M' ⊤ localized "notation `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` := times_cont_mdiff_map I I' M M' n" in manifold localized "notation `C^` n `⟮` I `, ` M `; ` k `⟯` := times_cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold open_locale manifold namespace times_cont_mdiff_map variables {I} {I'} {M} {M'} {n} instance : has_coe_to_fun C^n⟮I, M; I', M'⟯ (λ _, M → M') := ⟨times_cont_mdiff_map.to_fun⟩ instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') := ⟨λ f, ⟨f, f.times_cont_mdiff_to_fun.continuous⟩⟩ attribute [to_additive_ignore_args 21] times_cont_mdiff_map times_cont_mdiff_map.has_coe_to_fun times_cont_mdiff_map.continuous_map.has_coe variables {f g : C^n⟮I, M; I', M'⟯} @[simp] lemma coe_fn_mk (f : M → M') (hf : times_cont_mdiff I I' n f) : (mk f hf : M → M') = f := rfl protected lemma times_cont_mdiff (f : C^n⟮I, M; I', M'⟯) : times_cont_mdiff I I' n f := f.times_cont_mdiff_to_fun protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) : smooth I I' f := f.times_cont_mdiff_to_fun protected lemma mdifferentiable' (f : C^n⟮I, M; I', M'⟯) (hn : 1 ≤ n) : mdifferentiable I I' f := f.times_cont_mdiff.mdifferentiable hn protected lemma mdifferentiable (f : C^∞⟮I, M; I', M'⟯) : mdifferentiable I I' f := f.times_cont_mdiff.mdifferentiable le_top protected lemma mdifferentiable_at (f : C^∞⟮I, M; I', M'⟯) {x} : mdifferentiable_at I I' f x := f.mdifferentiable x lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext h /-- The identity as a smooth map. -/ def id : C^n⟮I, M; I, M⟯ := ⟨id, times_cont_mdiff_id⟩ /-- The composition of smooth maps, as a smooth map. -/ def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ := { to_fun := λ a, f (g a), times_cont_mdiff_to_fun := f.times_cont_mdiff_to_fun.comp g.times_cont_mdiff_to_fun, } @[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) : f.comp g x = f (g x) := rfl instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ := ⟨⟨λ _, default, times_cont_mdiff_const⟩⟩ /-- Constant map as a smooth map -/ def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, times_cont_mdiff_const⟩ end times_cont_mdiff_map instance continuous_linear_map.has_coe_to_times_cont_mdiff_map : has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ := ⟨λ f, ⟨f.to_fun, f.times_cont_mdiff⟩⟩
001895a17761fddd5aa15c51e0a92287356de8c4
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/while/Hoare.lean
a239006350531b0823eba588c46dbb3a0332ca26
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
3,728
lean
import Stmt import Subst import BigStep open Stmt def Hoare (p:Pred)(e:Stmt)(q:Pred) : Prop := ∀ (s t:Env), p s → BigStep e s t → q t lemma skip_intro : ∀ (p:Pred), Hoare p skip p := begin intros p s t H1 H2, cases H2, assumption end lemma assign_intro : ∀ (p:Pred) (x:string) (a:AExp), Hoare (subst x a p) (x :== a) p := begin intros p x a s t H1 H2, cases H2, assumption end lemma seq_intro : ∀ (p q r:Pred) (e₁ e₂:Stmt), Hoare p e₁ q → Hoare q e₂ r → Hoare p (e₁ ;; e₂) r := begin intros p q r e₁ e₂ H1 H2 s t H3 H4, unfold Hoare at H1, unfold Hoare at H2, cases H4 with _ _ _ _ _ _ _ u _ H4 H5, apply (H2 u t), { apply (H1 s u); assumption }, { assumption } end lemma ite_intro : ∀ (p q:Pred) (b:BExp) (e₁ e₂:Stmt), Hoare (λ s, p s ∧ b s) e₁ q → Hoare (λ s, p s ∧ ¬b s) e₂ q → Hoare p (ite b e₁ e₂) q := begin intros p q b e₁ e₂ H1 H2 s t H3 H4, unfold Hoare at H1, unfold Hoare at H2, cases H4 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H4 H5 , { apply (H1 s t), { split; assumption }, { assumption }}, { apply (H2 s t), { split; assumption }, { assumption }} end lemma while_intro : ∀ (p:Pred) (b:BExp) (e₁:Stmt), Hoare (λ s, p s ∧ b s) e₁ p → Hoare p (while b e₁) (λ s, p s ∧ ¬ b s) := begin intros p b e₁ H1 s t H2 H3, unfold Hoare at H1, revert H2, generalize H2 : while b e₁ = e, rw H2 at H3, revert H2, induction H3 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ s u t G1 G2 G3 G4 G5; intros H2, { cases H2 }, { cases H2 }, { cases H2 }, { cases H2 }, { cases H2 }, { cases H2, clear H2, intros G6, apply G5, { refl}, { apply (H1 s u), { split; assumption }, { assumption }}}, { cases H2, intros, split; assumption } end lemma weaken_intro : ∀ (p p' q q':Pred) (e₁:Stmt), (∀ s, p' s → p s) → Hoare p e₁ q → (∀ s, q s → q' s) → Hoare p' e₁ q' := begin intros p p' q q' e₁ H1 H2 H3 s t H4 H5, unfold Hoare at H2, apply H3, apply (H2 s t), { apply H1, assumption }, { assumption } end lemma weaken_left : ∀ (p p' q:Pred) (e₁:Stmt), (∀ s, p' s → p s) → Hoare p e₁ q → Hoare p' e₁ q := begin intros p p' q e₁ H1 H2, apply (weaken_intro p p' q q), { assumption }, { assumption }, { intros s H3, assumption } end lemma weaken_right : ∀ (p q q':Pred) (e₁:Stmt), Hoare p e₁ q → (∀ s, q s → q' s) → Hoare p e₁ q' := begin intros p q q' e₁ H1 H2, apply (weaken_intro p p q q'), {intros s H3, assumption }, { assumption }, { assumption } end lemma skip_intro' : ∀ (p q:Pred), (∀ s, p s → q s) → Hoare p skip q := begin intros p q H1, apply (weaken_left q p q), { assumption }, { apply skip_intro } end lemma assign_intro' : ∀ (p q:Pred) (x:string) (a:AExp), (∀ s, p s → subst x a q s) → Hoare p (x :== a) q := begin intros p q x a H1, apply (weaken_left (subst x a q) p q), { assumption }, { apply assign_intro } end lemma seq_intro' : ∀ (p q r:Pred) (e₁ e₂:Stmt), Hoare q e₂ r → Hoare p e₁ q → Hoare p (e₁ ;; e₂) r := begin intros p q r e₁ e₂ H1 H2, apply (seq_intro p q r); assumption end lemma while_intro' : ∀ (p q i:Pred) (b:BExp) (e₁:Stmt), Hoare (λ s, i s ∧ b s) e₁ i → (∀ s, p s → i s) → (∀ s, ¬b s → i s → q s) → Hoare p (while b e₁) q := begin intros p q i b e₁ H1 H2 H3, apply (weaken_intro i _ (λ s, i s ∧ ¬b s)), { assumption }, { apply while_intro, assumption }, { intros s H4, cases H4 with H4 H5, apply H3; assumption } end
bf3caf583f505c4627ad38fd5db02f8eddc23ea8
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/simp_tactic.lean
22b36a6f00c1ef02bcbe1a9c5f893ef3ede3b519
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
13,686
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /- (simp_lemmas.rewrite_core m s prove R e) apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /- (simp_lemmas.drewrite s e) tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff meta constant simp_lemmas.pp : simp_lemmas → tactic format namespace tactic /- (get_eqn_lemmas_for deps d) returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr meta def dunfold_expr : expr → tactic expr := dunfold_expr_core reducible meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core reducible meta def dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr := let unfold (c : nat) (e : expr) : tactic (nat × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, if occs^.contains c then return (c+1, new_e, tt) else return (c+1, e, tt) in do (c, new_e) ← dsimplify_core 1 max_steps tt unfold (λ c e, failed) e, return new_e meta def dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () max_steps tt (λ c e, failed) unfold e, return new_e meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core reducible default_max_steps cs >>= change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core reducible default_max_steps (occurrences.pos occs) [c] >>= change meta def dunfold_core_at (occs : occurrences) (cs : list name) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, new_d : expr ← dunfold_occs_core reducible default_max_steps occs cs d, change $ expr.pi n bi new_d b, intron num_reverted meta def dunfold_at (cs : list name) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, new_d : expr ← dunfold_core reducible default_max_steps cs d, change $ expr.pi n bi new_d b, intron num_reverted structure simplify_config := (max_steps : nat) (contextual : bool) (lift_eq : bool) (canonize_instances : bool) (canonize_proofs : bool) (use_axioms : bool) def default_simplify_config : simplify_config := { max_steps := default_max_steps, contextual := ff, lift_eq := tt, canonize_instances := tt, canonize_proofs := ff, use_axioms := tt } meta constant simplify_core (c : simplify_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simplify_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (cfg : simplify_config) (S : simp_lemmas) (e : expr) : tactic (expr × expr) := do e_type ← infer_type e >>= whnf, simplify_core cfg S `eq e meta def simplify_goal_core (cfg : simplify_config) (S : simp_lemmas) : tactic unit := do (new_target, heq) ← target >>= simplify cfg S, assert `htarget new_target, swap, ht ← get_local `htarget, mk_app `eq.mpr [heq, ht] >>= exact meta def simplify_goal (S : simp_lemmas) : tactic unit := simplify_goal_core default_simplify_config S meta def simp : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal S >> try triv >> try (reflexivity_core reducible) meta def simp_using (hs : list expr) : tactic unit := do S ← simp_lemmas.mk_default, S ← S^.append hs, simplify_goal S >> try triv meta def ctx_simp : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal_core {default_simplify_config with contextual := tt} S >> try triv >> try (reflexivity_core reducible) meta def dsimp_core (s : simp_lemmas) : tactic unit := target >>= s^.dsimplify >>= change meta def dsimp : tactic unit := simp_lemmas.mk_default >>= dsimp_core meta def dsimp_at_core (s : simp_lemmas) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, (expr.pi n bi d b : expr) ← target | failed, h_simp ← s^.dsimplify d, change $ expr.pi n bi h_simp b, intron num_reverted meta def dsimp_at (h : expr) : tactic unit := do s ← simp_lemmas.mk_default, dsimp_at_core s h private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps /- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs : tactic unit := collect_ctx_simps >>= simp_using meta def simp_core_at (extra_lemmas : list expr) (h : expr) : tactic unit := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, S ← simp_lemmas.mk_default, S ← S^.append extra_lemmas, (new_htype, heq) ← simplify default_simplify_config S htype, assert (expr.local_pp_name h) new_htype, mk_app `eq.mp [heq, h] >>= exact, try $ clear h meta def simp_at : expr → tactic unit := simp_core_at [] meta def simp_at_using (hs : list expr) : expr → tactic unit := simp_core_at hs meta def simp_at_using_hs (h : expr) : tactic unit := do hs ← collect_ctx_simps, simp_core_at (list.filter (ne h) hs) h meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S^.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do t ← to_expr `(caching_user_attribute simp_lemmas), a ← attr_name^.to_expr, v ← to_expr `(({ name := %%a, descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas)), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S^.join S') R meta def join_user_simp_lemmas : list name → tactic simp_lemmas | [] := simp_lemmas.mk_default | attr_names := join_user_simp_lemmas_core simp_lemmas.mk attr_names /- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) end tactic export tactic (mk_simp_attr)
719f1f40ec16196ed4e48195108dcf2e611dc4f3
7b89826c26634aa18c0110f1634f73027851edfe
/natural-number-game/src/world01/level01.lean
39e02d2ecea919125ea0fa07c26e33048a45448d
[ "MIT" ]
permissive
marcofavorito/leanings
b7642344d8c9012a1cec74a804c5884297880c4d
581b83be66ff4f8dd946fb6a1bb045d2ddf91076
refs/heads/master
1,672,310,991,244
1,603,031,766,000
1,603,031,766,000
279,163,004
1
0
null
null
null
null
UTF-8
Lean
false
false
350
lean
import mynat.definition -- imports the natural numbers {0,1,2,3,4,...}. import mynat.add -- imports definition of addition on the natural numbers. import mynat.mul -- imports definition of multiplication on the natural numbers. namespace mynat -- hide lemma example1 (x y z : mynat) : x * y + z = x * y + z := begin refl, end end mynat -- hide
5d10b60ed917160095c272fab45dc08c79207692
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0105/Q0105.lean
086da0f1007725f6444f36e02f514ec5cb89ee57
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,331
lean
-- ignore this part: we are building the notion of a set -- go to line 36 inductive zfc : Type | empty : zfc | insert : zfc → zfc → zfc instance : has_emptyc zfc := ⟨zfc.empty⟩ instance : has_insert zfc zfc := ⟨zfc.insert⟩ instance : has_zero zfc := ⟨{}⟩ instance : has_one zfc := ⟨{0}⟩ def succ (a : zfc) : zfc := has_insert.insert a a def zfc_add : zfc → zfc → zfc | m 0 := m | m (zfc.insert n p) := succ (zfc_add m n) instance : has_add zfc := ⟨zfc_add⟩ inductive member : zfc → zfc → Prop | left {a b c : zfc} : member a c → member a (has_insert.insert b c) | right {a b : zfc} : member a (has_insert.insert a b) instance : has_mem zfc zfc := ⟨member⟩ instance : has_subset zfc := ⟨(λ a b:zfc, (∀ z:zfc, z ∈ a → z ∈ b))⟩ infix `⊈`:50 := (λ a b, ¬(a ⊆ b)) infix `⊉`:50 := (λ a b, ¬(b ⊆ a)) axiom member.ext (a b : zfc) : (∀ x, x ∈ a ↔ x ∈ b) ↔ a=b export zfc export member -- start here /- USAGE: 1. ¬P is shorthand of (P → false). 2. A ∉ B is shorthand of ¬(A ∈ B), which is shorthand of (A ∈ B → false) per 1. 3. A ⊆ B is shorthand of (∀ z, z ∈ A → z ∈ B). 4. A ⊈ B is shorthand of ¬(A ⊆ B), and then use 1 and 3. 5. A ⊇ B is shorthand of B ⊆ A. 6. If the current goal is x ∈ {a,b,c,d,e}, then using "left" or "apply left" will make the goal x ∈ {a,b,c,d}. 7. If the current goal is x ∈ {a,b,c,d,x}, then using "right" or "apply right" or "exact right" will prove the goal. 8. If one wishes to disprove (i.e. derive false from) one of the current hypotheses of the form h : x ∈ {a,b,c,d,e}, using "cases h" will replace the current hypothesis with a_1 : x ∈ {a,b,c,d}, provided that x and e are not equal. When the set is empty, "cases h" will directly prove false. HINT: To prove a statement of the form "P → P", use "exact id". RECAP: 1. To prove a statement of the form "∀ z, P z", type "intro x" and then prove "P x". 2. To prove a statement of the form "P → Q", type "intro HP" and then prove "Q". NOTE: Somehow the goal will become messy. I tried to fix it but it just wouldn't work. Try to work with simple cases where the goal still works, and then trust in the force when it doesn't. -/ definition A : zfc := {1,2,3,4,5} -- prove one and delete the other for each part. theorem M1F_Sheet01_Q05a_is_true : (1:zfc) ∈ A := sorry theorem M1F_Sheet01_Q05a_is_false : (1:zfc) ∈ A := sorry theorem M1F_Sheet01_Q05b_is_true: ({1}:zfc) ∈ A := sorry theorem M1F_Sheet01_Q05b_is_false: ({1}:zfc) ∉ A := sorry theorem M1F_Sheet01_Q05c_is_true: ({1}:zfc) ⊆ A := sorry theorem M1F_Sheet01_Q05c_is_false: ({1}:zfc) ⊈ A := sorry -- The goal generator gets messy in (d) and (e). theorem M1F_Sheet01_Q05d_is_true: ({1,2}:zfc) ⊆ A := sorry theorem M1F_Sheet01_Q05d_is_false: ({1,2}:zfc) ⊆ A := sorry theorem M1F_Sheet01_Q05e_is_true: ({1,2,1}:zfc) ⊆ A := sorry theorem M1F_Sheet01_Q05e_is_false: ({1,2,1}:zfc) ⊈ A := sorry theorem M1F_Sheet01_Q05f_is_true: ({1,1}:zfc) ∈ A := sorry theorem M1F_Sheet01_Q05f_is_false: ({1,1}:zfc) ∉ A := sorry theorem M1F_Sheet01_Q05g_is_true: A ∈ A := sorry theorem M1F_Sheet01_Q05g_is_false: A ∉ A := sorry theorem M1F_Sheet01_Q05h_is_true: A ⊇ A := sorry theorem M1F_Sheet01_Q05h_is_false: A ⊉ A := sorry
53b1da73295148f4022529f3b12d953e2493700e
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/tactic22.lean
ae413ac8a3e64168664160e355394f161e67700f
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
177
lean
import logic open tactic theorem T (a b c d : Prop) (Ha : a) (Hb : b) (Hc : c) (Hd : d) : a ∧ b ∧ c ∧ d := by fixpoint (λ f, [apply @and.intro; f | assumption; f | id])
4005837f4d423b014b2d668bb74fe306a0a1f86c
5d166a16ae129621cb54ca9dde86c275d7d2b483
/leanpkg/leanpkg/manifest.lean
fdf885e0debf37cb7713fbccdc0b8d77c135c24f
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
3,472
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import leanpkg.toml system.io namespace leanpkg inductive source | path (dir_name : string) : source | git (url rev : string) : source namespace source def from_toml (v : toml.value) : option source := (do toml.value.str dir_name ← v.lookup "path" | none, return $ path dir_name) <|> (do toml.value.str url ← v.lookup "git" | none, toml.value.str rev ← (v.lookup "rev") | none, return $ git url rev) <|> (do toml.value.str url ← v.lookup "git" | none, return $ git url "master") def to_toml : ∀ (s : source), toml.value | (path dir_name) := toml.value.table [("path", toml.value.str dir_name)] | (git url "master") := toml.value.table [("git", toml.value.str url)] | (git url rev) := toml.value.table [("git", toml.value.str url), ("rev", toml.value.str rev)] instance : has_to_string source := ⟨λ s, s.to_toml.to_string⟩ end source structure dependency := (name : string) (src : source) namespace dependency instance : has_to_string dependency := ⟨λ d, d.name ++ " = " ++ to_string d.src⟩ end dependency structure manifest := (name : string) (version : string) (timeout : option nat := none) (path : option string := none) (dependencies : list dependency := []) namespace manifest def effective_path (m : manifest) : list string := [match m.path with some p := p | none := "." end] def from_toml (t : toml.value) : option manifest := do pkg ← t.lookup "package", toml.value.str n ← pkg.lookup "name" | none, toml.value.str ver ← pkg.lookup "version" | none, tm ← match pkg.lookup "timeout" with | some (toml.value.nat timeout) := some (some timeout) | none := some none | _ := none end, path ← match pkg.lookup "path" with | some (toml.value.str path) := some (some path) | none := some none | _ := none end, toml.value.table deps ← t.lookup "dependencies" <|> some (toml.value.table []) | none, deps ← monad.for deps (λ ⟨n, src⟩, do src ← source.from_toml src, return $ dependency.mk n src), return { name := n, version := ver, path := path, dependencies := deps, timeout := tm } def to_toml (d : manifest) : toml.value := let pkg := [("name", toml.value.str d.name), ("version", toml.value.str d.version)], pkg := match d.path with some p := pkg ++ [("path", toml.value.str p)] | none := pkg end, pkg := match d.timeout with some t := pkg ++ [("timeout", toml.value.nat t)] | none := pkg end, deps := toml.value.table $ d.dependencies.for $ λ dep, (dep.name, dep.src.to_toml) in toml.value.table [("package", toml.value.table pkg), ("dependencies", deps)] instance : has_to_string manifest := ⟨λ d, d.to_toml.to_string⟩ def from_string (s : string) : option manifest := match parser.run_string toml.File s with | sum.inr toml := from_toml toml | sum.inl _ := none end def from_file [io.interface] (fn : string) : io manifest := do cnts ← io.fs.read_file fn, toml ← (match parser.run toml.File cnts with | sum.inl err := io.fail $ "toml parse error in " ++ fn ++ "\n\n" ++ err | sum.inr res := return res end), some manifest ← return (from_toml toml) | io.fail ("cannot read manifest from " ++ fn ++ "\n\n" ++ toml.to_string), return manifest end manifest def leanpkg_toml_fn := "leanpkg.toml" end leanpkg
7f11befd24177a5d517164b7eada4cbaca2b5acf
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Data/PersistentArray.lean
a30feb7f281340d4539c64b8070ebccf9b84d542
[ "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
211
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.Data.PersistentArray.Basic
df1ed67bb3e0aa510b7999638cfdc9b5de9fdc38
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/polynomial/chebyshev.lean
8c7094a4cc3d3be1a1a5bf9d6834c3dda94da976
[ "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
10,851
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Julian Kuelshammer, Heather Macbeth -/ import data.polynomial.derivative import tactic.linear_combination /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `ℕ`, with integral coefficients. ## Main definitions * `polynomial.chebyshev.T`: the Chebyshev polynomials of the first kind. * `polynomial.chebyshev.U`: the Chebyshev polynomials of the second kind. ## Main statements * The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the Chebyshev polynomials of the second kind. * `polynomial.chebyshev.mul_T`, the product of the `m`-th and `(m + k)`-th Chebyshev polynomials of the first kind is the sum of the `(2 * m + k)`-th and `k`-th Chebyshev polynomials of the first kind. * `polynomial.chebyshev.T_mul`, the `(m * n)`-th Chebyshev polynomial of the first kind is the composition of the `m`-th and `n`-th Chebyshev polynomials of the first kind. ## Implementation details Since Chebyshev polynomials have interesting behaviour over the complex numbers and modulo `p`, we define them to have coefficients in an arbitrary commutative ring, even though technically `ℤ` would suffice. The benefit of allowing arbitrary coefficient rings, is that the statements afterwards are clean, and do not have `map (int.cast_ring_hom R)` interfering all the time. ## References [Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_] [ponton2020chebyshev] ## TODO * Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`. * Add explicit formula involving square roots for Chebyshev polynomials * Compute zeroes and extrema of Chebyshev polynomials. * Prove that the roots of the Chebyshev polynomials (except 0) are irrational. * Prove minimax properties of Chebyshev polynomials. -/ noncomputable theory namespace polynomial.chebyshev open polynomial open_locale polynomial variables (R S : Type*) [comm_ring R] [comm_ring S] /-- `T n` is the `n`-th Chebyshev polynomial of the first kind -/ noncomputable def T : ℕ → R[X] | 0 := 1 | 1 := X | (n + 2) := 2 * X * T (n + 1) - T n @[simp] lemma T_zero : T R 0 = 1 := rfl @[simp] lemma T_one : T R 1 = X := rfl @[simp] lemma T_add_two (n : ℕ) : T R (n + 2) = 2 * X * T R (n + 1) - T R n := by rw T lemma T_two : T R 2 = 2 * X ^ 2 - 1 := by simp only [T, sub_left_inj, sq, mul_assoc] lemma T_of_two_le (n : ℕ) (h : 2 ≤ n) : T R n = 2 * X * T R (n - 1) - T R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact T_add_two R n end /-- `U n` is the `n`-th Chebyshev polynomial of the second kind -/ noncomputable def U : ℕ → R[X] | 0 := 1 | 1 := 2 * X | (n + 2) := 2 * X * U (n + 1) - U n @[simp] lemma U_zero : U R 0 = 1 := rfl @[simp] lemma U_one : U R 1 = 2 * X := rfl @[simp] lemma U_add_two (n : ℕ) : U R (n + 2) = 2 * X * U R (n + 1) - U R n := by rw U lemma U_two : U R 2 = 4 * X ^ 2 - 1 := by { simp only [U], ring, } lemma U_of_two_le (n : ℕ) (h : 2 ≤ n) : U R n = 2 * X * U R (n - 1) - U R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact U_add_two R n end lemma U_eq_X_mul_U_add_T : ∀ n : ℕ, U R (n + 1) = X * U R n + T R (n + 1) | 0 := by { simp only [U_zero, U_one, T_one], ring } | 1 := by { simp only [U_one, T_two, U_two], ring } | (n + 2) := calc U R (n + 2 + 1) = 2 * X * (X * U R (n + 1) + T R (n + 2)) - (X * U R n + T R (n + 1)) : by simp only [U_add_two, U_eq_X_mul_U_add_T n, U_eq_X_mul_U_add_T (n + 1)] ... = X * (2 * X * U R (n + 1) - U R n) + (2 * X * T R (n + 2) - T R (n + 1)) : by ring ... = X * U R (n + 2) + T R (n + 2 + 1) : by simp only [U_add_two, T_add_two] lemma T_eq_U_sub_X_mul_U (n : ℕ) : T R (n + 1) = U R (n + 1) - X * U R n := by rw [U_eq_X_mul_U_add_T, add_comm (X * U R n), add_sub_cancel] lemma T_eq_X_mul_T_sub_pol_U : ∀ n : ℕ, T R (n + 2) = X * T R (n + 1) - (1 - X ^ 2) * U R n | 0 := by { simp only [T_one, T_two, U_zero], ring } | 1 := by { simp only [T_add_two, T_zero, T_add_two, U_one, T_one], ring } | (n + 2) := calc T R (n + 2 + 2) = 2 * X * T R (n + 2 + 1) - T R (n + 2) : T_add_two _ _ ... = 2 * X * (X * T R (n + 2) - (1 - X ^ 2) * U R (n + 1)) - (X * T R (n + 1) - (1 - X ^ 2) * U R n) : by simp only [T_eq_X_mul_T_sub_pol_U] ... = X * (2 * X * T R (n + 2) - T R (n + 1)) - (1 - X ^ 2) * (2 * X * U R (n + 1) - U R n) : by ring ... = X * T R (n + 2 + 1) - (1 - X ^ 2) * U R (n + 2) : by rw [T_add_two _ (n + 1), U_add_two] lemma one_sub_X_sq_mul_U_eq_pol_in_T (n : ℕ) : (1 - X ^ 2) * U R n = X * T R (n + 1) - T R (n + 2) := by rw [T_eq_X_mul_T_sub_pol_U, ←sub_add, sub_self, zero_add] variables {R S} @[simp] lemma map_T (f : R →+* S) : ∀ n : ℕ, map f (T R n) = T S n | 0 := by simp only [T_zero, polynomial.map_one] | 1 := by simp only [T_one, map_X] | (n + 2) := begin simp only [T_add_two, polynomial.map_mul, polynomial.map_sub, map_X, bit0, polynomial.map_add, polynomial.map_one], rw [map_T (n + 1), map_T n], end @[simp] lemma map_U (f : R →+* S) : ∀ n : ℕ, map f (U R n) = U S n | 0 := by simp only [U_zero, polynomial.map_one] | 1 := begin simp only [U_one, map_X, polynomial.map_mul, polynomial.map_add, polynomial.map_one], change map f (1 + 1) * X = 2 * X, simpa only [polynomial.map_add, polynomial.map_one] end | (n + 2) := begin simp only [U_add_two, polynomial.map_mul, polynomial.map_sub, map_X, bit0, polynomial.map_add, polynomial.map_one], rw [map_U (n + 1), map_U n], end lemma T_derivative_eq_U : ∀ n : ℕ, derivative (T R (n + 1)) = (n + 1) * U R n | 0 := by simp only [T_one, U_zero, derivative_X, nat.cast_zero, zero_add, mul_one] | 1 := by { simp only [T_two, U_one, derivative_sub, derivative_one, derivative_mul, derivative_X_pow, nat.cast_one, nat.cast_two], norm_num } | (n + 2) := calc derivative (T R (n + 2 + 1)) = 2 * T R (n + 2) + 2 * X * derivative (T R (n + 1 + 1)) - derivative (T R (n + 1)) : by simp only [T_add_two _ (n + 1), derivative_sub, derivative_mul, derivative_X, derivative_bit0, derivative_one, bit0_zero, zero_mul, zero_add, mul_one] ... = 2 * (U R (n + 1 + 1) - X * U R (n + 1)) + 2 * X * ((n + 1 + 1) * U R (n + 1)) - (n + 1) * U R n : by rw_mod_cast [T_derivative_eq_U, T_derivative_eq_U, T_eq_U_sub_X_mul_U] ... = (n + 1) * (2 * X * U R (n + 1) - U R n) + 2 * U R (n + 2) : by ring ... = (n + 1) * U R (n + 2) + 2 * U R (n + 2) : by rw U_add_two ... = (n + 2 + 1) * U R (n + 2) : by ring ... = (↑(n + 2) + 1) * U R (n + 2) : by norm_cast lemma one_sub_X_sq_mul_derivative_T_eq_poly_in_T (n : ℕ) : (1 - X ^ 2) * (derivative (T R (n + 1))) = (n + 1) * (T R n - X * T R (n+1)) := calc (1 - X ^ 2) * (derivative (T R (n + 1))) = (1 - X ^ 2) * ((n + 1) * U R n) : by rw T_derivative_eq_U ... = (n + 1) * ((1 - X ^ 2) * U R n) : by ring ... = (n + 1) * (X * T R (n + 1) - (2 * X * T R (n + 1) - T R n)) : by rw [one_sub_X_sq_mul_U_eq_pol_in_T, T_add_two] ... = (n + 1) * (T R n - X * T R (n + 1)) : by ring lemma add_one_mul_T_eq_poly_in_U (n : ℕ) : ((n : R[X]) + 1) * T R (n + 1) = X * U R n - (1 - X ^ 2) * derivative (U R n) := begin have h : derivative (T R (n + 2)) = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1)) + 2 * X * U R n - (1 - X ^ 2) * derivative (U R n), { conv_lhs { rw T_eq_X_mul_T_sub_pol_U }, simp only [derivative_sub, derivative_mul, derivative_X, derivative_one, derivative_X_pow, one_mul, T_derivative_eq_U], rw [T_eq_U_sub_X_mul_U, C_eq_nat_cast, nat.cast_bit0, nat.cast_one], ring }, calc ((n : R[X]) + 1) * T R (n + 1) = ((n : R[X]) + 1 + 1) * (X * U R n + T R (n + 1)) - X * ((n + 1) * U R n) - (X * U R n + T R (n + 1)) : by ring ... = derivative (T R (n + 2)) - X * derivative (T R (n + 1)) - U R (n + 1) : by rw [←U_eq_X_mul_U_add_T, ←T_derivative_eq_U, ←nat.cast_one, ←nat.cast_add, nat.cast_one, ←T_derivative_eq_U (n + 1)] ... = (U R (n + 1) - X * U R n) + X * derivative (T R (n + 1)) + 2 * X * U R n - (1 - X ^ 2) * derivative (U R n) - X * derivative (T R (n + 1)) - U R (n + 1) : by rw h ... = X * U R n - (1 - X ^ 2) * derivative (U R n) : by ring, end variables (R) /-- The product of two Chebyshev polynomials is the sum of two other Chebyshev polynomials. -/ lemma mul_T : ∀ m k, 2 * T R m * T R (m + k) = T R (2 * m + k) + T R k | 0 := by simp [two_mul, add_mul] | 1 := by simp [add_comm] | (m + 2) := begin intros k, -- clean up the `T` nat indices in the goal suffices : 2 * T R (m + 2) * T R (m + k + 2) = T R (2 * m + k + 4) + T R k, { have h_nat₁ : 2 * (m + 2) + k = 2 * m + k + 4 := by ring, have h_nat₂ : m + 2 + k = m + k + 2 := by simp [add_comm, add_assoc], simpa [h_nat₁, h_nat₂] using this }, -- clean up the `T` nat indices in the inductive hypothesis applied to `m + 1` and -- `k + 1` have H₁ : 2 * T R (m + 1) * T R (m + k + 2) = T R (2 * m + k + 3) + T R (k + 1), { have h_nat₁ : m + 1 + (k + 1) = m + k + 2 := by ring, have h_nat₂ : 2 * (m + 1) + (k + 1) = 2 * m + k + 3 := by ring, simpa [h_nat₁, h_nat₂] using mul_T (m + 1) (k + 1) }, -- clean up the `T` nat indices in the inductive hypothesis applied to `m` and `k + 2` have H₂ : 2 * T R m * T R (m + k + 2) = T R (2 * m + k + 2) + T R (k + 2), { have h_nat₁ : 2 * m + (k + 2) = 2 * m + k + 2 := by simp [add_assoc], have h_nat₂ : m + (k + 2) = m + k + 2 := by simp [add_assoc], simpa [h_nat₁, h_nat₂] using mul_T m (k + 2) }, -- state the `T` recurrence relation for a few useful indices have h₁ := T_add_two R m, have h₂ := T_add_two R (2 * m + k + 2), have h₃ := T_add_two R k, -- the desired identity is an appropriate linear combination of H₁, H₂, h₁, h₂, h₃ linear_combination 2 * T R (m + k + 2) * h₁ + 2 * X * H₁ - H₂ - h₂ - h₃, end /-- The `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th -/ lemma T_mul : ∀ m n, T R (m * n) = (T R m).comp (T R n) | 0 := by simp | 1 := by simp | (m + 2) := begin intros n, have : 2 * T R n * T R ((m + 1) * n) = T R ((m + 2) * n) + T R (m * n), { convert mul_T R n (m * n); ring }, simp [this, T_mul m, ← T_mul (m + 1)] end end polynomial.chebyshev
1c569096db1489bdfa2427b46a20d82f702ba884
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/char_zero.lean
03238d7319d7286350ac97d8dd89708c8339386a
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,384
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.cast import data.fintype.basic import tactic.wlog /-! # Characteristic zero A ring `R` is called of characteristic zero if every natural number `n` is non-zero when considered as an element of `R`. Since this definition doesn't mention the multiplicative structure of `R` except for the existence of `1` in this file characteristic zero is defined for additive monoids with `1`. ## Main definition `char_zero` is the typeclass of an additive monoid with one such that the natural homomorphism from the natural numbers into it is injective. ## Main statements * A linearly ordered semiring has characteristic zero. * Characteristic zero implies that the additive monoid is infinite. ## TODO * Once order of a group is defined for infinite additive monoids redefine or at least connect to order of `1` in the additive monoid with one. * Unify with `char_p` (possibly using an out-parameter) -/ /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (R : Type*) [add_monoid R] [has_one R] : Prop := (cast_injective : function.injective (coe : ℕ → R)) theorem char_zero_of_inj_zero {R : Type*} [add_left_cancel_monoid R] [has_one R] (H : ∀ n:ℕ, (n:R) = 0 → n = 0) : char_zero R := ⟨λ m n, begin assume h, wlog hle : m ≤ n, rcases nat.le.dest hle with ⟨k, rfl⟩, rw [nat.cast_add, eq_comm, add_right_eq_self] at h, rw [H k h, add_zero] end⟩ /-- Note this is not an instance as `char_zero` implies `nontrivial`, and this would risk forming a loop. -/ lemma ordered_semiring.to_char_zero {R : Type*} [ordered_semiring R] [nontrivial R] : char_zero R := ⟨nat.strict_mono_cast.injective⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {R : Type*} [linear_ordered_semiring R] : char_zero R := ordered_semiring.to_char_zero namespace nat variables {R : Type*} [add_monoid R] [has_one R] [char_zero R] theorem cast_injective : function.injective (coe : ℕ → R) := char_zero.cast_injective /-- `nat.cast` as an embedding into monoids of characteristic `0`. -/ @[simps] def cast_embedding : ℕ ↪ R := ⟨coe, cast_injective⟩ @[simp, norm_cast] theorem cast_inj {m n : ℕ} : (m : R) = n ↔ m = n := cast_injective.eq_iff @[simp, norm_cast] theorem cast_eq_zero {n : ℕ} : (n : R) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[norm_cast] theorem cast_ne_zero {n : ℕ} : (n : R) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero lemma cast_add_one_ne_zero (n : ℕ) : (n + 1 : R) ≠ 0 := by exact_mod_cast n.succ_ne_zero @[simp, norm_cast] theorem cast_dvd_char_zero {k : Type*} [field k] [char_zero k] {m n : ℕ} (n_dvd : n ∣ m) : ((m / n : ℕ) : k) = m / n := begin by_cases hn : n = 0, { subst hn, simp }, { exact cast_dvd n_dvd (cast_ne_zero.mpr hn), }, end end nat section variables (M : Type*) [add_monoid M] [has_one M] [char_zero M] @[priority 100] -- see Note [lower instance priority] instance char_zero.infinite : infinite M := infinite.of_injective coe nat.cast_injective variable {M} @[field_simps] lemma two_ne_zero' : (2:M) ≠ 0 := have ((2:ℕ):M) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_two] at this end section variables {R : Type*} [semiring R] [no_zero_divisors R] [char_zero R] @[simp] lemma add_self_eq_zero {a : R} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] @[simp] lemma bit0_eq_zero {a : R} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero @[simp] lemma zero_eq_bit0 {a : R} : 0 = bit0 a ↔ a = 0 := by { rw [eq_comm], exact bit0_eq_zero } end section variables {R : Type*} [ring R] [no_zero_divisors R] [char_zero R] lemma neg_eq_self_iff {a : R} : -a = a ↔ a = 0 := neg_eq_iff_add_eq_zero.trans add_self_eq_zero lemma eq_neg_self_iff {a : R} : a = -a ↔ a = 0 := eq_neg_iff_add_eq_zero.trans add_self_eq_zero lemma nat_mul_inj {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) : n = 0 ∨ a = b := begin rw [←sub_eq_zero, ←mul_sub, mul_eq_zero, sub_eq_zero] at h, exact_mod_cast h, end lemma nat_mul_inj' {n : ℕ} {a b : R} (h : (n : R) * a = (n : R) * b) (w : n ≠ 0) : a = b := by simpa [w] using nat_mul_inj h lemma bit0_injective : function.injective (bit0 : R → R) := λ a b h, begin dsimp [bit0] at h, simp only [(two_mul a).symm, (two_mul b).symm] at h, refine nat_mul_inj' _ two_ne_zero, exact_mod_cast h, end lemma bit1_injective : function.injective (bit1 : R → R) := λ a b h, begin simp only [bit1, add_left_inj] at h, exact bit0_injective h, end @[simp] lemma bit0_eq_bit0 {a b : R} : bit0 a = bit0 b ↔ a = b := bit0_injective.eq_iff @[simp] lemma bit1_eq_bit1 {a b : R} : bit1 a = bit1 b ↔ a = b := bit1_injective.eq_iff @[simp] lemma bit1_eq_one {a : R} : bit1 a = 1 ↔ a = 0 := by rw [show (1 : R) = bit1 0, by simp, bit1_eq_bit1] @[simp] lemma one_eq_bit1 {a : R} : 1 = bit1 a ↔ a = 0 := by { rw [eq_comm], exact bit1_eq_one } end section variables {R : Type*} [division_ring R] [char_zero R] @[simp] lemma half_add_self (a : R) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : R) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : R) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : R) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end namespace with_top instance {R : Type*} [add_monoid R] [has_one R] [char_zero R] : char_zero (with_top R) := { cast_injective := λ m n h, by rwa [← coe_nat, ← coe_nat n, coe_eq_coe, nat.cast_inj] at h } end with_top section ring_hom variables {R S : Type*} [semiring R] [semiring S] lemma ring_hom.char_zero (ϕ : R →+* S) [hS : char_zero S] : char_zero R := ⟨λ a b h, char_zero.cast_injective (by rw [←ϕ.map_nat_cast, ←ϕ.map_nat_cast, h])⟩ lemma ring_hom.char_zero_iff {ϕ : R →+* S} (hϕ : function.injective ϕ) : char_zero R ↔ char_zero S := ⟨λ hR, ⟨λ a b h, by rwa [←@nat.cast_inj R _ _ hR, ←hϕ.eq_iff, ϕ.map_nat_cast, ϕ.map_nat_cast]⟩, λ hS, by exactI ϕ.char_zero⟩ end ring_hom
4c9b0f834e60fbb28539ef1da90e5ca5e831263e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/punit_instances.lean
e876e9b70d0f470ba8cbb8dcd39675b7d24863aa
[ "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,438
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import algebra.module universes u namespace punit variables (x y : punit.{u+1}) (s : set punit.{u+1}) @[to_additive add_comm_group] instance : comm_group punit := by refine { mul := λ _ _, star, one := star, inv := λ _, star, .. }; intros; exact subsingleton.elim _ _ instance : comm_ring punit := by refine { .. punit.comm_group, .. punit.add_comm_group, .. }; intros; exact subsingleton.elim _ _ instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, sub := λ _ _, star, .. punit.comm_ring, .. }; intros; trivial instance : canonically_ordered_add_monoid punit := by refine { lt_of_add_lt_add_left := λ _ _ _, id, le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.complete_boolean_algebra, .. }; intros; trivial instance : decidable_linear_ordered_cancel_add_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, add_right_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_add_monoid } instance (R : Type u) [ring R] : module R punit := module.of_core $ by refine { smul := λ _ _, star, .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma zero_eq : (0 : punit) = star := rfl @[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl @[simp] lemma add_eq : x + y = star := rfl @[simp, to_additive] lemma mul_eq : x * y = star := rfl @[simp] lemma neg_eq : -x = star := rfl @[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl lemma smul_eq : x • y = star := rfl @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false instance {α : Type*} [has_mul α] (f : α → punit) : is_mul_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [has_add α] (f : α → punit) : is_add_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [monoid α] (f : α → punit) : is_monoid_hom f := { map_one := subsingleton.elim _ _ } instance {α : Type*} [add_monoid α] (f : α → punit) : is_add_monoid_hom f := { map_zero := subsingleton.elim _ _ } instance {α : Type*} [group α] (f : α → punit) : is_group_hom f := { } instance {α : Type*} [add_group α] (f : α → punit) : is_add_group_hom f := { } instance {α : Type*} [semiring α] (f : α → punit) : is_semiring_hom f := { .. punit.is_monoid_hom f, .. punit.is_add_monoid_hom f } instance {α : Type*} [ring α] (f : α → punit) : is_ring_hom f := { .. punit.is_semiring_hom f } end punit
ef82d9cacd4ba9cfcb28493fd84f3ebdfb39d9c1
367134ba5a65885e863bdc4507601606690974c1
/src/data/string/defs.lean
be87de10bc20ca7359d5f76352d0a59a202fb938
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,929
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon, Keeley Hoek, Floris van Doorn -/ import data.list.defs namespace string /-- `s.split_on c` tokenizes `s : string` on `c : char`. -/ def split_on (s : string) (c : char) : list string := split (= c) s /-- `string.map_tokens c f s` tokenizes `s : string` on `c : char`, maps `f` over each token, and then reassembles the string by intercalating the separator token `c` over the mapped tokens. -/ def map_tokens (c : char) (f : string → string) : string → string := intercalate (singleton c) ∘ list.map f ∘ split (= c) /-- Tests whether the first string is a prefix of the second string. -/ def is_prefix_of (x y : string) : bool := x.to_list.is_prefix_of y.to_list /-- Tests whether the first string is a suffix of the second string. -/ def is_suffix_of (x y : string) : bool := x.to_list.is_suffix_of y.to_list /-- `x.starts_with y` is true if `y` is a prefix of `x`, and is false otherwise. -/ abbreviation starts_with (x y : string) : bool := y.is_prefix_of x /-- `x.ends_with y` is true if `y` is a suffix of `x`, and is false otherwise. -/ abbreviation ends_with (x y : string) : bool := y.is_suffix_of x /-- `get_rest s t` returns `some r` if `s = t ++ r`. If `t` is not a prefix of `s`, returns `none` -/ def get_rest (s t : string) : option string := list.as_string <$> s.to_list.get_rest t.to_list /-- Removes the first `n` elements from the string `s` -/ def popn (s : string) (n : nat) : string := (s.mk_iterator.nextn n).next_to_string /-- `is_nat s` is true iff `s` is a nonempty sequence of digits. -/ def is_nat (s : string) : bool := ¬ s.is_empty ∧ s.to_list.all (λ c, to_bool c.is_digit) /-- Produce the head character from the string `s`, if `s` is not empty, otherwise 'A'. -/ def head (s : string) : char := (s.mk_iterator).curr end string
98405f5e7e5c31054d0c0a475c86ed48047b2d70
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/order/group.lean
59766570196d86fe412c56f0f4dfd9409f839519
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
48,477
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.abs import algebra.order.sub /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true open function universe u variable {α : Type u} @[to_additive] instance group.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (*) (≤)] : contravariant_class α α (*) (≤) := group.covconv @[to_additive] instance group.swap.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (swap (*)) (≤)] : contravariant_class α α (swap (*)) (≤) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... ≤ c * a * a⁻¹ : mul_le_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } @[to_additive] instance group.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (*) (<)] : contravariant_class α α (*) (<) := { elim := λ a b c bc, calc b = a⁻¹ * (a * b) : eq_inv_mul_of_mul_eq rfl ... < a⁻¹ * (a * c) : mul_lt_mul_left' bc a⁻¹ ... = c : inv_mul_cancel_left a c } @[to_additive] instance group.swap.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (swap (*)) (<)] : contravariant_class α α (swap (*)) (<) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... < c * a * a⁻¹ : mul_lt_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group @[to_additive] instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] : covariant_class α α (*) (≤) := { elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a } /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive "The units of an ordered commutative additive monoid form an ordered commutative additive group."] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group αˣ := { mul_le_mul_left := λ a b h c, (mul_le_mul_left' (h : (a : α) ≤ b) _ : (c : α) * a ≤ c * b), .. units.partial_order, .. units.comm_group } @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := λ a b c, (mul_right_inj a).mp, le_of_mul_le_mul_left := λ a b c, (mul_le_mul_iff_left a).mp, ..s } @[priority 100, to_additive] instance ordered_comm_group.has_exists_mul_of_le (α : Type u) [ordered_comm_group α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩ @[to_additive] instance [h : has_inv α] : has_inv αᵒᵈ := h @[to_additive] instance [h : has_div α] : has_div αᵒᵈ := h @[to_additive] instance [h : has_involutive_inv α] : has_involutive_inv αᵒᵈ := h @[to_additive] instance [h : div_inv_monoid α] : div_inv_monoid αᵒᵈ := h @[to_additive] instance [h : group α] : group αᵒᵈ := h @[to_additive] instance [h : comm_group α] : comm_group αᵒᵈ := h @[to_additive] instance [ordered_comm_group α] : ordered_comm_group αᵒᵈ := { .. order_dual.ordered_comm_monoid, .. order_dual.group } section group variables [group α] section typeclasses_left_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_nonpos_iff] lemma left.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_left a], simp } /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.nonneg_neg_iff] lemma left.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_left a], simp } @[simp, to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := by { rw ← mul_le_mul_iff_left a, simp } @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left] @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a := by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a := trans (inv_mul_le_iff_le_mul) $ by rw mul_one end typeclasses_left_le section typeclasses_left_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_pos_iff] lemma left.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_neg_iff] lemma left.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := by { rw [← mul_lt_mul_iff_left a], simp } @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left] @[to_additive] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a := by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a := trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one end typeclasses_left_lt section typeclasses_right_le variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_nonpos_iff] lemma right.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_right a], simp } /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.nonneg_neg_iff] lemma right.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_right a], simp } @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b := mul_inv_le_iff_le_mul.trans $ by rw one_mul @[to_additive] lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a := trans (mul_inv_le_iff_le_mul) $ by rw one_mul end typeclasses_right_le section typeclasses_right_lt variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_neg_iff "Uses `right` co(ntra)variant."] lemma right.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_pos_iff "Uses `right` co(ntra)variant."] lemma right.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] @[to_additive] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right] @[simp, to_additive] lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul] @[to_additive] lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a := trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul end typeclasses_right_lt section typeclasses_left_right_le variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp } alias neg_le_neg_iff ↔ le_of_neg_le_neg _ section variable (α) /-- `x ↦ x⁻¹` as an order-reversing equivalence. -/ @[to_additive "`x ↦ -x` as an order-reversing equivalence.", simps] def order_iso.inv : α ≃o αᵒᵈ := { to_equiv := (equiv.inv α).trans order_dual.to_dual, map_rel_iff' := λ a b, @inv_le_inv_iff α _ _ _ _ _ _ } end @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := (order_iso.inv α).symm_apply_le alias inv_le' ↔ inv_le_of_inv_le' _ attribute [to_additive neg_le_of_neg_le] inv_le_of_inv_le' @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := (order_iso.inv α).le_symm_apply @[to_additive] lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b := by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b := by simp [div_eq_mul_inv] @[simp, to_additive] lemma le_div_self_iff (a : α) {b : α} : a ≤ a / b ↔ b ≤ 1 := by simp [div_eq_mul_inv] alias sub_le_self_iff ↔ _ sub_le_self end typeclasses_left_right_le section typeclasses_left_right_lt variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp } @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := by rw [← inv_lt_inv_iff, inv_inv] @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := by rw [← inv_lt_inv_iff, inv_inv] alias lt_inv' ↔ lt_inv_of_lt_inv _ attribute [to_additive] lt_inv_of_lt_inv alias inv_lt' ↔ inv_lt_of_inv_lt' _ attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt' @[to_additive] lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b := by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b := by simp [div_eq_mul_inv] alias sub_lt_self_iff ↔ _ sub_lt_self end typeclasses_left_right_lt section pre_order variable [preorder α] section left_le variables [covariant_class α α (*) (≤)] {a : α} @[to_additive] lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (left.inv_le_one_iff.mpr h) h alias left.neg_le_self ← neg_le_self @[to_additive] lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (left.one_le_inv_iff.mpr h) end left_le section left_lt variables [covariant_class α α (*) (<)] {a : α} @[to_additive] lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a := (left.inv_lt_one_iff.mpr h).trans h alias left.neg_lt_self ← neg_lt_self @[to_additive] lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (left.one_lt_inv_iff.mpr h) end left_lt section right_le variables [covariant_class α α (swap (*)) (≤)] {a : α} @[to_additive] lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (right.inv_le_one_iff.mpr h) h @[to_additive] lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (right.one_le_inv_iff.mpr h) end right_le section right_lt variables [covariant_class α α (swap (*)) (<)] {a : α} @[to_additive] lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a := (right.inv_lt_one_iff.mpr h).trans h @[to_additive] lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (right.one_lt_inv_iff.mpr h) end right_lt end pre_order end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm] end has_le section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive] lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[simp, to_additive] lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c := by rw [← inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_lt_add_neg_iff] lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b := by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm] end has_lt end comm_group alias le_inv' ↔ le_inv_of_le_inv _ attribute [to_additive] le_inv_of_le_inv alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _ attribute [to_additive] one_le_of_inv_le_one alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _ attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _ attribute [to_additive] lt_of_inv_lt_inv alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _ attribute [to_additive] one_lt_of_inv_lt_one alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt attribute [to_additive] inv_lt_one_iff_one_lt alias left.inv_lt_one_iff ← inv_lt_one' attribute [to_additive neg_lt_zero] inv_lt_one' alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _ attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _ attribute [to_additive] mul_le_of_le_inv_mul alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le attribute [to_additive] le_inv_mul_of_mul_le alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul attribute [to_additive] inv_mul_le_iff_le_mul alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _ attribute [to_additive] mul_lt_of_lt_inv_mul alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt attribute [to_additive] lt_inv_mul_of_mul_lt alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul attribute [to_additive] lt_mul_of_inv_mul_lt attribute [to_additive] inv_mul_lt_of_lt_mul alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left attribute [to_additive] lt_mul_of_inv_mul_lt_left alias left.inv_le_one_iff ← inv_le_one' attribute [to_additive neg_nonpos] inv_le_one' alias left.one_le_inv_iff ← one_le_inv' attribute [to_additive neg_nonneg] one_le_inv' alias left.one_lt_inv_iff ← one_lt_inv' attribute [to_additive neg_pos] one_lt_inv' alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left' attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left' alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left] ordered_comm_group.le_of_mul_le_mul_left alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left] ordered_comm_group.lt_of_mul_lt_mul_left /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group [ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul npow, ..hf.comm_group f one mul inv div npow zpow } /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_le α] section right variables [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b := by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _ @[to_additive sub_le_sub_right] lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c := (div_le_div_iff_right c).2 h @[simp, to_additive sub_nonneg] lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp, to_additive sub_nonpos] lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[to_additive] lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c := by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le @[to_additive] lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c := by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] -- TODO: Should we get rid of `sub_le_iff_le_add` in favor of -- (a renamed version of) `tsub_le_iff_right`? @[priority 100] -- see Note [lower instance priority] instance add_group.to_has_ordered_sub {α : Type*} [add_group α] [has_le α] [covariant_class α α (swap (+)) (≤)] : has_ordered_sub α := ⟨λ a b c, sub_le_iff_le_add⟩ /-- `equiv.mul_right` as an `order_iso`. See also `order_embedding.mul_right`. -/ @[to_additive "`equiv.add_right` as an `order_iso`. See also `order_embedding.add_right`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_right (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_right a, to_equiv := equiv.mul_right a } @[simp, to_additive] lemma order_iso.mul_right_symm (a : α) : (order_iso.mul_right a).symm = order_iso.mul_right a⁻¹ := by { ext x, refl } end right section left variables [covariant_class α α (*) (≤)] /-- `equiv.mul_left` as an `order_iso`. See also `order_embedding.mul_left`. -/ @[to_additive "`equiv.add_left` as an `order_iso`. See also `order_embedding.add_left`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_left (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_left a, to_equiv := equiv.mul_left a } @[simp, to_additive] lemma order_iso.mul_left_symm (a : α) : (order_iso.mul_left a).symm = order_iso.mul_left a⁻¹ := by { ext x, refl } variables [covariant_class α α (swap (*)) (≤)] {a b c : α} @[simp, to_additive] lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_le_inv_iff] @[to_additive sub_le_sub_left] lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a := (div_le_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub_iff] lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b := by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff' @[to_additive] lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c := by rw [le_div_iff_mul_le, mul_comm] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le @[to_additive] lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c := by rw [div_le_iff_le_mul, mul_comm] alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add @[simp, to_additive] lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b := le_div_iff_mul_le.trans inv_mul_le_iff_le_mul' @[to_additive] lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b := by rw [inv_le_div_iff_le_mul, mul_comm] @[to_additive sub_le] lemma div_le'' : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm @[to_additive le_sub] lemma le_div'' : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm end has_le section preorder variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub] lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) : a / d ≤ b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm], exact mul_le_mul' hab hcd end end preorder end comm_group /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_lt α] section right variables [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b := by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _ @[to_additive sub_lt_sub_right] lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c := (div_lt_div_iff_right c).2 h @[simp, to_additive sub_pos] lemma one_lt_div' : 1 < a / b ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp, to_additive sub_neg] lemma div_lt_one' : a / b < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt alias sub_neg ← sub_lt_zero @[to_additive] lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c := by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c := by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add end right section left variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α} @[simp, to_additive] lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_lt_inv_iff] @[simp, to_additive] lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b := by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul] @[to_additive sub_lt_sub_left] lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a := (div_lt_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub_iff] lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b := by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff' @[to_additive] lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c := by rw [lt_div_iff_mul_lt, mul_comm] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c := by rw [div_lt_iff_lt_mul, mul_comm] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add @[to_additive] lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b := lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul' @[to_additive sub_lt] lemma div_lt'' : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm @[to_additive lt_sub] lemma lt_div'' : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm end has_lt section preorder variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub] lemma div_lt_div'' (hab : a < b) (hcd : c < d) : a / d < b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm], exact mul_lt_mul_of_lt_of_lt hab hcd end end preorder end comm_group section linear_order variables [group α] [linear_order α] [covariant_class α α (*) (≤)] section variable_names variables {a b c : α} @[to_additive] lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁)))) @[to_additive] lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩ /- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of) `div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/ @[to_additive] lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] : a / b ≤ a⁻¹ * b ↔ a ≤ b := begin rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff], exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul''' k k)), λ h, mul_le_mul' h h⟩, end /- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/ @[simp, to_additive] lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)] {a b : α}: a / b ≤ b / a ↔ a ≤ b := begin rw [div_eq_mul_inv b, mul_comm], exact div_le_inv_mul_iff, end @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end variable_names section densely_ordered variables [densely_ordered α] {a b c : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ c hc, calc a ≤ b * (b⁻¹ * c) : h _ (lt_inv_mul_iff_lt.mpr hc) ... = c : mul_inv_cancel_left b c @[to_additive] lemma le_of_forall_lt_one_mul_le (h : ∀ ε < 1, a * ε ≤ b) : a ≤ b := @le_of_forall_one_lt_le_mul αᵒᵈ _ _ _ _ _ _ h @[to_additive] lemma le_of_forall_one_lt_div_le (h : ∀ ε : α, 1 < ε → a / ε ≤ b) : a ≤ b := le_of_forall_lt_one_mul_le $ λ ε ε1, by simpa only [div_eq_mul_inv, inv_inv] using h ε⁻¹ (left.one_lt_inv_iff.2 ε1) @[to_additive] lemma le_iff_forall_one_lt_le_mul : a ≤ b ↔ ∀ ε, 1 < ε → a ≤ b * ε := ⟨λ h ε ε_pos, le_mul_of_le_of_one_le h ε_pos.le, le_of_forall_one_lt_le_mul⟩ @[to_additive] lemma le_iff_forall_lt_one_mul_le : a ≤ b ↔ ∀ ε < 1, a * ε ≤ b := @le_iff_forall_one_lt_le_mul αᵒᵈ _ _ _ _ _ _ end densely_ordered end linear_order /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj, ancestor ordered_add_comm_group linear_order] class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial] class linear_ordered_add_comm_group_with_top (α : Type*) extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α := (neg_top : - (⊤ : α) = ⊤) (add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, ancestor ordered_comm_group linear_order, to_additive] class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α @[to_additive] instance [linear_ordered_comm_group α] : linear_ordered_comm_group αᵒᵈ := { .. order_dual.ordered_comm_group, .. order_dual.linear_order α } section linear_ordered_comm_group variables [linear_ordered_comm_group α] {a b c : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid : linear_ordered_cancel_comm_monoid α := { le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left', mul_left_cancel := λ x y z, mul_left_cancel, ..‹linear_ordered_comm_group α› } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : linear_ordered_comm_group β := { ..linear_order.lift f hf, ..hf.ordered_comm_group f one mul inv div npow zpow } @[to_additive linear_ordered_add_comm_group.add_lt_add_left] lemma linear_ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := mul_lt_mul_left' h c @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] @[to_additive eq_zero_of_neg_eq] lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 := match lt_trichotomy a 1 with | or.inl h₁ := have 1 < a, from h ▸ one_lt_inv_of_inv h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 1, from h ▸ inv_lt_one'.mpr h₁, absurd h₁ this.asymm end @[to_additive exists_zero_lt] lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a := begin obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α), cases hy.lt_or_lt, { exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_max_order [nontrivial α] : no_max_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩ end ⟩ @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_min_order [nontrivial α] : no_min_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩ end ⟩ end linear_ordered_comm_group section covariant_add_le section has_neg /-- `abs a` is the absolute value of `a`. -/ @[to_additive "`abs a` is the absolute value of `a`", priority 100] -- see Note [lower instance priority] instance has_inv.to_has_abs [has_inv α] [has_sup α] : has_abs α := ⟨λ a, a ⊔ a⁻¹⟩ @[to_additive] lemma abs_eq_sup_inv [has_inv α] [has_sup α] (a : α) : |a| = a ⊔ a⁻¹ := rfl variables [has_neg α] [linear_order α] {a b: α} lemma abs_eq_max_neg : abs a = max a (-a) := rfl lemma abs_choice (x : α) : |x| = x ∨ |x| = -x := max_choice _ _ lemma abs_le' : |a| ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma le_abs : a ≤ |b| ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ |a| := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ |a| := le_max_right _ _ lemma lt_abs : a < |b| ↔ a < b ∨ a < -b := lt_max_iff theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : |a| ≤ |b| := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (|a|) := sup_ind _ _ h1 h2 end has_neg section add_group variables [add_group α] [linear_order α] @[simp] lemma abs_neg (a : α) : | -a| = |a| := begin rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg] end lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : |a| = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq_abs {a b : α} : |a| = |b| ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_sub_comm (a b : α) : |a - b| = |b - a| := calc |a - b| = | - (b - a)| : congr_arg _ (neg_sub b a).symm ... = |b - a| : abs_neg (b - a) variables [covariant_class α α (+) (≤)] {a b c : α} lemma abs_of_nonneg (h : 0 ≤ a) : |a| = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : |a| = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : |a| = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : |a| = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : |0| = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_pos : 0 < |a| ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < |a| := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < |a| := abs_pos.2 h.ne lemma neg_abs_le_self (a : α) : -|a| ≤ a := begin cases le_total 0 a with h h, { calc -|a| = - a : congr_arg (has_neg.neg) (abs_of_nonneg h) ... ≤ 0 : neg_nonpos.mpr h ... ≤ a : h }, { calc -|a| = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h) ... ≤ a : (neg_neg a).le } end lemma neg_abs_le_neg (a : α) : -|a| ≤ -a := by simpa using neg_abs_le_self (-a) lemma abs_nonneg (a : α) : 0 ≤ |a| := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : | |a| | = |a| := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : |a| = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : |a| ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero variable [covariant_class α α (swap (+)) (≤)] lemma abs_lt : |a| < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : |a| < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : |a| < b) : a < b := (abs_lt.mp h).2 lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = |a - b| := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = |b - a| := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } end add_group end covariant_add_le section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {a b c d : α} lemma abs_le : |a| ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma le_abs' : a ≤ |b| ↔ b ≤ -a ∨ a ≤ b := by rw [le_abs, or.comm, le_neg] lemma neg_le_of_abs_le (h : |a| ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : |a| ≤ b) : a ≤ b := (abs_le.mp h).2 @[to_additive] lemma apply_abs_le_mul_of_one_le' {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} {a : α} (h₁ : 1 ≤ f a) (h₂ : 1 ≤ f (-a)) : f (|a|) ≤ f a * f (-a) := (le_total a 0).by_cases (λ ha, (abs_of_nonpos ha).symm ▸ le_mul_of_one_le_left' h₁) (λ ha, (abs_of_nonneg ha).symm ▸ le_mul_of_one_le_right' h₂) @[to_additive] lemma apply_abs_le_mul_of_one_le {β : Type*} [mul_one_class β] [preorder β] [covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)] {f : α → β} (h : ∀ x, 1 ≤ f x) (a : α) : f (|a|) ≤ f a * f (-a) := apply_abs_le_mul_of_one_le' (h _) (h _) /-- The **triangle inequality** in `linear_ordered_add_comm_group`s. -/ lemma abs_add (a b : α) : |a + b| ≤ |a| + |b| := abs_le.2 ⟨(neg_add (|a|) (|b|)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ lemma abs_add' (a b : α) : |a| ≤ |b| + |b + a| := by simpa using abs_add (-b) (b + a) theorem abs_sub (a b : α) : |a - b| ≤ |a| + |b| := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : |a - b| ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add'] lemma abs_sub_lt_iff : |a - b| < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add'] lemma sub_le_of_abs_sub_le_left (h : |a - b| ≤ c) : b - c ≤ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : |a - b| ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : |a - b| < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : |a - b| < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : |a| - |b| ≤ |a - b| := sub_le_iff_le_add.2 $ calc |a| = |a - b + b| : by rw [sub_add_cancel] ... ≤ |a - b| + |b| : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : | |a| - |b| | ≤ |a - b| := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≤ b) : |a| = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : |b| ≤ max (|a|) (|c|) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩ lemma eq_of_abs_sub_eq_zero {a b : α} (h : |a - b| = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_sub_le (a b c : α) : |a - c| ≤ |a - b| + |b - c| := calc |a - c| = |a - b + (b - c)| : by rw [sub_add_sub_cancel] ... ≤ |a - b| + |b - c| : abs_add _ _ lemma abs_add_three (a b c : α) : |a + b + c| ≤ |a| + |b| + |c| := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : |a - b| ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : |a - b| ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) lemma max_sub_max_le_max (a b c d : α) : max a b - max c d ≤ max (a - c) (b - d) := begin simp only [sub_le_iff_le_add, max_le_iff], split, calc a = a - c + c : (sub_add_cancel a c).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_left _ _) (le_max_left _ _), calc b = b - d + d : (sub_add_cancel b d).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_right _ _) (le_max_right _ _) end lemma abs_max_sub_max_le_max (a b c d : α) : |max a b - max c d| ≤ max (|a - c|) (|b - d|) := begin refine abs_sub_le_iff.2 ⟨_, _⟩, { exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) }, { rw [abs_sub_comm a c, abs_sub_comm b d], exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) } end lemma abs_min_sub_min_le_max (a b c d : α) : |min a b - min c d| ≤ max (|a - c|) (|b - d|) := by simpa only [max_neg_neg, neg_sub_neg, abs_sub_comm] using abs_max_sub_max_le_max (-a) (-b) (-c) (-d) lemma abs_max_sub_max_le_abs (a b c : α) : |max a c - max b c| ≤ |a - b| := by simpa only [sub_self, abs_zero, max_eq_left (abs_nonneg _)] using abs_max_sub_max_le_max a c b c instance with_top.linear_ordered_add_comm_group_with_top : linear_ordered_add_comm_group_with_top (with_top α) := { neg := option.map (λ a : α, -a), neg_top := @option.map_none _ _ (λ a : α, -a), add_neg_cancel := begin rintro (a | a) ha, { exact (ha rfl).elim }, { exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)) } end, .. with_top.linear_ordered_add_comm_monoid_with_top, .. option.nontrivial } @[simp, norm_cast] lemma with_top.coe_neg (a : α) : ((-a : α) : with_top α) = -a := rfl end linear_ordered_add_comm_group namespace add_comm_group /-- A collection of elements in an `add_comm_group` designated as "non-negative". This is useful for constructing an `ordered_add_commm_group` by choosing a positive cone in an exisiting `add_comm_group`. -/ @[nolint has_inhabited_instance] structure positive_cone (α : Type*) [add_comm_group α] := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (-a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) /-- A positive cone in an `add_comm_group` induces a linear order if for every `a`, either `a` or `-a` is non-negative. -/ @[nolint has_inhabited_instance] structure total_positive_cone (α : Type*) [add_comm_group α] extends positive_cone α := (nonneg_decidable : decidable_pred nonneg) (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) /-- Forget that a `total_positive_cone` is total. -/ add_decl_doc total_positive_cone.to_positive_cone end add_comm_group namespace ordered_add_comm_group open add_comm_group /-- Construct an `ordered_add_comm_group` by designating a positive cone in an existing `add_comm_group`. -/ def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : positive_cone α) : ordered_add_comm_group α := { le := λ a b, C.nonneg (b - a), lt := λ a b, C.pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [C.pos_iff]; simp, le_refl := λ a, by simp [C.zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact C.add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ C.nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..‹add_comm_group α› } end ordered_add_comm_group namespace linear_ordered_add_comm_group open add_comm_group /-- Construct a `linear_ordered_add_comm_group` by designating a positive cone in an existing `add_comm_group` such that for every `a`, either `a` or `-a` is non-negative. -/ def mk_of_positive_cone {α : Type*} [add_comm_group α] (C : total_positive_cone α) : linear_ordered_add_comm_group α := { le_total := λ a b, by { convert C.nonneg_total (b - a), change C.nonneg _ = _, congr, simp, }, decidable_le := λ a b, C.nonneg_decidable _, ..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone } end linear_ordered_add_comm_group namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G × H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group } end type_tags section norm_num_lemmas /- The following lemmas are stated so that the `norm_num` tactic can use them with the expected signatures. -/ variables [ordered_comm_group α] {a b : α} @[to_additive neg_le_neg] lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ := inv_le_inv_iff.mpr @[to_additive neg_lt_neg] lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ := inv_lt_inv_iff.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 := inv_lt_one_iff_one_lt.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 := inv_le_one'.mpr @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ := one_le_inv'.mpr end norm_num_lemmas
68c62def1ca19ea247c9c8fdf5767a2b9db699b3
11e28114d9553ecd984ac4819661ffce3068bafe
/src/policy.lean
b2359b2cef16264b1da3f32f8cfae9b88618f684
[ "MIT" ]
permissive
EdAyers/lean-subtask
9a26eb81f0c8576effed4ca94342ae1281445c59
04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b
refs/heads/master
1,586,516,665,621
1,558,701,948,000
1,558,701,948,000
160,983,035
4
1
null
null
null
null
UTF-8
Lean
false
false
5,892
lean
/- Author: E.W.Ayers © 2019 -/ import .M .refine open expr tactic expr.zipper namespace robot meta def is_term : expr → tactic bool := λ e, do T ← tactic.infer_type e >>= instantiate_mvars, pure $ expr.is_sort T def weak : ℕ := 1 def medium : ℕ := 2 def strong : ℕ := 3 meta def requires_nonmeta_variable_that_is_already_present (r : rule) : M nat := do ce ← get_ce, lhs_locals ← list_local_const_terms $ r.lhs, rhs_locals ← list_local_const_terms $ r.rhs, lhs_reqs ← pure $ list.filter (∉ rhs_locals) lhs_locals, ce_locals ← list_local_const_terms $ ce, let result := list.any ce_locals (∈ lhs_reqs), pure $ if result then weak else 0 meta def requires_complex_term_that_is_already_present (r : rule) : M nat := do ce ← get_ce, subterms ← list.map zipper.current <$> (get_smallest_complex_subterms $ r.lhs), subterms ← pure $ subterms.filter $ λ t, ¬ expr.occurs t r.rhs, unify_present ← subterms.mfilter $ λ t, zipper.has_occurences t ce, directly_present ← pure $ unify_present.filter $ λ t, expr.occurs t ce, pure $ if unify_present.empty then 0 else if directly_present.empty then medium else strong meta def requires_nonmeta_variable_present_in_rule (r : rule) : M nat := do -- that is, look through local constants and find hypotheses which would introduce these. lcs ← list_local_const_terms r.lhs, rs ← list.msome (λ lc, bnot <$> list.empty <$> M.submatch lc) lcs, pure $ if rs then weak else 0 -- meta def requires_complex_term_that_is_present_in_rule (r : rule) : M nat := do /- I feel like this one will just always be true. A better refinement would be: -/ meta def get_candidate_actions : Z → M (list action) := tree.zipper.get_non_failures (λ z, as_action z) meta def get_sister_candidate_actions_aux : Z → list action → M (list action) |z acc := do some (z,i) ← pure $ tree.zipper.up_with_index z | pure acc, cs ← list.mcollect get_candidate_actions $ list.take i $ z.down_all, acc ← pure $ cs ++ acc, if z.item.is_strat then pure acc else do get_sister_candidate_actions_aux z acc meta def get_merger_actions : list action → list action → M ( list action) |l₁ l₂ := list.mcollect (λ a₁ : action, list.mchoose (λ a₂ : action, strategy.merge a₁.1 a₂.1 >>= λ s, pure (s,a₂.2)) l₂) l₁ meta def score_rule (r : rule_app) : M int := do is_local ← r.is_local_hypothesis, meta_count ← r.count_metas, if (meta_count > 1) then pure (-10) else do ce ← get_ce, lookahead ← get_lookahead, -- [IDEA]: score by symbol overlap ce_symbs ← zipper.count_symbols $ ce, lhs_symbs ← zipper.count_symbols $ r.lhs, let overlap := table.size $ ce_symbs ∩ lhs_symbs, let symm_diff := table.size (ce_symbs ∪ lhs_symbs) - overlap, -- [TODO] if the LHS is in the lookahead table then use that has_diom ← (if ¬ expr.is_composite r.r.lhs then pure ff else (do let pts := ce :: lookahead.map rule_app.rhs, matches ← state_t.lift $ list.mchoose (λ x, do zipper.find_subterm r.lhs (zipper.zip x), pure x ) pts, pure $ bnot $ list.empty $ matches )), is_comm ← rule_app.is_commuter r, pure $ (if is_comm then -5 else 0) + (if is_local then 10 else 0) + (if has_diom then 10 else 0) - meta_count - symm_diff meta def score_strategy : strategy → M int |(strategy.ReduceDistance a b) := do ce ← get_ce, d ← get_distance ce a b, pure $ max (10 - d) 0 |(strategy.Use r) := score_rule r meta def simple_evaluate : list action → M evaluation |[] := pure [] |l@(⟨s,sz⟩::t) := do -- sisters ← get_sister_candidate_actions_aux sz [], -- mergers ← get_merger_actions sisters l, -- trace mergers, scores ← list.mmap (score_strategy ∘ prod.fst) l, scoreboard ← pure $ list.zip l scores, let scoreboard := scoreboard.qsort (λ x y, x.2 > y.2), scoreboard_pretty ← scoreboard.mmap (λ ⟨s,b⟩, do pps ← tactic.pp s, pure $ (to_fmt $ to_string b) ++ format.space ++ pps), tactic.trace_m "\nscore: \n" $ scoreboard_pretty, tactic.trace " ", -- ⟨a,_⟩ ← list.maxby (prod.snd) $ list.zip l scores, pure scoreboard /- [TODO] give a human-tuned, ad-hoc score based on: - [ ] what previous strategies were chosen from? That is, suppose a strategy came up earlier, then it would be good to detect that it should be a good idea now. - [x] Is the strategy a diom? If yes then it should be preferred, but only if it doesn't introduce too many more metas. - [ ] How many siblings does the strategy have? If this number is low we should prefer it. - [x] Is the rule an assumption, or a library rule? - [ ] Does the rule have high definitional depth? - [x] How many metas are introduced? - [ ] Some type-theoretical information??? eg, if the rule is for a specific type or for any type. - [x] on a `Use`, if there are large subterms already present then that's good. -/ /-- A simple scoring heuristic for lists of terms. [TODO] For now this is just whatever works but there is some theory that can go in here. -/ meta def simple_overall_score : list (action × score) → M score |[x] := pure $ 10 |l := do let l := l.filter (λ x, x.2 ≥ -5), match list.partition (λ x : _ × score, x.2 ≥ 0) l with |⟨[],[]⟩ := pure $ -100 -- [TODO], special case: it's impossible? |⟨[],negs⟩ := do pure $ 5 - negs.length |⟨xs,_⟩ := pure $ 5 - xs.length end meta def simple_policy : policy := { evaluate := simple_evaluate , get_overall_score := simple_overall_score } end robot
74728ada10601dd6972c0afd49f6466fb6176a87
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/limits/shapes/wide_pullbacks.lean
e7b9f0133b160844cf2e7197bdf4136d3141e35e
[ "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
5,261
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.has_limits import category_theory.thin /-! # Wide pullbacks We define the category `wide_pullback_shape`, (resp. `wide_pushout_shape`) which is the category obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element. Limits of this shape are wide pullbacks (pushouts). The convenience method `wide_cospan` (`wide_span`) constructs a functor from this category, hitting the given morphisms. We use `wide_pullback_shape` to define ordinary pullbacks (pushouts) by using `J := walking_pair`, which allows easy proofs of some related lemmas. Furthermore, wide pullbacks are used to show the existence of limits in the slice category. Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`. Typeclasses `has_wide_pullbacks` and `has_finite_wide_pullbacks` assert the existence of wide pullbacks and finite wide pullbacks. -/ universes v u open category_theory category_theory.limits namespace category_theory.limits variable (J : Type v) /-- A wide pullback shape for any type `J` can be written simply as `option J`. -/ @[derive inhabited] def wide_pullback_shape := option J /-- A wide pushout shape for any type `J` can be written simply as `option J`. -/ @[derive inhabited] def wide_pushout_shape := option J namespace wide_pullback_shape variable {J} /-- The type of arrows for the shape indexing a wide pullback. -/ @[derive decidable_eq] inductive hom : wide_pullback_shape J → wide_pullback_shape J → Type v | id : Π X, hom X X | term : Π (j : J), hom (some j) none attribute [nolint unused_arguments] hom.decidable_eq instance struct : category_struct (wide_pullback_shape J) := { hom := hom, id := λ j, hom.id j, comp := λ j₁ j₂ j₃ f g, begin cases f, exact g, cases g, apply hom.term _ end } instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pullback_shape J)⟩ local attribute [tidy] tactic.case_bash instance subsingleton_hom (j j' : wide_pullback_shape J) : subsingleton (j ⟶ j') := ⟨by tidy⟩ instance category : small_category (wide_pullback_shape J) := thin_category @[simp] lemma hom_id (X : wide_pullback_shape J) : hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] /-- Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a fixed object. -/ @[simps] def wide_cospan (B : C) (objs : J → C) (arrows : Π (j : J), objs j ⟶ B) : wide_pullback_shape J ⥤ C := { obj := λ j, option.cases_on j B objs, map := λ X Y f, begin cases f with _ j, { apply (𝟙 _) }, { exact arrows j } end } /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_cospan` -/ def diagram_iso_wide_cospan (F : wide_pullback_shape J ⥤ C) : F ≅ wide_cospan (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.term j)) := nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy end wide_pullback_shape namespace wide_pushout_shape variable {J} /-- The type of arrows for the shape indexing a wide psuhout. -/ @[derive decidable_eq] inductive hom : wide_pushout_shape J → wide_pushout_shape J → Type v | id : Π X, hom X X | init : Π (j : J), hom none (some j) attribute [nolint unused_arguments] hom.decidable_eq instance struct : category_struct (wide_pushout_shape J) := { hom := hom, id := λ j, hom.id j, comp := λ j₁ j₂ j₃ f g, begin cases f, exact g, cases g, apply hom.init _ end } instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pushout_shape J)⟩ local attribute [tidy] tactic.case_bash instance subsingleton_hom (j j' : wide_pushout_shape J) : subsingleton (j ⟶ j') := ⟨by tidy⟩ instance category : small_category (wide_pushout_shape J) := thin_category @[simp] lemma hom_id (X : wide_pushout_shape J) : hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] /-- Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a fixed object. -/ @[simps] def wide_span (B : C) (objs : J → C) (arrows : Π (j : J), B ⟶ objs j) : wide_pushout_shape J ⥤ C := { obj := λ j, option.cases_on j B objs, map := λ X Y f, begin cases f with _ j, { apply (𝟙 _) }, { exact arrows j } end } /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_span` -/ def diagram_iso_wide_span (F : wide_pushout_shape J ⥤ C) : F ≅ wide_span (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.init j)) := nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy end wide_pushout_shape variables (C : Type u) [category.{v} C] /-- `has_wide_pullbacks` represents a choice of wide pullback for every collection of morphisms -/ abbreviation has_wide_pullbacks : Prop := Π (J : Type v), has_limits_of_shape (wide_pullback_shape J) C /-- `has_wide_pushouts` represents a choice of wide pushout for every collection of morphisms -/ abbreviation has_wide_pushouts : Prop := Π (J : Type v), has_colimits_of_shape (wide_pushout_shape J) C end category_theory.limits
d0f804132b45e4ecd074a13b87aad0cdbda9c042
1a61aba1b67cddccce19532a9596efe44be4285f
/hott/algebra/category/iso.hlean
23877991a058767d5913dc8fe8c162c4419073d7
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
14,634
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer -/ import .precategory types.sigma arity open eq category prod equiv is_equiv sigma sigma.ops is_trunc namespace iso structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {retraction_of : b ⟶ a} (retraction_comp : retraction_of ∘ f = id) structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {section_of : b ⟶ a} (comp_section : f ∘ section_of = id) structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) := {inverse : b ⟶ a} (left_inverse : inverse ∘ f = id) (right_inverse : f ∘ inverse = id) attribute is_iso.inverse [quasireducible] attribute is_iso [multiple-instances] open split_mono split_epi is_iso abbreviation retraction_of [unfold 6] := @split_mono.retraction_of abbreviation retraction_comp [unfold 6] := @split_mono.retraction_comp abbreviation section_of [unfold 6] := @split_epi.section_of abbreviation comp_section [unfold 6] := @split_epi.comp_section abbreviation inverse [unfold 6] := @is_iso.inverse abbreviation left_inverse [unfold 6] := @is_iso.left_inverse abbreviation right_inverse [unfold 6] := @is_iso.right_inverse postfix `⁻¹` := inverse --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C definition split_mono_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_mono f := split_mono.mk !left_inverse definition split_epi_of_is_iso [instance] [priority 300] [reducible] (f : a ⟶ b) [H : is_iso f] : split_epi f := split_epi.mk !right_inverse definition is_iso_id [instance] [priority 500] (a : ob) : is_iso (ID a) := is_iso.mk !id_comp !id_comp definition is_iso_inverse [instance] [priority 200] (f : a ⟶ b) [H : is_iso f] : is_iso f⁻¹ := is_iso.mk !right_inverse !left_inverse definition left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := by rewrite [-(id_right g), -Hr, assoc, Hl, id_left] definition retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_comp H2 definition section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h := (left_inverse_eq_right_inverse H2 !comp_section)⁻¹ definition inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !left_inverse H2 definition inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := (left_inverse_eq_right_inverse H2 !right_inverse)⁻¹ definition retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : retraction_of f = section_of f := retraction_eq !comp_section definition is_iso_of_split_epi_of_split_mono (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] : is_iso f := is_iso.mk ((retraction_eq_section f) ▸ (retraction_comp f)) (comp_section f) definition inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := inverse_eq_left !left_inverse definition inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)] : (f⁻¹)⁻¹ = f := inverse_eq_right !left_inverse definition inverse_eq_inverse {f g : a ⟶ b} [H : is_iso f] [H : is_iso g] (p : f = g) : f⁻¹ = g⁻¹ := by cases p;apply inverse_unique definition retraction_id (a : ob) : retraction_of (ID a) = id := retraction_eq !id_comp definition section_id (a : ob) : section_of (ID a) = id := section_eq !id_comp definition id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id := inverse_eq_left !id_comp definition split_mono_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) := split_mono.mk (show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id, by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp]) definition split_epi_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) := split_epi.mk (show (g ∘ f) ∘ section_of f ∘ section_of g = id, by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section]) definition is_iso_comp [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b) [Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) := !is_iso_of_split_epi_of_split_mono definition is_hprop_is_iso [instance] (f : hom a b) : is_hprop (is_iso f) := begin apply is_hprop.mk, intro H H', cases H with g li ri, cases H' with g' li' ri', fapply (apd0111 (@is_iso.mk ob C a b f)), apply left_inverse_eq_right_inverse, apply li, apply ri', apply is_hprop.elim, apply is_hprop.elim, end end iso open iso /- isomorphic objects -/ structure iso {ob : Type} [C : precategory ob] (a b : ob) := (to_hom : hom a b) [struct : is_iso to_hom] namespace iso variables {ob : Type} [C : precategory ob] variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} include C infix `≅`:50 := iso attribute struct [instance] [priority 400] attribute to_hom [coercion] protected definition MK [constructor] (f : a ⟶ b) (g : b ⟶ a) (H1 : g ∘ f = id) (H2 : f ∘ g = id) := @(mk f) (is_iso.mk H1 H2) definition to_inv [unfold 5] (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹ definition to_left_inverse [unfold 5] (f : a ≅ b) : (to_hom f)⁻¹ ∘ (to_hom f) = id := left_inverse (to_hom f) definition to_right_inverse [unfold 5] (f : a ≅ b) : (to_hom f) ∘ (to_hom f)⁻¹ = id := right_inverse (to_hom f) protected definition refl [constructor] (a : ob) : a ≅ a := mk (ID a) protected definition symm [constructor] ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (to_hom H)⁻¹ protected definition trans [constructor] ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (to_hom H2 ∘ to_hom H1) definition iso_mk_eq {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f') : iso.mk f = iso.mk f' := apd011 iso.mk p !is_hprop.elim definition iso_eq {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' := by (cases f; cases f'; apply (iso_mk_eq p)) -- The structure for isomorphism can be characterized up to equivalence by a sigma type. protected definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) := begin fapply (equiv.mk), {intro S, apply iso.mk, apply (S.2)}, {fapply adjointify, {intro p, cases p with f H, exact sigma.mk f H}, {intro p, cases p, apply idp}, {intro S, cases S, apply idp}}, end -- The type of isomorphisms between two objects is a set definition is_hset_iso [instance] : is_hset (a ≅ b) := begin apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv (!iso.sigma_char), end definition iso_of_eq [unfold 5] (p : a = b) : a ≅ b := eq.rec_on p (iso.refl a) definition hom_of_eq [reducible] [unfold 5] (p : a = b) : a ⟶ b := iso.to_hom (iso_of_eq p) definition inv_of_eq [reducible] [unfold 5] (p : a = b) : b ⟶ a := iso.to_inv (iso_of_eq p) definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) := eq.rec_on p idp definition iso_of_eq_con (p : a = b) (q : b = c) : iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) := eq.rec_on q (eq.rec_on p (iso_eq !id_comp⁻¹)) section open funext variables {X : Type} {x y : X} {F G : X → ob} definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y)) : p ▸ f = hom_of_eq (apd10 p y) ∘ f ∘ inv_of_eq (apd10 p x) := by induction p; exact !id_leftright⁻¹ definition transport_hom_of_eq_right (p : x = y) (f : hom c (F x)) : p ▸ f = hom_of_eq (ap F p) ∘ f := by induction p; exact !id_left⁻¹ definition transport_hom_of_eq_left (p : x = y) (f : hom (F x) c) : p ▸ f = f ∘ inv_of_eq (ap F p) := by induction p; exact !id_right⁻¹ definition transport_hom (p : F ~ G) (f : hom (F x) (F y)) : eq_of_homotopy p ▸ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) := calc eq_of_homotopy p ▸ f = hom_of_eq (apd10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apd10 (eq_of_homotopy p) x) : transport_hom_of_eq ... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {right_inv apd10 p} end structure mono [class] (f : a ⟶ b) := (elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) structure epi [class] (f : a ⟶ b) := (elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f := mono.mk (λ c g h H, calc g = id ∘ g : by rewrite id_left ... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp ... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc] ... = id ∘ h : by rewrite retraction_comp ... = h : by rewrite id_left) definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f := epi.mk (λ c g h H, calc g = g ∘ id : by rewrite id_right ... = g ∘ f ∘ section_of f : by rewrite -(comp_section f) ... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc] ... = h ∘ id : by rewrite comp_section ... = h : by rewrite id_right) definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g] : mono (g ∘ f) := mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), begin rewrite *assoc, exact H end, !mono.elim (!mono.elim H2)) definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g] : epi (g ∘ f) := epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, begin rewrite -*assoc, exact H end, !epi.elim (!epi.elim H2)) end iso namespace iso /- rewrite lemmas for inverses, modified from https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v -/ section variables {ob : Type} [C : precategory ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq definition comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse definition comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse definition inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p := by rewrite [assoc, left_inverse, id_left] definition comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g := by rewrite [assoc, right_inverse, id_left] definition comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r := by rewrite [-assoc, right_inverse, id_right] definition inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f := by rewrite [-assoc, left_inverse, id_right] definition comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ := inverse_eq_left (show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from by rewrite [-assoc, inverse_comp_cancel_left, left_inverse]) definition inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▸ comp_inverse q⁻¹ g definition inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▸ comp_inverse q f⁻¹ definition inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▸ inverse_comp_inverse_left q r⁻¹ end section variables {ob : Type} {C : precategory ob} include C variables {d c b a : ob} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq definition comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▸ comp_inverse_cancel_left q g definition comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▸ inverse_comp_cancel_right f q definition eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y := (comp_eq_of_eq_inverse_comp H⁻¹)⁻¹ definition eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q := (comp_eq_of_eq_comp_inverse H⁻¹)⁻¹ variable {Hq} definition inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▸ inverse_comp_cancel_left q p definition comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▸ comp_inverse_cancel_right r q definition eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z := (inverse_comp_eq_of_eq_comp H⁻¹)⁻¹ definition eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ := (comp_inverse_eq_of_eq_comp H⁻¹)⁻¹ definition eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹ definition eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹ definition inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h := (eq_inverse_of_comp_eq_id' H⁻¹)⁻¹ definition inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h := (eq_inverse_of_comp_eq_id H⁻¹)⁻¹ variable [Hq] definition eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q := eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q definition eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q := eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q definition eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹ definition eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹ end end iso
f85a526abc0bf6870b949967bf22dcc36eb757c0
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/aexp/properties.lean
cb76c036711870959147c4aa12aa5010d0d210f2
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
1,988
lean
/- This file contains properties for `aexp`. -/ import .type namespace acie ----------------------------------------------------------------- namespace aexp ----------------------------------------------------------------- variables {V : Type} [decidable_eq V] -- Type of variable names variables {vs : Type → Type} [vset vs V] -- Type of variable name sets variables {W X Y Z : vs V} -- Variable name sets -- Paper: Proposition 6.1 (b) theorem self_eq_subst_var_self (α : aexp X) : α = aexp.subst.apply (aexp.subst.id X) α := quot.induction_on α $ λ e, quot.sound $ aeq.self_aeq_subst_var e -- Paper: Proposition 6.2 theorem subst_F_comp_var_eq_F (F : aexp.subst X Y) : aexp.subst.apply F ∘ aexp.subst.app (aexp.subst.id X) = aexp.subst.app F := funext begin intro x, simp [function.comp], cases F with F, apply quot.lift_beta (aexp.of_exp ∘ exp.subst.apply F) (eq_of_aeq F) (exp.var x) end theorem subst.left_id (F : aexp.subst X Y) : aexp.subst.id Y ∘ F ≈ F := begin cases F with F, simp [has_comp.comp, setoid.r, subst.eq, subst.app], apply funext, intro x, apply quotient.sound, simp [setoid.r, function.comp], exact aeq.id.symm (aeq.self_aeq_subst_var (F x)) end theorem subst.right_id (F : aexp.subst X Y) : F ∘ aexp.subst.id X ≈ F := begin cases F with F, simp [has_comp.comp, setoid.r, subst.eq, function.comp, exp.subst.apply] end theorem subst.assoc (H : aexp.subst Y Z) (G : aexp.subst X Y) (F : aexp.subst W X) : H ∘ (G ∘ F) ≈ (H ∘ G) ∘ F := begin cases H with H, cases G with G, cases F with F, simp [has_comp.comp, setoid.r, subst.eq, subst.app], apply funext, intro w, apply quotient.sound, simp [setoid.r, function.comp], exact aeq.subst_comp G H (F w) end end /- namespace -/ aexp ------------------------------------------------------- end /- namespace -/ acie -------------------------------------------------------
06ca6c27b553b76f578ed12b7c0839051c14fdf8
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/order/filter/basic.lean
7c4d8f8bdcbfa6cb1b0f275a896c518126edb8b7
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
93,440
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 -/ import order.galois_connection order.zorn import data.set.finite /-! # Theory of filters on sets ## Main definitions * `filter` : filter on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `join` : operations on filters; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`. -/ open lattice set universes u v w x y open_locale classical 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) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.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 ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := 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, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨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) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], 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 ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ principal s := 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} ∈ f}, 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 ↔ {t | s ∈ filter.sets t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, 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, x ∈ f := 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 := generate_sets g, 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 : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } 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, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /- 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 h, generate_sets.basic h, 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) (b ∈ g), 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 ↔ ∃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) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨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) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := 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 α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ 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, by have := univ_mem_sets ; finish) /- 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⟩, show s ∈ complete_lattice.inf f g, from 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 α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, 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 α) := λ _ _, principal_mono.2 @[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 ↔ 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) : ∃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 → 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 := have ∅ ∈ f ⊓ principal (- s), 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 eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end 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 have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [mem_Union]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s) : s ∈ infi f ↔ s ∈ ⋃ i, (f i).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃ i, (f i).sets, by rw infi_sets_eq h ne @[nolint] -- Intentional use of `≥` lemma binfi_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 @[nolint] -- Intentional use of `≥` lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ t ∈ ⋃ i ∈ s, (f i).sets := by rw [← binfi_sets_eq h ne] 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 lemma mem_infi_finite {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets, by rw infi_sets_eq_finite @[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) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅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 /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} (f : filter α) (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (f.eventually_of_forall hq) /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} (hf : f ≠ ⊥) {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := begin assume h', have := h.and h', simp only [and_not_self, eventually_false_iff_eq_bot] at this, exact hf this end lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (f.eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from f.eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hf : f ≠ ⊥) : ∃ x, p x := (hp.frequently hf).exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ /- 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) : 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 ↔ { x | x ∈ t → x ∈ s } ∈ f := 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 @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, principal (f i)) = principal (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, principal (f i)) = principal (⋂i, f i) := by simpa using infi_principal_finset finset.univ f 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 ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, 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, 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] } lemma cofinite_ne_bot (hi : set.infinite (@set.univ α)) : @cofinite α ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ λ s hs hn, by change set.finite _ at hs; rw [hn, set.compl_empty] at hs; exact hi hs /-- 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, ∃t∈ g, (∀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 lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp only [has_bind.bind, pure, 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 [has_bind.bind, pure, functor.map, 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 α) := 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 α) ↔ 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 ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨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 : monotone (map m) := (gc_map_comap m).monotone_l lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[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 le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top 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 ∧ 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, comap_mono $ 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₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (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) (hsg : s ∈ g) (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) (hsg : s ∈ g) (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) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (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) (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) (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, ∃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_ne_bot_of_range_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : range m ∈ f) : comap m f ≠ ⊥ := comap_neq_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := inhabited_of_mem_sets hf (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) {s : set α} (hs : m '' s ∈ f) : (comap m f ⊓ principal s) ≠ ⊥ := begin refine compl_compl s ▸ mt mem_sets_of_neq_bot _, rintros ⟨t, ht, hts⟩, rcases inhabited_of_mem_sets hf (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : function.surjective m) : comap m f ≠ ⊥ := comap_ne_bot_of_range_mem hf $ univ_mem_sets' hm @[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, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → 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, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] 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) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f, filter_upwards [h, hs], simp only [subset_def, mem_preimage, 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), have ∃i, preimage m s ∈ f i, 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_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (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 map_inf_le (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage, 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 : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) 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), ⟨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, m '' s ∈ g) : 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 α) ↔ 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 α) := 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 ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, 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 ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀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) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨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, ∀u ∈ g, set.seq t u ∈ h) : 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 ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f), 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), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ f i, by rw [mem_infi 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 → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_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₂, f ⁻¹' s ∈ l₁ := 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_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_cong hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 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 γ} (hg : tendsto g y z) (hf : tendsto f x y) : 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.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) (hx : x ≠ ⊥) : y ≠ ⊥ := neq_bot_of_le_neq_bot (map_ne_bot hx) 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, tendsto_comap.comp h, 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) : 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.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_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 := 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₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end 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) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g := 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 ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, 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.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) 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_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {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_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := by rw [(≠), prod_eq_bot, not_or_distrib] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ 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] 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 α _ := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [nonempty α] [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 [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := let ⟨a⟩ := ‹nonempty α› in iff.intro (assume h, infi_sets_induct h ⟨a, 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 [nonempty α] [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}⟩) (by apply_instance) ... = (⨅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) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : {x | f₁ x ≤ f₂ x} ∈ l) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_top_mono [preorder β] (l : filter α) : monotone (λ f : α → β, tendsto f l at_top) := λ f₁ f₂ h, tendsto_at_top_mono' l $ univ_mem_sets' h section ordered_monoid variables [ordered_cancel_comm_monoid β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : {x | 0 ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_left) hf) hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' l (univ_mem_sets' hf) hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : {x | 0 ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' l hf (univ_mem_sets' hg) lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_left) ((tendsto_at_top _ _).1 hf (C + b)) lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_right) ((tendsto_at_top _ _).1 hf (b + C)) lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : {x | f x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : f x ≤ C), add_le_add_right hx (g x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' l C (univ_mem_sets' hC) lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : {x | g x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : g x ≤ C), add_le_add_left hx (f x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' l C (univ_mem_sets' hC) end ordered_monoid section ordered_group variables [ordered_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : {x | C ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simp [hf]) (by simp [hg]) lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : {x | C ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) end ordered_group lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [decidable_linear_order α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → b ≥ f a := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top.2 finset.exists_nat_subset_range lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (finset.image j) at_top at_top := have j ∘ i = id, from funext h, (finset.image_mono j).tendsto_at_top_at_top.2 $ assume s, ⟨s.image i, by simp only [finset.image_image, this, finset.image_id, le_refl]⟩ 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] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /- 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 ↔ s ∉ f) := ⟨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, have s ∩ -s ∈ g, 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 ∨ - s ∈ f := 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) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f, 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 → ∃t∈s, t ∈ f := 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, ⟨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) : ∃i∈is, s i ∈ f := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := 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, preimage], 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 exists_maximal_of_chains_bounded (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 } noncomputable def hyperfilter : filter α := ultrafilter_of cofinite lemma hyperfilter_le_cofinite (hi : set.infinite (@set.univ α)) : @hyperfilter α ≤ cofinite := (ultrafilter_of_spec (cofinite_ne_bot hi)).1 lemma is_ultrafilter_hyperfilter (hi : set.infinite (@set.univ α)) : is_ultrafilter (@hyperfilter α) := (ultrafilter_of_spec (cofinite_ne_bot hi)).2 theorem nmem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) : s ∉ @hyperfilter α := λ hy, have hx : -s ∉ hyperfilter := λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mp hs hy, have ht : -s ∈ cofinite.sets := by show -s ∈ {s | _}; rwa [set.mem_set_of_eq, lattice.neg_neg], hx $ hyperfilter_le_cofinite hi ht theorem compl_mem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) : -s ∈ @hyperfilter α := (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mpr $ nmem_hyperfilter_of_finite hi hf theorem mem_hyperfilter_of_finite_compl (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite (-s)) : s ∈ @hyperfilter α := have h : _ := compl_mem_hyperfilter_of_finite hi hf, by rwa [lattice.neg_neg] at h 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) fs us → traverse s us ∈ traverse f fs | [] [] 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 ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) 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
825e6be05233153f8a88ccf39ba96a66a8aa7a79
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/algebra/order/floor.lean
26adfe819ab00a8d7ae836f56e16274649dcbc38
[ "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
9,515
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import algebra.order.floor import topology.algebra.order.basic /-! # Topological facts about `int.floor`, `int.ceil` and `int.fract` This file proves statements about limits and continuity of functions involving `floor`, `ceil` and `fract`. ## Main declarations * `tendsto_floor_at_top`, `tendsto_floor_at_bot`, `tendsto_ceil_at_top`, `tendsto_ceil_at_bot`: `int.floor` and `int.ceil` tend to +-∞ in +-∞. * `continuous_on_floor`: `int.floor` is continuous on `Ico n (n + 1)`, because constant. * `continuous_on_ceil`: `int.ceil` is continuous on `Ioc n (n + 1)`, because constant. * `continuous_on_fract`: `int.fract` is continuous on `Ico n (n + 1)`. * `continuous_on.comp_fract`: Precomposing a continuous function satisfying `f 0 = f 1` with `int.fract` yields another continuous function. -/ open filter function int set open_locale topological_space variables {α β γ : Type*} [linear_ordered_ring α] [floor_ring α] lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top := floor_mono.tendsto_at_top_at_top $ λ b, ⟨(b + 1 : ℤ), by { rw floor_coe, exact (lt_add_one _).le }⟩ lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot := floor_mono.tendsto_at_bot_at_bot $ λ b, ⟨b, (floor_coe _).le⟩ lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top := ceil_mono.tendsto_at_top_at_top $ λ b, ⟨b, (ceil_coe _).ge⟩ lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot := ceil_mono.tendsto_at_bot_at_bot $ λ b, ⟨(b - 1 : ℤ), by { rw ceil_coe, exact (sub_one_lt _).le }⟩ variables [topological_space α] lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) := (continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) := (continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝 n) := begin rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)), simpa only [floor_coe] using (continuous_on_floor n _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto end lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝 n) := begin rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)), simpa only [ceil_coe] using (continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto end lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝[≥] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _) begin refine (eventually_nhds_within_of_forall $ λ x (hx : (n : α) ≤ x), _), change _ ≤ _, norm_cast, convert ← floor_mono hx, rw floor_eq_iff, exact ⟨le_rfl, lt_add_one _⟩ end lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝[≤] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _) begin refine (eventually_nhds_within_of_forall $ λ x (hx : x ≤ (n : α)), _), change _ ≤ _, norm_cast, convert ← ceil_mono hx, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_rfl⟩ end lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝[≤] (n-1)) := begin rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Iic.mpr $ le_rfl))); norm_cast <|> apply_instance, ring end lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝[≥] (n+1)) := begin rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Ici.mpr $ le_rfl))); norm_cast <|> apply_instance, ring end lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝 (n-1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n), end lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝 (n+1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n), end lemma continuous_on_fract [topological_add_group α] (n : ℤ) : continuous_on (fract : α → α) (Ico n (n+1) : set α) := continuous_on_id.sub (continuous_on_floor n) lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝 1) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n); [{norm_cast, ring}, apply_instance, apply_instance] end lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝[<] 1) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_left' _) (eventually_of_forall fract_lt_one) lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝 0) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n); [exact (sub_self _).symm, apply_instance, apply_instance] end lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝[≥] 0) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_right' _) (eventually_of_forall fract_nonneg) local notation `I` := (Icc 0 1 : set α) variables [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] /-- Do not use this, use `continuous_on.comp_fract` instead. -/ lemma continuous_on.comp_fract' {f : β → α → γ} (h : continuous_on (uncurry f) $ univ ×ˢ I) (hf : ∀ s, f s 0 = f s 1) : continuous (λ st : β × α, f st.1 $ fract st.2) := begin change continuous ((uncurry f) ∘ (prod.map id (fract))), rw continuous_iff_continuous_at, rintro ⟨s, t⟩, by_cases ht : t = floor t, { rw ht, rw ← continuous_within_at_univ, have : (univ : set (β × α)) ⊆ (univ ×ˢ Iio ↑⌊t⌋) ∪ (univ ×ˢ Ici ↑⌊t⌋), { rintros p -, rw ← prod_union, exact ⟨trivial, lt_or_le p.2 _⟩ }, refine continuous_within_at.mono _ this, refine continuous_within_at.union _ _, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)), by simp [uncurry, hf], rw this, refine (h _ ⟨⟨⟩, by exact_mod_cast right_mem_Icc.2 (zero_le_one' α)⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ], rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _ _), exact tendsto_id.prod_map (tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) }, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], refine (h _ ⟨⟨⟩, by exact_mod_cast left_mem_Icc.2 (zero_le_one' α)⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ, nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _ _)], exact tendsto_id.prod_map (tendsto_fract_right _) } }, { have : t ∈ Ioo (floor t : α) ((floor t : α) + 1), from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩, apply (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp, simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk], exact continuous_at_id.tendsto.prod_map (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2)) (eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) } end lemma continuous_on.comp_fract {s : β → α} {f : β → α → γ} (h : continuous_on (uncurry f) $ univ ×ˢ Icc 0 1) (hs : continuous s) (hf : ∀ s, f s 0 = f s 1) : continuous (λ x : β, f x $ int.fract (s x)) := (h.comp_fract' hf).comp (continuous_id.prod_mk hs) /-- A special case of `continuous_on.comp_fract`. -/ lemma continuous_on.comp_fract'' {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) : continuous (f ∘ fract) := continuous_on.comp_fract (h.comp continuous_on_snd $ λ x hx, (mem_prod.mp hx).2) continuous_id (λ _, hf)
d8830be333a71969fc52d34eca4451404840de9c
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/power_series/basic.lean
591e43568d3f04b6c8eb6fbf4972e572995a7a91
[ "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
76,594
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp.interval import data.mv_polynomial.basic import data.polynomial.algebra_map import data.polynomial.coeff import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.multiplicity import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m < n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators polynomial /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : add_monoid_with_one (mv_power_series σ R) := { nat_cast := λ n, monomial R 0 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := by simp [nat.cast, monomial_zero_one], one := 1, .. mv_power_series.add_monoid } instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, add_tsub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, add_tsub_cancel_right], exact le_add_left le_rfl end @[simp] lemma commute_monomial {a : R} {n} : commute φ (monomial R n a) ↔ ∀ m, commute (coeff R m φ) a := begin refine ext_iff.trans ⟨λ h m, _, λ h m, _⟩, { have := h (m + n), rwa [coeff_add_mul_monomial, add_comm, coeff_add_monomial_mul] at this }, { rw [coeff_mul_monomial, coeff_monomial_mul], split_ifs; [apply h, refl] } end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.add_monoid_with_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, tsub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, add_tsub_cancel_right] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by simp only [coeff_X, single_left_inj one_ne_zero] @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma commute_X (φ : mv_power_series σ R) (s : σ) : commute φ (X s) := φ.commute_monomial.mpr $ λ m, commute.one_right _ lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := by rw [← (φ.commute_X s).eq, coeff_zero_mul_X] variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map _ @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma smul_eq_C_mul (f : mv_power_series σ R) (a : R) : a • f = C σ R a * f := by { ext, simp } lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [mv_power_series.X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X default, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single default 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in finset.Iio n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one (hnn : n ≠ 0) : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, rintro rfl, apply H, exact ne.bot_lt hnn, } end @[simp] lemma trunc_C (hnn : n ≠ 0) (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, exact ne.bot_lt hnn, end end trunc section semiring variable [semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [add_tsub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_tsub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using tsub_add_cancel_of_le H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul, mul_neg, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_rfl), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance [local_ring R] : local_ring (mv_power_series σ R) := local_ring.of_is_unit_or_is_unit_one_sub_self $ by { intro φ, rcases local_ring.is_unit_or_is_unit_one_sub_self (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma zero_inv : (0 : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_zero] @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv_cancel h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul_cancel _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv_cancel _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] @[simp] protected lemma mul_inv_rev (φ ψ : mv_power_series σ k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := begin by_cases h : constant_coeff σ k (φ * ψ) = 0, { rw inv_eq_zero.mpr h, simp only [map_mul, mul_eq_zero] at h, -- we don't have `no_zero_divisors (mw_power_series σ k)` yet, cases h; simp [inv_eq_zero.mpr h] }, { rw [mv_power_series.inv_eq_iff_mul_eq_one h], simp only [not_or_distrib, map_mul, mul_eq_zero] at h, rw [←mul_assoc, mul_assoc _⁻¹, mv_power_series.inv_mul_cancel _ h.left, mul_one, mv_power_series.inv_mul_cancel _ h.right] } end instance : inv_one_class (mv_power_series σ k) := { inv_one := by { rw [mv_power_series.inv_eq_iff_mul_eq_one, mul_one], simp }, ..mv_power_series.has_one, ..mv_power_series.has_inv } @[simp] lemma C_inv (r : k) : (C σ k r)⁻¹ = C σ k r⁻¹ := begin rcases eq_or_ne r 0 with rfl|hr, { simp }, rw [mv_power_series.inv_eq_iff_mul_eq_one, ←map_mul, inv_mul_cancel hr, map_one], simpa using hr end @[simp] lemma X_inv (s : σ) : (X s : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_X] @[simp] lemma smul_inv (r : k) (φ : mv_power_series σ k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := by simp [smul_eq_C_mul, mul_comm] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : mv_polynomial σ R) /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ lemma coe_def : (φ : mv_power_series σ R) = λ n, coeff n φ := rfl @[simp, norm_cast] lemma coeff_coe (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : mv_polynomial σ R) : mv_power_series σ R) = bit0 (φ : mv_power_series σ R) := coe_add _ _ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : mv_polynomial σ R) : mv_power_series σ R) = bit1 (φ : mv_power_series σ R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ variables (σ R) lemma coe_injective : function.injective (coe : mv_polynomial σ R → mv_power_series σ R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {σ R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : mv_power_series σ R) = ψ ↔ φ = ψ := (coe_injective σ R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : mv_power_series σ R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : mv_power_series σ R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((φ ^ n : mv_polynomial σ R) : mv_power_series σ R) = (φ : mv_power_series σ R) ^ n := coe_to_mv_power_series.ring_hom.map_pow _ _ variables (φ ψ) @[simp] lemma coe_to_mv_power_series.ring_hom_apply : coe_to_mv_power_series.ring_hom φ = φ := rfl section algebra variables (A : Type*) [comm_semiring A] [algebra R A] /-- The coercion from multivariable polynomials to multivariable power series as an algebra homomorphism. -/ def coe_to_mv_power_series.alg_hom : mv_polynomial σ R →ₐ[R] mv_power_series σ A := { commutes' := λ r, by simp [algebra_map_apply, mv_power_series.algebra_map_apply], ..(mv_power_series.map σ (algebra_map R A)).comp coe_to_mv_power_series.ring_hom} @[simp] lemma coe_to_mv_power_series.alg_hom_apply : (coe_to_mv_power_series.alg_hom A φ) = mv_power_series.map σ (algebra_map R A) ↑φ := rfl end algebra end mv_polynomial namespace mv_power_series variables {σ R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : mv_power_series σ R) instance algebra_mv_polynomial : algebra (mv_polynomial σ R) (mv_power_series σ A) := ring_hom.to_algebra (mv_polynomial.coe_to_mv_power_series.alg_hom A).to_ring_hom instance algebra_mv_power_series : algebra (mv_power_series σ R) (mv_power_series σ A) := (map σ (algebra_map R A)).to_algebra variables (A) lemma algebra_map_apply' (p : mv_polynomial σ R): algebra_map (mv_polynomial σ R) (mv_power_series σ A) p = map σ (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (mv_power_series σ R) (mv_power_series σ A) f = map σ (algebra_map R A) f := rfl end mv_power_series /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by simp only [finsupp.unique_single_eq_iff] lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () lemma commute_X (φ : power_series R) : commute φ X := φ.commute_X _ @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] @[simp] lemma X_ne_zero [nontrivial R] : (X : power_series R) ≠ 0 := λ H, by simpa only [coeff_one_X, one_ne_zero, map_zero] using congr_arg (coeff R 1) H lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul {S : Type*} [semiring S] [module R S] (n : ℕ) (φ : power_series S) (a : R) : coeff S n (a • φ) = a • coeff S n φ := rfl lemma smul_eq_C_mul (f : power_series R) (a : R) : a • f = C R a * f := by { ext, simp } @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp -- The following section duplicates the api of `data.polynomial.coeff` and should attempt to keep -- up to date with that section lemma coeff_C_mul_X_pow (x : R) (k n : ℕ) : coeff R n (C R x * X ^ k : power_series R) = if n = k then x else 0 := by simp [X_pow_eq, coeff_monomial] @[simp] theorem coeff_mul_X_pow (p : power_series R) (n d : ℕ) : coeff R (d + n) (p * X ^ n) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (d, n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_X_pow_mul (p : power_series R) (n d : ℕ) : coeff R (d + n) (X ^ n * p) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (n,d), coeff_X_pow, if_pos rfl, one_mul], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, zero_mul], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_comm, add_right_cancel_iff] at h1, subst h1 }, { rw add_comm, exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : power_series R) (n d : ℕ) : coeff R d (p * X ^ n) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ((le_of_add_le_right (finset.nat.mem_antidiagonal.mp hx).le).trans_lt $ not_le.mp h).ne } end lemma coeff_X_pow_mul' (p : power_series R) (n d : ℕ) : coeff R d (X ^ n * p) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_X_pow_mul], simp, }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, zero_mul], have := finset.nat.mem_antidiagonal.mp hx, rw add_comm at this, exact ((le_of_add_le_right this.le).trans_lt $ not_le.mp h).ne } end end /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl @[simp] lemma map_C (r : R) : map f (C _ r) = C _ (f r) := by { ext, simp [coeff_C, apply_ite f] } @[simp] lemma map_X : map f X = X := by { ext, simp [coeff_X, apply_ite f] } end map lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end end semiring section comm_semiring variables [comm_semiring R] open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } lemma rescale_mk (f : ℕ → R) (a : R) : rescale a (mk f) = mk (λ n : ℕ, a^n * (f n)) := by { ext, rw [coeff_rescale, coeff_mk, coeff_mk], } lemma rescale_rescale (f : power_series R) (a b : R) : rescale b (rescale a f) = rescale (a * b) f := begin ext, repeat { rw coeff_rescale, }, rw [mul_pow, mul_comm _ (b^n), mul_assoc], end lemma rescale_mul (a b : R) : rescale (a * b) = (rescale b).comp (rescale a) := by { ext, simp [← rescale_rescale], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : R[X] := ∑ m in Ico 0 n, polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc (n + 1) (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, rintro rfl, apply H, exact nat.zero_lt_succ _ } end @[simp] lemma trunc_C (n) (a : R) : trunc (n + 1) (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : Rˣ) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : Rˣ) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : Rˣ) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_X (a : A) : rescale a X = C A a * X := begin ext, simp only [coeff_rescale, coeff_C_mul, coeff_X], split_ifs with h; simp [h], end lemma rescale_neg_one_X : rescale (-1 : A) X = -X := by rw [rescale_X, map_neg, map_one, neg_one_mul] /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section domain variables [ring R] lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors R] (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, obtain rfl := le_antisymm hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance [no_zero_divisors R] : no_zero_divisors (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero } instance [is_domain R] : is_domain (power_series R) := no_zero_divisors.to_is_domain _ end domain section is_domain variables [comm_ring R] [is_domain R] /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end is_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma zero_inv : (0 : power_series k)⁻¹ = 0 := mv_power_series.zero_inv @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv_cancel φ h @[simp] protected lemma inv_mul_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul_cancel φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h @[simp] protected lemma mul_inv_rev (φ ψ : power_series k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := mv_power_series.mul_inv_rev _ _ instance : inv_one_class (power_series k) := mv_power_series.inv_one_class @[simp] lemma C_inv (r : k) : (C k r)⁻¹ = C k r⁻¹ := mv_power_series.C_inv _ @[simp] lemma X_inv : (X : power_series k)⁻¹ = 0 := mv_power_series.X_inv _ @[simp] lemma smul_inv (r : k) (φ : power_series k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := mv_power_series.smul_inv _ _ end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [semiring R] {φ : power_series R} lemma exists_coeff_ne_zero_iff_ne_zero : (∃ (n : ℕ), coeff R n φ ≠ 0) ↔ φ ≠ 0 := begin refine not_iff_not.mp _, push_neg, simp [power_series.ext_iff] end /-- The order of a formal power series `φ` is the greatest `n : part_enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ def order (φ : power_series R) : part_enat := if h : φ = 0 then ⊤ else nat.find (exists_coeff_ne_zero_iff_ne_zero.mpr h) /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := dif_pos rfl lemma order_finite_iff_ne_zero : (order φ).dom ↔ φ ≠ 0 := begin simp only [order], split, { split_ifs with h h; intro H, { contrapose! H, simpa [←part.eq_none_iff'] }, { exact h } }, { intro h, simp [h] } end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin simp only [order, order_finite_iff_ne_zero.mp h, not_false_iff, dif_neg, part_enat.get_coe'], generalize_proofs h, exact nat.find_spec h end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have := exists.intro n h, rw [order, dif_neg], { simp only [part_enat.coe_le_coe, nat.find_le_iff], exact ⟨n, le_rfl, h⟩ }, { exact exists_coeff_ne_zero_iff_ne_zero.mp ⟨n, h⟩ } end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ h } /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := part_enat.dom_of_le_coe H.le, rw [← part_enat.coe_get this, part_enat.coe_lt_coe] at H, exact coeff_order this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : part_enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using part_enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (part_enat.coe_lt_top i) }, { apply nat_le_order, simpa only [part_enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin rcases eq_or_ne φ 0 with rfl|hφ, { simpa using (part_enat.coe_ne_top _).symm }, simp [order, dif_neg hφ, nat.find_eq_iff] end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : part_enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using part_enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact part_enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (part_enat.coe_lt_top i) } }, { simpa [part_enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := begin refine le_order _ _ _, simp [coeff_of_lt_order] {contextual := tt} end private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_rfl, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw ←hi at H, rw [(coeff _ _).map_add, coeff_of_lt_order i H, add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order i hi, coeff_of_lt_order i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← nat.cast_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [part_enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [part_enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end -- TODO: link with `X_pow_dvd_iff` lemma X_pow_order_dvd (h : (order φ).dom) : X ^ ((order φ).get h) ∣ φ := begin refine ⟨power_series.mk (λ n, coeff R (n + (order φ).get h) φ), _⟩, ext n, simp only [coeff_mul, coeff_X_pow, coeff_mk, boole_mul, finset.sum_ite, finset.nat.filter_fst_eq_antidiagonal, finset.sum_const_zero, add_zero], split_ifs with hn hn, { simp [tsub_add_cancel_of_le hn] }, { simp only [finset.sum_empty], refine coeff_of_lt_order _ _, simpa [part_enat.coe_lt_iff] using λ _, hn } end lemma order_eq_multiplicity_X {R : Type*} [semiring R] (φ : power_series R) : order φ = multiplicity X φ := begin rcases eq_or_ne φ 0 with rfl|hφ, { simp }, induction ho : order φ using part_enat.cases_on with n, { simpa [hφ] using ho }, have hn : φ.order.get (order_finite_iff_ne_zero.mpr hφ) = n, { simp [ho] }, rw ←hn, refine le_antisymm (le_multiplicity_of_pow_dvd $ X_pow_order_dvd (order_finite_iff_ne_zero.mpr hφ)) (part_enat.find_le _ _ _), rintro ⟨ψ, H⟩, have := congr_arg (coeff R n) H, rw [← (ψ.commute_X.pow_right _).eq, coeff_mul_of_lt_order, ←hn] at this, { exact coeff_order _ this }, { rw [X_pow_eq, order_monomial], split_ifs, { exact part_enat.coe_lt_top _ }, { rw [←hn, part_enat.coe_lt_coe], exact nat.lt_succ_self _ } } end end order_basic section order_zero_ne_one variables [semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_is_domain -- TODO: generalize to `[semiring R] [no_zero_divisors R]` variables [comm_ring R] [is_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := begin simp_rw [order_eq_multiplicity_X], exact multiplicity.mul X_prime end end order_is_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : R[X]) /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe R[X] (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ lemma coe_def : (φ : power_series R) = power_series.mk (coeff φ) := rfl @[simp, norm_cast] lemma coeff_coe (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : R[X]) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R[X]) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add : ((φ + ψ : R[X]) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul : ((φ * ψ : R[X]) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : R[X]) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : R[X]) : power_series R) = bit0 (φ : power_series R) := coe_add φ φ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : R[X]) : power_series R) = bit1 (φ : power_series R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X : ((X : R[X]) : power_series R) = power_series.X := coe_monomial _ _ @[simp] lemma constant_coeff_coe : power_series.constant_coeff R φ = φ.coeff 0 := rfl variables (R) lemma coe_injective : function.injective (coe : R[X] → power_series R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : power_series R) = ψ ↔ φ = ψ := (coe_injective R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : power_series R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : power_series R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] variables (φ ψ) /-- The coercion from polynomials to power series as a ring homomorphism. -/ def coe_to_power_series.ring_hom : R[X] →+* power_series R := { to_fun := (coe : R[X] → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp] lemma coe_to_power_series.ring_hom_apply : coe_to_power_series.ring_hom φ = φ := rfl @[simp, norm_cast] lemma coe_pow (n : ℕ): ((φ ^ n : R[X]) : power_series R) = (φ : power_series R) ^ n := coe_to_power_series.ring_hom.map_pow _ _ variables (A : Type*) [semiring A] [algebra R A] /-- The coercion from polynomials to power series as an algebra homomorphism. -/ def coe_to_power_series.alg_hom : R[X] →ₐ[R] power_series A := { commutes' := λ r, by simp [algebra_map_apply, power_series.algebra_map_apply], ..(power_series.map (algebra_map R A)).comp coe_to_power_series.ring_hom } @[simp] lemma coe_to_power_series.alg_hom_apply : (coe_to_power_series.alg_hom A φ) = power_series.map (algebra_map R A) ↑φ := rfl end polynomial namespace power_series variables {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : power_series R) instance algebra_polynomial : algebra R[X] (power_series A) := ring_hom.to_algebra (polynomial.coe_to_power_series.alg_hom A).to_ring_hom instance algebra_power_series : algebra (power_series R) (power_series A) := (map (algebra_map R A)).to_algebra @[priority 100] -- see Note [lower instance priority] instance algebra_polynomial' {A : Type*} [comm_semiring A] [algebra R A[X]] : algebra R (power_series A) := ring_hom.to_algebra $ polynomial.coe_to_power_series.ring_hom.comp (algebra_map R A[X]) variables (A) lemma algebra_map_apply' (p : R[X]) : algebra_map R[X] (power_series A) p = map (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (power_series R) (power_series A) f = map (algebra_map R A) f := rfl end power_series
03192a388acc8e1df5fe4c80f452cd7eb372c7c4
bdb33f8b7ea65f7705fc342a178508e2722eb851
/order/filter.lean
fac57350a0c136d4b84847db60e5389d3f80f15f
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
70,604
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 Theory of filters on sets. -/ import order.complete_lattice order.galois_connection data.set data.finset order.zorn open lattice set universes u v w x y open set classical local attribute [instance] prop_decidable namespace lattice variables {α : Type u} {ι : Sort v} section variable [complete_lattice α] lemma Inf_eq_finite_sets {s : set α} : Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) := le_antisymm (le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h) (le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp) lemma infi_insert_finset {ι : Type v} {s : finset ι} {f : ι → α} {i : ι} : (⨅j∈insert i s, f j) = f i ⊓ (⨅j∈s, f j) := by simp [infi_or, infi_inf_eq] lemma infi_empty_finset {ι : Type v} {f : ι → α} : (⨅j∈(∅ : finset ι), f j) = ⊤ := by simp end lemma inf_left_comm [semilattice_inf α] (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a] end lattice namespace set variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) := assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h h₂⟩ theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h end set section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f z ≼ f x ∧ f z ≼ f y /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, z ≼ x ∧ z ≼ y 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 [directed_on]; 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 {α : Type u} {β : Type v} [preorder β] {f : α → β} {c : set α} (h : zorn.chain (λa b, f b ≤ f a) c) : directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp [this]; exact ⟨b, hb, le_refl _⟩) (assume : a ≠ b, have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this, or.elim this (assume : f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩) (assume : f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩)) structure filter (α : Type u) := (sets : set (set α)) (exists_mem_sets : ∃x, x ∈ sets) (upwards_sets : ∀{x y}, x ∈ sets → x ⊆ y → y ∈ sets) (directed_sets : directed_on (⊆) 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⟩ lemma filter.ext : f = g ↔ ∀ s, s ∈ f.sets ↔ s ∈ g.sets := by rw [filter_eq_iff, set_eq_def] lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f.sets := let ⟨x, x_in_s⟩ := f.exists_mem_sets in f.upwards_sets x_in_s (assume x _, h x) lemma univ_mem_sets : univ ∈ f.sets := univ_mem_sets' mem_univ lemma inter_mem_sets (hs : s ∈ f.sets) (ht : t ∈ f.sets) : s ∩ t ∈ f.sets := let ⟨z, ⟨z_in_s, z_le_x, z_le_y⟩⟩ := f.directed_sets _ hs _ ht in f.upwards_sets z_in_s (subset_inter z_le_x z_le_y) lemma mp_sets (hs : s ∈ f.sets) (h : {x | x ∈ s → x ∈ t} ∈ f.sets) : t ∈ f.sets := f.upwards_sets (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 [univ_mem_sets]) (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 [ha], by simp [inter_mem_sets h₁ h₂]) lemma exists_sets_subset_iff : (∃t∈f.sets, t ⊆ s) ↔ s ∈ f.sets := ⟨assume ⟨t, ht, ts⟩, f.upwards_sets ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f.sets) := assume s t hst h, f.upwards_sets 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}, exists_mem_sets := ⟨s, subset.refl _⟩, upwards_sets := assume x y hx hy, subset.trans hx hy, directed_sets := assume x hx y hy, ⟨s, subset.refl _, hx, hy⟩ } 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}, exists_mem_sets := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩, upwards_sets := assume x y hx xy, f.upwards_sets hx $ assume a h, a.upwards_sets h xy, directed_sets := assume x hx y hy, ⟨x ∩ y, by filter_upwards [hx, hy] assume z h₁ h₂, inter_mem_sets h₁ h₂, inter_subset_left _ _, inter_subset_right _ _⟩ } @[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 @[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, f.upwards_sets hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp lemma monotone_principal : monotone (principal : set α → filter α) := by simp [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 [le_antisymm_iff]; refl /-- The supremum of filters is the intersection because the ordering of filters is reverse subset. -/ instance : has_sup (filter α) := ⟨λf g : filter α, { sets := f.sets ∩ g.sets, exists_mem_sets := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩, upwards_sets := assume x y hx xy, and.imp (assume h, f.upwards_sets h xy) (assume h, g.upwards_sets h xy) hx, directed_sets := assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨inter_mem_sets hx₁ hy₁, inter_mem_sets hx₂ hy₂⟩, inter_subset_left _ _, inter_subset_right _ _⟩ }⟩ @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ (f ⊔ g).sets ↔ s ∈ f.sets ∧ s ∈ g.sets := iff.rfl /-- 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 }, exists_mem_sets := ⟨univ, univ, univ_mem_sets, univ, univ_mem_sets, subset_univ _⟩, upwards_sets := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, directed_sets := assume x ⟨a₁, ha₁, b₁, hb₁, h₁⟩ y ⟨a₂, ha₂, b₂, hb₂, h₂⟩, ⟨x ∩ y, ⟨_, inter_mem_sets ha₁ ha₂, _, inter_mem_sets hb₁ hb₂, calc (a₁ ⊓ a₂) ⊓ (b₁ ⊓ b₂) = (a₁ ⊓ b₁) ⊓ (a₂ ⊓ b₂) : by ac_refl ... ≤ x ∩ y : inf_le_inf h₁ h₂ ⟩, inter_subset_left _ _, inter_subset_right _ _⟩ }⟩ @[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 α) := ⟨principal univ⟩ @[simp] lemma mem_top_sets_iff {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ := ⟨assume h, top_unique $ h, assume h, h.symm ▸ univ_mem_sets⟩ instance : has_bot (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α).sets := assume x, false.elim instance : has_Sup (filter α) := ⟨join ∘ principal⟩ protected lemma le_Sup {s : set (filter α)} {f : filter α} : f ∈ s → f ≤ Sup s := assume f_in_s t' h, h f_in_s protected lemma Sup_le {s : set (filter α)} {f : filter α} : (∀g∈s, g ≤ f) → Sup s ≤ f := assume h a ha g hg, h g hg ha @[simp] lemma mem_Sup_sets {S : set (filter α)} {s : set α} : s ∈ (Sup S).sets ↔ ∀ f ∈ S, s ∈ (f : filter α).sets := by simp [Sup, has_Sup.Sup]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl instance complete_lattice_filter : complete_lattice (filter α) := { sup := (⊔), le_sup_left := assume a b, inter_subset_left _ _, le_sup_right := assume a b, inter_subset_right _ _, sup_le := assume a b c h₁ h₂, subset_inter h₁ h₂, inf := (⊓), le_inf := assume f g h fg fh s ⟨a, ha, b, hb, h⟩, by filter_upwards [fg ha, fh hb] assume x ha hb, h ⟨ha, hb⟩, inf_le_left := assume f g s, mem_inf_sets_of_left, inf_le_right := assume f g s, mem_inf_sets_of_right, top := ⊤, le_top := assume a, show a ≤ principal univ, by simp [univ_mem_sets], bot := ⊥, bot_le := assume a, show a.sets ⊆ {x | ∅ ⊆ x}, by simp; apply subset_univ, Sup := Sup, le_Sup := assume s f, filter.le_Sup, Sup_le := assume s f, filter.Sup_le, Inf := λs, Sup {x | ∀y∈s, x ≤ y}, le_Inf := assume s a h, filter.le_Sup h, Inf_le := assume s a ha, filter.Sup_le $ assume b h, h _ ha, ..filter.partial_order } /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, f.upwards_sets 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 [(@empty_in_sets_eq_bot α f).symm]; 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), exists_mem_sets := ⟨univ, begin simp, exact ⟨i, univ_mem_sets⟩ end⟩, directed_sets := directed_on_Union (show directed (≤) f, from h) (assume i, (f i).directed_sets), upwards_sets := by simpa using assume x y j xf (xy : x ⊆ y), exists.intro j ((f j).upwards_sets xf xy) } 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 (λx y, f x ≤ f y) 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 Inf_sets_eq_finite {s : set (filter α)} : (Inf s).sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) := calc (Inf s).sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t).sets : by rw [lattice.Inf_eq_finite_sets] ... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩, Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩) ⟨∅, by simp⟩ lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := set.ext $ assume s, show s ∈ (join (principal {a : filter α | ∃i : ι, a = f i})).sets ↔ s ∈ (⋂i, (f i).sets), begin rw [mem_join_sets], simp, rw [forall_swap], exact forall_congr (λ i, by simp) end @[simp] lemma mem_supr_sets {f : ι → filter α} {s : set α} : s ∈ (supr f).sets ↔ ∀ i, s ∈ (f i).sets := by simp [supr_sets_eq] @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] @[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 [supr_sets_eq, join] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := assume x y z s, begin 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.upwards_sets hs $ subset_union_left _ _, y.upwards_sets ht₁ $ subset_union_right _ _, s ∪ t₂, x.upwards_sets hs $ subset_union_left _ _, z.upwards_sets ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice_filter } private lemma infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) : (⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) := finite.induction_on h (by simp only [mem_empty_eq, infi_false, infi_top, Inf_empty, sup_top_eq]) (by intros a s hn hs hi; rw [infi_insert, hi, ← sup_inf_left, Inf_insert]) /- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/ lemma binfi_sup_eq { f : filter α } {s : set (filter α)} : (⨅ g∈s, f ⊔ g) = f ⊔ Inf s := le_antisymm begin intros t h, cases h with h₁ h₂, rw [Inf_sets_eq_finite] at h₂, simp [and_assoc] at h₂, cases h₂ with s' hs', cases hs' with hs' hs'', cases hs'' with hs's ht', have ht : t ∈ (⨅ a ∈ s', f ⊔ a).sets, { rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' }, clear h₁ ht', revert ht t, change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a), apply infi_le_infi2 _, exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩ end (le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h) lemma infi_sup_eq { f : filter α } {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp ... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq ... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp 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 refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, lattice.infi_empty_finset, top_le_iff, imp_true_iff, mem_top_sets_iff, true_and, exists_const], exact assume _, iff.refl _ }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, lattice.infi_insert_finset, 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 : (⨅j ∈ s, function.update p a t₁ j) = (⨅j ∈ s, p j), begin congr, funext b, congr, funext h, apply this, assumption end, 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 }, from assume p hpa hp ht, ⟨p a, hpa, (⨅j∈s, p j), ⟨⟨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 [union_subset_iff] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := rfl lemma principal_empty : principal (∅ : set α) = ⊥ := rfl @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩ 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₂⟩ end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, exists_mem_sets := ⟨univ, univ_mem_sets⟩, upwards_sets := assume s t hs st, f.upwards_sets hs (assume x h, st h), directed_sets := assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, inter_subset_left _ _, inter_subset_right _ _⟩ } @[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.upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩ @[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 vmap /-- The inverse map of a filter -/ def vmap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈f.sets, m ⁻¹' t ⊆ s }, exists_mem_sets := ⟨univ, univ, univ_mem_sets, by simp⟩, upwards_sets := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, directed_sets := assume a ⟨a', ha₁, ha₂⟩ b ⟨b', hb₁, hb₂⟩, ⟨preimage m (a' ∩ b'), ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, subset.refl _⟩, subset.trans (preimage_mono $ inter_subset_left _ _) ha₂, subset.trans (preimage_mono $ inter_subset_right _ _) hb₂⟩ } end vmap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, exists_mem_sets := ⟨univ, by simp⟩, upwards_sets := assume s t, assume hs : finite (-s), assume st: s ⊆ t, finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, directed_sets := assume s, assume hs : finite (-s), assume t, assume ht : finite (-t), ⟨s ∩ t, by simp [compl_inter, finite_union, ht, hs], inter_subset_left _ _, inter_subset_right _ _⟩ } /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) instance : monad filter := { bind := @bind, pure := λ(α : Type u) x, principal {x}, map := @filter.map } instance : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp [bind, Sup_image], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [bind, join, map, preimage, principal] } @[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; exact id @[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 instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } /- map and vmap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_vmap_sets : s ∈ (vmap m g).sets ↔ ∃t∈g.sets, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_vmap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (vmap m g).sets := ⟨t, ht, subset.refl _⟩ lemma vmap_id : vmap id f = f := le_antisymm (assume s, preimage_mem_vmap) (assume s ⟨t, ht, hst⟩, f.upwards_sets ht hst) lemma vmap_vmap_comp {m : γ → β} {n : β → α} : vmap m (vmap n f) = vmap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_vmap 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 vmap_principal {t : set β} : vmap 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_vmap : map m f ≤ g ↔ f ≤ vmap m g := ⟨assume h s ⟨t, ht, hts⟩, f.upwards_sets (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_vmap (m : α → β) : galois_connection (map m) (vmap m) := assume f g, map_le_iff_le_vmap lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_vmap m).monotone_l h lemma monotone_map : monotone (map m) | a b := map_mono lemma vmap_mono (h : g₁ ≤ g₂) : vmap m g₁ ≤ vmap m g₂ := (gc_map_vmap m).monotone_u h lemma monotone_vmap : monotone (vmap m) | a b := vmap_mono @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_vmap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_vmap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_vmap m).l_supr @[simp] lemma vmap_top : vmap m ⊤ = ⊤ := (gc_map_vmap m).u_top @[simp] lemma vmap_inf : vmap m (g₁ ⊓ g₂) = vmap m g₁ ⊓ vmap m g₂ := (gc_map_vmap m).u_inf @[simp] lemma vmap_infi {f : ι → filter β} : vmap m (⨅i, f i) = (⨅i, vmap m (f i)) := (gc_map_vmap m).u_infi lemma map_vmap_le : map m (vmap m g) ≤ g := (gc_map_vmap m).decreasing_l_u _ lemma le_vmap_map : f ≤ vmap m (map m f) := (gc_map_vmap m).increasing_u_l _ @[simp] lemma vmap_bot : vmap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp, by simp⟩ lemma vmap_sup : vmap m (g₁ ⊔ g₂) = vmap m g₁ ⊔ vmap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.upwards_sets ht₁ (subset_union_left _ _), g₂.upwards_sets ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) (sup_le (vmap_mono le_sup_left) (vmap_mono le_sup_right)) lemma le_map_vmap' {f : filter β} {m : α → β} {s : set β} (hs : s ∈ f.sets) (hm : ∀b∈s, ∃a, m a = b) : f ≤ map m (vmap m f) := assume t' ⟨t, ht, (sub : m ⁻¹' t ⊆ m ⁻¹' t')⟩, by filter_upwards [ht, hs] assume x hxt hxs, let ⟨y, hy⟩ := hm x hxs in hy ▸ sub (show m y ∈ t, from hy.symm ▸ hxt) lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (vmap m f) := le_map_vmap' univ_mem_sets (assume b _, hm b) lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : vmap 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.upwards_sets hs $ by simp [this, subset.refl], by simp [this, subset.refl]⟩) le_vmap_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 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 vmap m (map m f) = vmap m (map m g), by rw h, by rwa [vmap_map hm, vmap_map hm] at this lemma vmap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap 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 vmap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ := vmap_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 [*]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h 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 [subset_def] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ f.upwards_sets 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 [infi_sets_eq hf hι] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp; assumption, by simp at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (λx y, f x ≤ f y) {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 [infi_subtype] ... = (⨅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 [infi_subtype] 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 [map, 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_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.upwards_sets ha $ calc a = preimage (n ∘ m) a : by simp [h₂, preimage_id] ... ⊆ 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 [h₁]; apply subset.refl⟩) lemma map_swap_eq_vmap_swap {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f := map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq /- bind equations -/ @[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 [bind] ... ↔ (∃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 [bind] 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 [Sup_image] lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ := le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg) @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s := by simp @[simp] lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α).sets ↔ a ∈ s := mem_pure_sets 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 at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).upwards_sets 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 have hs' : s ∈ (Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs, rw [Inf_sets_eq_finite] at hs', simp only [mem_Union_eq] at hs', rcases hs' with ⟨is, h, hs⟩, cases h with fin_is his, revert his s, refine finite.induction_on fin_is _ (λ fi is fi_ne_is fin_is ih, _); intros his s hs' hs, { rw [Inf_empty, mem_top_sets_iff] at hs, subst hs, assumption }, { rw [Inf_insert] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, rcases (his (mem_insert _ _) : ∃i, fi = f i) with ⟨i, rfl⟩, have hs₂ : p s₂, from have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, his $ mem_insert_of_mem _ hi, have infi f ≤ Inf is, from Inf_le_Inf his, ih his (this hs₂) hs₂, exact upw hs (ins hs₁ hs₂) } end @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp [pure, has_pure.pure] /- 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_vmap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.vmap f := map_le_iff_le_vmap 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 [tendsto] { 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_vmap {f : α → β} {x : filter β} : tendsto f (vmap f x) x := map_vmap_le lemma tendsto_vmap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.vmap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, h.comp tendsto_vmap, assume h, map_le_iff_le_vmap.mp $ by rwa [map_map]⟩ lemma tendsto_vmap'' {m : α → β} {f : filter α} {g : filter β} (s : set α) {i : γ → α} (hs : s ∈ f.sets) (hi : ∀a∈s, ∃c, i c = a) (h : tendsto (m ∘ i) (vmap i f) g) : tendsto m f g := have tendsto m (map i $ vmap i $ f) g, by rwa [tendsto, ←map_compose] at h, le_trans (map_mono $ le_map_vmap' hs hi) this lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp [tendsto] 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 [tendsto] 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 [tendsto] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp [tendsto, image_subset_iff]; refl 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_eq] 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 [mem_lift_sets, hg, @mem_lift_sets _ _ f _ this] lemma vmap_lift_eq {m : γ → β} (hg : monotone g) : vmap m (f.lift g) = f.lift (vmap m ∘ g) := have monotone (vmap m ∘ g), from monotone_comp hg monotone_vmap, filter_eq $ set.ext begin simp only [hg, @mem_lift_sets _ _ f _ this, vmap, 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 vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (vmap 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.upwards_sets 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 [filter.lift, infi_subtype] ... ↔ (∀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 [h₁] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂]) @[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 [filter.lift, infi_inf_eq] @[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 [hs]) 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_eq, 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 `vmap`. -/ 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 [filter.lift', @mem_lift_sets α β f _ this] 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 [function.comp, filter.lift'] 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 vmap_lift'_eq {m : γ → β} (hh : monotone h) : vmap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc vmap m (f.lift' h) = f.lift (vmap m ∘ principal ∘ h) : vmap_lift_eq $ monotone_comp hh monotone_principal ... = f.lift' (preimage m ∘ h) : by simp [function.comp, filter.lift'] theorem vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (vmap m f).lift' g = f.lift' (g ∘ preimage m) := vmap_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 [lift_principal, hh] 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) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; 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 [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 [h_le]; 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_eq, 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; apply assume s t, hg theorem vmap_eq_lift' {f : filter β} {m : α → β} : vmap m f = f.lift' (preimage m) := filter_eq $ set.ext $ by simp [mem_lift'_sets, monotone_preimage, vmap] 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.vmap prod.fst ⊓ g.vmap 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_vmap hs) (preimage_mem_vmap 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 [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_vmap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_vmap 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_vmap_iff.2 h₁, tendsto_vmap_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, vmap_infi, infi_inf i]; simp [filter.prod] 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, vmap_infi, inf_infi i]; simp [filter.prod] 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 (vmap_mono hf) (vmap_mono hg) lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp [filter.prod, vmap_vmap_comp] lemma prod_comm' : filter.prod f g = vmap (prod.swap) (filter.prod g f) := by simp [filter.prod, vmap_vmap_comp, function.comp, inf_comm] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_vmap_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.upwards_sets _ (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 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, vmap_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 [filter.prod, vmap_principal]; refl 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).vmap prod.fst ⊓ (principal t).vmap prod.snd, by simp; intros; refl, begin simp [filter.lift', function.comp, this, -vmap_principal, lift_inf], rw [← vmap_lift_eq monotone_principal, ← vmap_lift_eq monotone_principal], simp [filter.prod] 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] 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 {contextual := tt}⟩) (assume a, by simp [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⟩ (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 {contextual := tt}⟩) ⟨default α⟩ ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by 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 [finset.image_image, (∘), h]; exact finset.image_id.symm ... ⊆ t.image j : finset.image_subset_image ht /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_pure {a : α} : ultrafilter (pure a) := ⟨pure_neq_bot, assume g hg ha, have {a} ∈ g.sets, begin simp at ha, assumption end, show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $ begin simp only [classical.not_forall, not_imp, exists_imp_distrib, singleton_subset_iff], exact assume s ⟨hs, hna⟩, have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs, have ∅ ∈ g.sets, from g.upwards_sets this $ assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end, have g = ⊥, from empty_in_sets_eq_bot.mp this, hg this end⟩ lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ 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₂⟩ lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) : s ∈ f.sets ∨ - s ∈ f.sets := classical.or_iff_not_imp_right.2 $ assume : - s ∉ f.sets, have f ≤ principal s, from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*], by simp at this; assumption lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : 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 : ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets := finite.induction_on hs (by simp [empty_in_sets_eq_bot, hf.left]) $ λ t s' ht' hs' ih, by simp; 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 : 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 [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_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) : ultrafilter f := ⟨hf, assume g hg g_le s hs, (h s).elim id $ assume : - s ∈ f.sets, have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this), by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) := ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $ assume s, show preimage m s ∈ f.sets ∨ - preimage m s ∈ f.sets, from mem_or_compl_mem_of_ultrafilter h (preimage m s) /-- 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 epsilon (λu, u ≤ f ∧ ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) := begin have h' := epsilon_spec (exists_ultrafilter h), simp [ultrafilter_of, dif_neg, h], simp at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le end ultrafilter end filter
0a4632ebbbf584e1b5fe8597b98737efbaeac5d4
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/ring.lean
ab6a7314cfebdbfd8d1f96269991267888d850ed
[ "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
28,896
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 tactic.norm_num /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, using_new_ref mk_buffer $ λ atoms, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := h /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_sum [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_prod [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``division_ring_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p₃ ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], p₄ ← lift $ mk_eq_symm $ `(nat.pow_eq_pow).mk_app [e₁, e₂], p ← lift $ mk_eq_trans p₄ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
1cd5d4e7eccbef60d0e24f41a20a288bfca85d3a
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Compiler/IR/PushProj.lean
1b6bfb4f94c368852670a90203f8f2e8b87a2f46
[ "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
2,178
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.Compiler.IR.Basic import Init.Lean.Compiler.IR.FreeVars import Init.Lean.Compiler.IR.NormIds namespace Lean namespace IR partial def pushProjs : Array FnBody → Array Alt → Array IndexSet → Array FnBody → IndexSet → Array FnBody × Array Alt | bs, alts, altsF, ctx, ctxF => if bs.isEmpty then (ctx.reverse, alts) else let b := bs.back; let bs := bs.pop; let done (_ : Unit) := (bs.push b ++ ctx.reverse, alts); let skip (_ : Unit) := pushProjs bs alts altsF (ctx.push b) (b.collectFreeIndices ctxF); let push (x : VarId) (t : IRType) (v : Expr) := if !ctxF.contains x.idx then let alts := alts.mapIdx $ fun i alt => alt.modifyBody $ fun b' => if (altsF.get! i).contains x.idx then b.setBody b' else b'; let altsF := altsF.map $ fun s => if s.contains x.idx then b.collectFreeIndices s else s; pushProjs bs alts altsF ctx ctxF else skip (); match b with | FnBody.vdecl x t v _ => match v with | Expr.proj _ _ => push x t v | Expr.uproj _ _ => push x t v | Expr.sproj _ _ _ => push x t v | Expr.isShared _ => skip () | Expr.isTaggedPtr _ => skip () | _ => done () | _ => done () partial def FnBody.pushProj : FnBody → FnBody | b => let (bs, term) := b.flatten; let bs := modifyJPs bs FnBody.pushProj; match term with | FnBody.case tid x xType alts => let altsF := alts.map $ fun alt => alt.body.freeIndices; let (bs, alts) := pushProjs bs alts altsF #[] (mkIndexSet x.idx); let alts := alts.map $ fun alt => alt.modifyBody FnBody.pushProj; let term := FnBody.case tid x xType alts; reshape bs term | other => reshape bs term /-- Push projections inside `case` branches. -/ def Decl.pushProj : Decl → Decl | Decl.fdecl f xs t b => (Decl.fdecl f xs t b.pushProj).normalizeIds | other => other end IR end Lean
18ad1d9c9a6a62ff5485fd7c20aa562a3658d83a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/doIssue.lean
3c84a0d74e910a7265ba765f2e9291cce7212239
[ "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
471
lean
def f (x : Nat) : IO Unit := do x -- Error IO.println x def f' (x : Nat) : IO Unit := do discard (pure x) IO.println x def g (xs : Array Nat) : IO Unit := do xs.set! 0 1 -- Error IO.println xs def g' (xs : Array Nat) : IO Unit := do discard <| pure (xs.set! 0 1) IO.println xs def h (xs : Array Nat) : IO Unit := do pure (xs.set! 0 1) -- Error IO.println xs def h' (xs : Array Nat) : IO Unit := do discard <| pure (xs.set! 0 1) IO.println xs
6d26d0220268edcb77e6eb1cc3c5fbc7ba13fd2f
2fbe653e4bc441efde5e5d250566e65538709888
/src/data/fintype.lean
b6d1b76881457deeeb364c60cef1bef76e56eb96
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
37,058
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = (finset.univ : finset α).sum (λ _, 1) := finset.card_eq_sum_ones _ end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.prod f = f 0 * univ.prod (λ i:fin n, f i.succ) := begin rw [fin.univ_succ, prod_insert, prod_image], { intros x _ y _ hxy, exact fin.succ.inj hxy }, { simpa using fin.succ_ne_zero } end @[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : univ.prod f = 1 := rfl theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.sum f = f 0 + univ.sum (λ i:fin n, f i.succ) := by apply @fin.prod_univ_succ (multiplicative β) attribute [to_additive] fin.prod_univ_succ @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [∀ a, fintype (β a)] [decidable α] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [fintype α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) @[to_additive] lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) : (range n).prod f = univ.prod (λ (k : fin n), f k) := begin symmetry, refine prod_bij (λ k hk, k) _ _ _ _, { rintro ⟨k, hk⟩ _, simp * }, { rintro ⟨k, hk⟩ _, simp * }, { intros, rwa fin.eq_iff_veq }, { intros k hk, rw mem_range at hk, exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ } end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
f56a97038215572e74d7da96c1ba9311e0f46046
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category/functor.lean
c3c6d74faf14514103f4749fe835993f88607c8d
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
4,083
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Standard identity and composition functors -/ import tactic.ext tactic.cache category.basic universe variables u v w section functor variables {F : Type u → Type v} variables {α β γ : Type u} variables [functor F] [is_lawful_functor F] lemma functor.map_id : (<$>) id = (id : F α → F α) := by apply funext; apply id_map lemma functor.map_comp_map (f : α → β) (g : β → γ) : ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) := by apply funext; intro; rw comp_map theorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F} [@is_lawful_functor F F1] [@is_lawful_functor F F2] (H : ∀ α β (f : α → β) (x : F α), @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x), F1 = F2 | ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H := begin cases show @m = @m', by funext α β f x; apply H, congr, funext α β, have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1, have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2, exact E1.trans E2.symm end end functor def id.mk {α : Sort u} : α → id α := id namespace functor def const (α : Type*) (β : Type*) := α def add_const (α : Type*) := const α @[pattern] def const.mk {α β} (x : α) : const α β := x def const.run {α β} (x : const α β) : α := x namespace const protected lemma ext {α β} {x y : const α β} (h : x.run = y.run) : x = y := h protected def map {γ α β} (f : α → β) (x : const γ β) : const γ α := x instance {γ} : functor (const γ) := { map := @const.map γ } instance add_const.functor {γ} : functor (add_const γ) := @const.functor γ instance {γ} : is_lawful_functor (const γ) := by constructor; intros; refl instance add_const.is_lawful_functor {γ} : is_lawful_functor (add_const γ) := @const.is_lawful_functor γ end const /-- `functor.comp` is a wrapper around `function.comp` for types. It prevents Lean's type class resolution mechanism from trying a `functor (comp F id)` when `functor F` would do. -/ def comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F $ G α @[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : comp F G α := x def comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : comp F G α) : F (G α) := x namespace comp variables {F : Type u → Type w} {G : Type v → Type u} protected lemma ext {α} {x y : comp F G α} : x.run = y.run → x = y := id variables [functor F] [functor G] protected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β | (comp.mk x) := comp.mk ((<$>) h <$> x) instance : functor (comp F G) := { map := @comp.map F G _ _ } @[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl variables [is_lawful_functor F] [is_lawful_functor G] variables {α β γ : Type v} protected lemma id_map : ∀ (x : comp F G α), comp.map id x = x | (comp.mk x) := by simp [comp.map, functor.map_id] protected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α), comp.map (h ∘ g') x = comp.map h (comp.map g' x) | (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm @[simp] protected lemma run_map (h : α → β) (x : comp F G α) : (h <$> x).run = (<$>) h <$> x.run := rfl instance : is_lawful_functor (comp F G) := { id_map := @comp.id_map F G _ _ _ _, comp_map := @comp.comp_map F G _ _ _ _ } theorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] : @comp.functor F id _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl) theorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] : @comp.functor id F _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl) end comp end functor namespace ulift instance : functor ulift := { map := λ α β f, up ∘ f ∘ down } end ulift
6c88dd39f1fd23559302ad5bd1fa783916eab5fe
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/field_theory/algebraic_closure.lean
7201fcd7b31e5b4ef6a630c043b61164011d46e4
[ "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
15,256
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_limit import field_theory.splitting_field /-! # Algebraic Closure In this file we define the typeclass for algebraically closed fields and algebraic closures. We also construct an algebraic closure for any field. ## Main Definitions - `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every polynomial in `k` splits. - `is_alg_closure k K` is the typeclass saying `K` is an algebraic closure of `k`. - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## TODO Show that any algebraic extension embeds into any algebraically closed extension (via Zorn's lemma). ## Tags algebraic closure, algebraically closed -/ universes u v w noncomputable theory open_locale classical big_operators open polynomial variables (k : Type u) [field k] /-- Typeclass for algebraically closed fields. To show `polynomial.splits p f` for an arbitrary ring homomorphism `f`, see `is_alg_closed.splits_codomain` and `is_alg_closed.splits_domain`. -/ class is_alg_closed : Prop := (splits : ∀ p : polynomial k, p.splits $ ring_hom.id k) /-- Every polynomial splits in the field extension `f : K →+* k` if `k` is algebraically closed. See also `is_alg_closed.splits_domain` for the case where `K` is algebraically closed. -/ theorem is_alg_closed.splits_codomain {k K : Type*} [field k] [is_alg_closed k] [field K] {f : K →+* k} (p : polynomial K) : p.splits f := by { convert is_alg_closed.splits (p.map f), simp [splits_map_iff] } /-- Every polynomial splits in the field extension `f : K →+* k` if `K` is algebraically closed. See also `is_alg_closed.splits_codomain` for the case where `k` is algebraically closed. -/ theorem is_alg_closed.splits_domain {k K : Type*} [field k] [is_alg_closed k] [field K] {f : k →+* K} (p : polynomial k) : p.splits f := polynomial.splits_of_splits_id _ $ is_alg_closed.splits _ namespace is_alg_closed theorem of_exists_root (H : ∀ p : polynomial k, p.monic → irreducible p → ∃ x, p.eval x = 0) : is_alg_closed k := ⟨λ p, or.inr $ λ q hq hqp, have irreducible (q * C (leading_coeff q)⁻¹), by { rw ← coe_norm_unit_of_ne_zero hq.ne_zero, exact irreducible_of_associated associated_normalize hq }, let ⟨x, hx⟩ := H (q * C (leading_coeff q)⁻¹) (monic_mul_leading_coeff_inv hq.ne_zero) this in degree_mul_leading_coeff_inv q hq.ne_zero ▸ degree_eq_one_of_irreducible_of_root this hx⟩ lemma degree_eq_one_of_irreducible [is_alg_closed k] {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) : p.degree = 1 := degree_eq_one_of_irreducible_of_splits h_nz hp (is_alg_closed.splits_codomain _) lemma algebra_map_surjective_of_is_integral {k K : Type*} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_integral k K) : function.surjective (algebra_map k K) := begin refine λ x, ⟨-((minpoly k x).coeff 0), _⟩, have hq : (minpoly k x).leading_coeff = 1 := minpoly.monic (hf x), have h : (minpoly k x).degree = 1 := degree_eq_one_of_irreducible k (minpoly.ne_zero (hf x)) (minpoly.irreducible (hf x)), have : (aeval x (minpoly k x)) = 0 := minpoly.aeval k x, rw [eq_X_add_C_of_degree_eq_one h, hq, C_1, one_mul, aeval_add, aeval_X, aeval_C, add_eq_zero_iff_eq_neg] at this, exact (ring_hom.map_neg (algebra_map k K) ((minpoly k x).coeff 0)).symm ▸ this.symm, end lemma algebra_map_surjective_of_is_integral' {k K : Type*} [field k] [integral_domain K] [hk : is_alg_closed k] (f : k →+* K) (hf : f.is_integral) : function.surjective f := @algebra_map_surjective_of_is_integral k K _ _ _ f.to_algebra hf lemma algebra_map_surjective_of_is_algebraic {k K : Type*} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_algebraic k K) : function.surjective (algebra_map k K) := algebra_map_surjective_of_is_integral ((is_algebraic_iff_is_integral' k).mp hf) end is_alg_closed /-- Typeclass for an extension being an algebraic closure. -/ class is_alg_closure (K : Type v) [field K] [algebra k K] : Prop := (alg_closed : is_alg_closed K) (algebraic : algebra.is_algebraic k K) theorem is_alg_closure_iff (K : Type v) [field K] [algebra k K] : is_alg_closure k K ↔ is_alg_closed K ∧ algebra.is_algebraic k K := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ namespace algebraic_closure open mv_polynomial /-- The subtype of monic irreducible polynomials -/ @[reducible] def monic_irreducible : Type u := { f : polynomial k // monic f ∧ irreducible f } /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (X f) f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span $ set.range $ eval_X_self k /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (s : finset (monic_irreducible k)) : mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : polynomial k) := mv_polynomial.aeval $ λ f, if hf : f ∈ s then root_of_splits _ ((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1 (splitting_field.splits _) f hf) (mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit) else 37 theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) : to_splitting_field k s (eval_X_self k f) = 0 := by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂, alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf, ← algebra_map_eq, alg_hom.comp_algebra_map], exact map_root_of_splits _ _ _ } theorem span_eval_ne_top : span_eval k ≠ ⊤ := begin rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_iff_total], rintros ⟨v, _, hv⟩, replace hv := congr_arg (to_splitting_field k v.support) hv, rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv, { exact zero_ne_one hv }, intros j hj, rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero] end /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) := classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k instance max_ideal.is_maximal : (max_ideal k).is_maximal := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1 theorem le_max_ideal : span_eval k ≤ max_ideal k := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2 /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic : Type u := (max_ideal k).quotient instance adjoin_monic.field : field (adjoin_monic k) := ideal.quotient.field _ instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩ /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic : k →+* adjoin_monic k := (ideal.quotient.mk _).comp C instance adjoin_monic.algebra : algebra k (adjoin_monic k) := (to_adjoin_monic k).to_algebra theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C := rfl theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z := let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸ mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add) (λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1, by { erw [adjoin_monic.algebra_map, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩) theorem adjoin_monic.exists_root {f : polynomial k} (hfm : f.monic) (hfi : irreducible f) : ∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 := ⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k), by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩ /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (n : ℕ) : Σ α : Type u, field α := nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩ /-- The `n`th step of constructing `algebraic_closure`. -/ def step (n : ℕ) : Type u := (step_aux k n).1 instance step.field (n : ℕ) : field (step k n) := (step_aux k n).2 instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩ /-- The canonical inclusion to the `0`th step. -/ def to_step_zero : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) := @to_adjoin_monic (step k n) (step.field k n) instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) := (to_step_succ k n).to_algebra theorem to_step_succ.exists_root {n} {f : polynomial (step k n)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 := @adjoin_monic.exists_root _ (step.field k n) _ hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n := { to_fun := nat.le_rec_on h (λ n, to_step_succ k n), map_one' := begin induction h with n h ih, { exact nat.le_rec_on_self 1 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_one] end, map_mul' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul] end, map_zero' := begin induction h with n h ih, { exact nat.le_rec_on_self 0 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero] end, map_add' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add] end } @[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) : (to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) := rfl instance step.algebra (n) : algebra k (step k n) := (to_step_of_le k 0 n n.zero_le).to_algebra instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq $ λ z, @nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z theorem step.is_integral (n) : ∀ z : step k n, is_integral k z := nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z, is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _) instance to_step_of_le.directed_system : directed_system (step k) (λ i j h, to_step_of_le k i j h) := ⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩ end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure : Type u := ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h) namespace algebraic_closure instance : field (algebraic_closure k) := field.direct_limit.field _ _ instance : inhabited (algebraic_closure k) := ⟨37⟩ /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (n : ℕ) : step k n →+* algebraic_closure k := ring_hom.of $ ring.direct_limit.of _ _ _ instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) := (of_step k n).to_algebra theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n := ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _, by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm } theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z := ring.direct_limit.exists_of z -- slow theorem exists_root {f : polynomial (algebraic_closure k)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : algebraic_closure k, f.eval x = 0 := begin have : ∃ n p, polynomial.map (of_step k n) p = f, { convert ring.direct_limit.polynomial.exists_of f }, unfreezingI { obtain ⟨n, p, rfl⟩ := this }, rw monic_map_iff at hfm, have := hfm.irreducible_of_irreducible_map (of_step k n) p hfi, obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this, refine ⟨of_step k (n + 1) x, _⟩, rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero] end instance : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root _ $ λ f, exists_root k instance : algebra k (algebraic_closure k) := (of_step k 0).to_algebra /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k := { commutes' := λ x, ring.direct_limit.of_f n.zero_le x, .. of_step k n } theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) := λ z, (is_algebraic_iff_is_integral _).2 $ let ⟨n, x, hx⟩ := exists_of_step k z in hx ▸ is_integral_alg_hom (of_step_hom k n) (step.is_integral k n x) instance : is_alg_closure k (algebraic_closure k) := ⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩ end algebraic_closure /-- Every element `f` in a nontrivial finite-dimensional algebra `A` over an algebraically closed field `K` has non-empty spectrum: that is, there is some `c : K` so `f - c • 1` is not invertible. -/ -- We will use this both to show eigenvalues exist, and to prove Schur's lemma. lemma exists_spectrum_of_is_alg_closed_of_finite_dimensional (𝕜 : Type*) [field 𝕜] [is_alg_closed 𝕜] {A : Type*} [nontrivial A] [ring A] [algebra 𝕜 A] [I : finite_dimensional 𝕜 A] (f : A) : ∃ c : 𝕜, ¬ is_unit (f - algebra_map 𝕜 A c) := begin obtain ⟨p, ⟨h_mon, h_eval_p⟩⟩ := is_integral_of_noetherian I f, have nu : ¬ is_unit (aeval f p), { rw [←aeval_def] at h_eval_p, rw h_eval_p, simp, }, rw [eq_prod_roots_of_monic_of_splits_id h_mon (is_alg_closed.splits p), ←multiset.prod_to_list, alg_hom.map_list_prod] at nu, replace nu := mt list.prod_is_unit nu, simp only [not_forall, exists_prop, aeval_C, multiset.mem_to_list, list.mem_map, aeval_X, exists_exists_and_eq_and, multiset.mem_map, alg_hom.map_sub] at nu, exact ⟨nu.some, nu.some_spec.2⟩, end