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
3ace1fc70fd56c28ff77f27a2983198dfe075172
4fa161becb8ce7378a709f5992a594764699e268
/src/tactic/equiv_rw.lean
d934ddd3caba40793694be2d3fc239cf484909a8
[ "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
12,065
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import control.equiv_functor.instances /-! # The `equiv_rw` tactic transports goals or hypotheses along equivalences. The basic syntax is `equiv_rw e`, where `e : α ≃ β` is an equivalence. This will try to replace occurrences of `α` in the goal with `β`, for example transforming * `⊢ α` to `⊢ β`, * `⊢ option α` to `⊢ option β` * `⊢ {a // P}` to `{b // P (⇑(equiv.symm e) b)}` The tactic can also be used to rewrite hypotheses, using the syntax `equiv_rw e at h`. ## Implementation details The main internal function is `equiv_rw_type e t`, which attempts to turn an expression `e : α ≃ β` into a new equivalence with left hand side `t`. As an example, with `t = option α`, it will generate `functor.map_equiv option e`. This is achieved by generating a new synthetic goal `%%t ≃ _`, and calling `solve_by_elim` with an appropriate set of congruence lemmas. To avoid having to specify the relevant congruence lemmas by hand, we mostly rely on `equiv_functor.map_equiv` and `bifunctor.map_equiv` along with some structural congruence lemmas such as * `equiv.arrow_congr'`, * `equiv.subtype_equiv_of_subtype'`, * `equiv.sigma_congr_left'`, and * `equiv.Pi_congr_left'`. The main `equiv_rw` function, when operating on the goal, simply generates a new equivalence `e'` with left hand side matching the target, and calls `apply e'.inv_fun`. When operating on a hypothesis `x : α`, we introduce a new fact `h : x = e.symm (e x)`, revert this, and then attempt to `generalize`, replacing all occurrences of `e x` with a new constant `y`, before `intro`ing and `subst`ing `h`, and renaming `y` back to `x`. ## Future improvements In a future PR I anticipate that `derive equiv_functor` should work on many examples, (internally using `transport`, which is in turn based on `equiv_rw`) and we can incrementally bootstrap the strength of `equiv_rw`. An ambitious project might be to add `equiv_rw!`, a tactic which, when failing to find appropriate `equiv_functor` instances, attempts to `derive` them on the spot. For now `equiv_rw` is entirely based on `equiv`, but the framework can readily be generalised to also work with other types of equivalences, for example specific notations such as ring equivalence (`≃+*`), or general categorical isomorphisms (`≅`). This will allow us to transport across more general types of equivalences, but this will wait for another subsequent PR. -/ namespace tactic /-- A list of lemmas used for constructing congruence equivalences. -/ -- Although this looks 'hard-coded', in fact the lemma `equiv_functor.map_equiv` -- allows us to extend `equiv_rw` simply by constructing new instance so `equiv_functor`. -- TODO: We should also use `category_theory.functorial` and `category_theory.hygienic` instances. -- (example goal: we could rewrite along an isomorphism of rings (either as `R ≅ S` or `R ≃+* S`) -- and turn an `x : mv_polynomial σ R` into an `x : mv_polynomial σ S`.). meta def equiv_congr_lemmas : tactic (list expr) := do exprs ← [ `equiv.of_iff, -- TODO decide what to do with this; it's an equiv_bifunctor? `equiv.equiv_congr, -- The function arrow is technically a bifunctor `Typeᵒᵖ → Type → Type`, -- but the pattern matcher will never see this. `equiv.arrow_congr', -- Allow rewriting in subtypes: `equiv.subtype_equiv_of_subtype', -- Allow rewriting in the first component of a sigma-type: `equiv.sigma_congr_left', -- Allow rewriting ∀s: -- (You might think that repeated application of `equiv.forall_congr' -- would handle the higher arity cases, but unfortunately unification is not clever enough.) `equiv.forall₃_congr', `equiv.forall₂_congr', `equiv.forall_congr', -- Allow rewriting in argument of Pi types: `equiv.Pi_congr_left', -- Handles `sum` and `prod`, and many others: `bifunctor.map_equiv, -- Handles `list`, `option`, `unique`, and many others: `equiv_functor.map_equiv, -- We have to filter results to ensure we don't cheat and use exclusively `equiv.refl` and `iff.refl`! `equiv.refl, `iff.refl ].mmap (λ n, try_core (mk_const n)), return (exprs.map option.to_list).join -- TODO: implement `.mfilter_map mk_const`? declare_trace equiv_rw_type /-- Configuration structure for `equiv_rw`. * `max_depth` bounds the search depth for equivalences to rewrite along. The default value is 10. (e.g., if you're rewriting along `e : α ≃ β`, and `max_depth := 2`, you can rewrite `option (option α))` but not `option (option (option α))`. -/ meta structure equiv_rw_cfg := (max_depth : ℕ := 10) /-- Implementation of `equiv_rw_type`, using `solve_by_elim`. Expects a goal of the form `t ≃ _`, and tries to solve it using `eq : α ≃ β` and congruence lemmas. -/ meta def equiv_rw_type_core (eq : expr) (cfg : equiv_rw_cfg) : tactic unit := do -- Assemble the relevant lemmas. equiv_congr_lemmas ← equiv_congr_lemmas, /- We now call `solve_by_elim` to try to generate the requested equivalence. There are a few subtleties! * We make sure that `eq` is the first lemma, so it is applied whenever possible. * In `equiv_congr_lemmas`, we put `equiv.refl` last so it is only used when it is not possible to descend further. * Since some congruence lemmas generate subgoals with `∀` statements, we use the `pre_apply` subtactic of `solve_by_elim` to preprocess each new goal with `intros`. -/ solve_by_elim { use_symmetry := false, use_exfalso := false, lemmas := some (eq :: equiv_congr_lemmas), max_depth := cfg.max_depth, -- Subgoals may contain function types, -- and we want to continue trying to construct equivalences after the binders. pre_apply := tactic.intros >> skip, -- If solve_by_elim gets stuck, make sure it isn't because there's a later `≃` or `↔` goal -- that we should still attempt. discharger := `[show _ ≃ _] <|> `[show _ ↔ _] <|> trace_if_enabled `equiv_rw_type "Failed, no congruence lemma applied!" >> failed, -- We use the `accept` tactic in `solve_by_elim` to provide tracing. accept := λ goals, lock_tactic_state (do when_tracing `equiv_rw_type (do goals.mmap pp >>= λ goals, trace format!"So far, we've built: {goals}"), done <|> when_tracing `equiv_rw_type (do gs ← get_goals, gs ← gs.mmap (λ g, infer_type g >>= pp), trace format!"Attempting to adapt to {gs}")) } /-- `equiv_rw_type e t` rewrites the type `t` using the equivalence `e : α ≃ β`, returning a new equivalence `t ≃ t'`. -/ meta def equiv_rw_type (eqv : expr) (ty : expr) (cfg : equiv_rw_cfg) : tactic expr := do when_tracing `equiv_rw_type (do ty_pp ← pp ty, eqv_pp ← pp eqv, eqv_ty_pp ← infer_type eqv >>= pp, trace format!"Attempting to rewrite the type `{ty_pp}` using `{eqv_pp} : {eqv_ty_pp}`."), `(_ ≃ _) ← infer_type eqv | fail format!"{eqv} must be an `equiv`", -- We prepare a synthetic goal of type `(%%ty ≃ _)`, for some placeholder right hand side. equiv_ty ← to_expr ``(%%ty ≃ _), -- Now call `equiv_rw_type_core`. new_eqv ← prod.snd <$> (solve_aux equiv_ty $ equiv_rw_type_core eqv cfg), -- Check that we actually used the equivalence `eq` -- (`equiv_rw_type_core` will always find `equiv.refl`, but hopefully only after all other possibilities) new_eqv ← instantiate_mvars new_eqv, -- We previously had `guard (eqv.occurs new_eqv)` here, but `kdepends_on` is more reliable. kdepends_on new_eqv eqv >>= guardb <|> (do eqv_pp ← pp eqv, ty_pp ← pp ty, fail format!"Could not construct an equivalence from {eqv_pp} of the form: {ty_pp} ≃ _"), -- Finally we simplify the resulting equivalence, -- to compress away some `map_equiv equiv.refl` subexpressions. prod.fst <$> new_eqv.simp {fail_if_unchanged := ff} mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to simplify applications of equivalences and their inverses." attribute [equiv_rw_simp] equiv.symm_symm equiv.apply_symm_apply equiv.symm_apply_apply /-- Attempt to replace the hypothesis with name `x` by transporting it along the equivalence in `e : α ≃ β`. -/ meta def equiv_rw_hyp (x : name) (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := -- We call `dsimp_result` to perform the beta redex introduced by `revert` dsimp_result (do x' ← get_local x, x_ty ← infer_type x', -- Adapt `e` to an equivalence with left-hand-side `x_ty`. e ← equiv_rw_type e x_ty cfg, eq ← to_expr ``(%%x' = equiv.symm %%e (equiv.to_fun %%e %%x')), prf ← to_expr ``((equiv.symm_apply_apply %%e %%x').symm), h ← note_anon eq prf, -- Revert the new hypothesis, so it is also part of the goal. revert h, ex ← to_expr ``(equiv.to_fun %%e %%x'), -- Now call `generalize`, -- attempting to replace all occurrences of `e x`, -- calling it for now `j : β`, with `k : x = e.symm j`. generalize ex (by apply_opt_param) transparency.none, -- Reintroduce `x` (now of type `b`), and the hypothesis `h`. intro x, h ← intro1, -- We may need to unfreeze `x` before we can `subst` or `clear` it. unfreeze x', -- Finally, if we're working on properties, substitute along `h`, then do some cleanup, -- and if we're working on data, just throw out the old `x`. b ← target >>= is_prop, if b then do subst h, `[try { simp only [] with equiv_rw_simp }] else clear' tt [x'] <|> fail format!"equiv_rw expected to be able to clear the original hypothesis {x}, but couldn't.", skip) {fail_if_unchanged := ff} tt -- call `dsimp_result` with `no_defaults := tt`. /-- Rewrite the goal using an equiv `e`. -/ meta def equiv_rw_target (e : expr) (cfg : equiv_rw_cfg := {}) : tactic unit := do t ← target, e ← equiv_rw_type e t cfg, s ← to_expr ``(equiv.inv_fun %%e), tactic.eapply s, skip end tactic namespace tactic.interactive open lean.parser open interactive interactive.types open tactic local postfix `?`:9001 := optional /-- `equiv_rw e at h`, where `h : α` is a hypothesis, and `e : α ≃ β`, will attempt to transport `h` along `e`, producing a new hypothesis `h : β`, with all occurrences of `h` in other hypotheses and the goal replaced with `e.symm h`. `equiv_rw e` will attempt to transport the goal along an equivalence `e : α ≃ β`. In its minimal form it replaces the goal `⊢ α` with `⊢ β` by calling `apply e.inv_fun`. `equiv_rw` will also try rewriting under (equiv_)functors, so can turn a hypothesis `h : list α` into `h : list β` or a goal `⊢ unique α` into `⊢ unique β`. The maximum search depth for rewriting in subexpressions is controlled by `equiv_rw e {max_depth := n}`. -/ meta def equiv_rw (e : parse texpr) (loc : parse $ (tk "at" *> ident)?) (cfg : equiv_rw_cfg := {}) : itactic := do e ← to_expr e, match loc with | (some hyp) := equiv_rw_hyp hyp e cfg | none := equiv_rw_target e cfg end add_tactic_doc { name := "equiv_rw", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw], tags := ["rewriting", "equiv", "transport"] } /-- Solve a goal of the form `t ≃ _`, by constructing an equivalence from `e : α ≃ β`. This is the same equivalence that `equiv_rw` would use to rewrite a term of type `t`. A typical usage might be: ``` have e' : option α ≃ option β := by equiv_rw_type e ``` -/ meta def equiv_rw_type (e : parse texpr) (cfg : equiv_rw_cfg := {}) : itactic := do `(%%t ≃ _) ← target | fail "`equiv_rw_type` solves goals of the form `t ≃ _`.", e ← to_expr e, tactic.equiv_rw_type e t cfg >>= tactic.exact add_tactic_doc { name := "equiv_rw_type", category := doc_category.tactic, decl_names := [`tactic.interactive.equiv_rw_type], tags := ["rewriting", "equiv", "transport"] } end tactic.interactive
f00fcd475d721b176e87f6127124296a29aea703
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Parser/Do.lean
c7eb1af7ce4f352a774e8a57498e6e4a6ff1a5a9
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
7,252
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinDoElemParser `doElem builtin_initialize registerBuiltinDynamicParserAttribute `doElemParser `doElem @[inline] def doElemParser (rbp : Nat := 0) : Parser := categoryParser `doElem rbp namespace Term def leftArrow : Parser := unicodeSymbol " ← " " <- " @[builtinTermParser] def liftMethod := leading_parser:minPrec leftArrow >> termParser def doSeqItem := leading_parser ppLine >> doElemParser >> optional "; " def doSeqIndent := leading_parser many1Indent doSeqItem def doSeqBracketed := leading_parser "{" >> withoutPosition (many1 doSeqItem) >> ppLine >> "}" def doSeq := doSeqBracketed <|> doSeqIndent def termBeforeDo := withForbidden "do" termParser attribute [runBuiltinParserAttributeHooks] doSeq termBeforeDo builtin_initialize register_parser_alias "doSeq" doSeq register_parser_alias "termBeforeDo" termBeforeDo def notFollowedByRedefinedTermToken := -- Remark: we don't currently support `open` and `set_option` in `do`-blocks, but we include them in the following list to fix the ambiguity -- "open" command following `do`-block. If we don't add `do`, then users would have to indent `do` blocks or use `{ ... }`. notFollowedBy ("set_option" <|> "open" <|> "if" <|> "match" <|> "let" <|> "have" <|> "do" <|> "dbg_trace" <|> "assert!" <|> "for" <|> "unless" <|> "return" <|> symbol "try") "token at 'do' element" @[builtinDoElemParser] def doLet := leading_parser "let " >> optional "mut " >> letDecl @[builtinDoElemParser] def doLetRec := leading_parser group ("let " >> nonReservedSymbol "rec ") >> letRecDecls def doIdDecl := leading_parser atomic (ident >> optType >> leftArrow) >> doElemParser def doPatDecl := leading_parser atomic (termParser >> leftArrow) >> doElemParser >> optional (checkColGt >> " | " >> doElemParser) @[builtinDoElemParser] def doLetArrow := leading_parser withPosition ("let " >> optional "mut " >> (doIdDecl <|> doPatDecl)) -- We use `letIdDeclNoBinders` to define `doReassign`. -- Motivation: we do not reassign functions, and avoid parser conflict def letIdDeclNoBinders := node `Lean.Parser.Term.letIdDecl $ atomic (ident >> pushNone >> optType >> " := ") >> termParser @[builtinDoElemParser] def doReassign := leading_parser notFollowedByRedefinedTermToken >> (letIdDeclNoBinders <|> letPatDecl) @[builtinDoElemParser] def doReassignArrow := leading_parser notFollowedByRedefinedTermToken >> withPosition (doIdDecl <|> doPatDecl) @[builtinDoElemParser] def doHave := leading_parser "have " >> Term.haveDecl /- In `do` blocks, we support `if` without an `else`. Thus, we use indentation to prevent examples such as ``` if c_1 then if c_2 then action_1 else action_2 ``` from being parsed as ``` if c_1 then { if c_2 then { action_1 } else { action_2 } } ``` We also have special support for `else if` because we don't want to write ``` if c_1 then action_1 else if c_2 then action_2 else action_3 ``` -/ def elseIf := atomic (group (withPosition (" else " >> checkLineEq >> " if "))) -- ensure `if $e then ...` still binds to `e:term` def doIfLetPure := leading_parser " := " >> termParser def doIfLetBind := leading_parser " ← " >> termParser def doIfLet := nodeWithAntiquot "doIfLet" `Lean.Parser.Term.doIfLet <| "let " >> termParser >> (doIfLetPure <|> doIfLetBind) def doIfProp := nodeWithAntiquot "doIfProp" `Lean.Parser.Term.doIfProp <| optIdent >> termParser def doIfCond := withAntiquot (mkAntiquot "doIfCond" none (anonymous := false)) <| doIfLet <|> doIfProp @[builtinDoElemParser] def doIf := leading_parser withPosition $ "if " >> doIfCond >> " then " >> doSeq >> many (checkColGe "'else if' in 'do' must be indented" >> group (elseIf >> doIfCond >> " then " >> doSeq)) >> optional (checkColGe "'else' in 'do' must be indented" >> " else " >> doSeq) @[builtinDoElemParser] def doUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser @[builtinDoElemParser] def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq def doMatchAlts := matchAlts (rhsParser := doSeq) @[builtinDoElemParser] def doMatch := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> doMatchAlts def doCatch := leading_parser atomic ("catch " >> binderIdent) >> optional (" : " >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq @[builtinDoElemParser] def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinDoElemParser] def doBreak := leading_parser "break" @[builtinDoElemParser] def doContinue := leading_parser "continue" @[builtinDoElemParser] def doReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) @[builtinDoElemParser] def doDbgTrace := leading_parser:leadPrec "dbg_trace " >> ((interpolatedStr termParser) <|> termParser) @[builtinDoElemParser] def doAssert := leading_parser:leadPrec "assert! " >> termParser /- We use `notFollowedBy` to avoid counterintuitive behavior. For example, the `if`-term parser doesn't enforce indentation restrictions, but we don't want it to be used when `doIf` fails. Note that parser priorities would not solve this problem since the `doIf` parser is failing while the `if` parser is succeeding. The first `notFollowedBy` prevents this problem. Consider the `doElem` `x := (a, b⟩` it contains an error since we are using `⟩` instead of `)`. Thus, `doReassign` parser fails. However, `doExpr` would succeed consuming just `x`, and cryptic error message is generated after that. The second `notFollowedBy` prevents this problem. -/ @[builtinDoElemParser] def doExpr := leading_parser notFollowedByRedefinedTermToken >> termParser >> notFollowedBy (symbol ":=" <|> symbol "←" <|> symbol "<-") "unexpected token after 'expr' in 'do' block" @[builtinDoElemParser] def doNested := leading_parser "do " >> doSeq @[builtinTermParser] def «do» := leading_parser:argPrec "do " >> doSeq @[builtinTermParser] def doElem.quot : Parser := leading_parser "`(doElem|" >> toggleInsideQuot doElemParser >> ")" /- macros for using `unless`, `for`, `try`, `return` as terms. They expand into `do unless ...`, `do for ...`, `do try ...`, and `do return ...` -/ @[builtinTermParser] def termUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinTermParser] def termFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq @[builtinTermParser] def termTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinTermParser] def termReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) end Term end Parser end Lean
cf5258f05963cd51ae9703c63f5aec63dc23e6f5
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/fractional_ideal.lean
a9de343bb9234c5c314abc749f3e10c98edaee37
[ "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
39,604
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.localization import ring_theory.noetherian import ring_theory.principal_ideal_domain import tactic.field_simp /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal f` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal f)` instance * `comm_semiring (fractional_ideal f)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal f)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`. * `has_div (fractional_ideal g)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists * `is_noetherian` states that very fractional ideal of a noetherian integral domain is noetherian ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P` (`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce the `R`-algebra structure. We don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization_map namespace ring section defs variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] (f : localization_map S P) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R f.codomain) := ∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R f.codomain // is_fractional f I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] {f : localization_map S P} instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl @[simp, norm_cast] lemma coe_mk (I : submodule R f.codomain) (hI : is_fractional f I) : (subtype.mk I hI : submodule R f.codomain) = I := rfl instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J := subtype.ext_iff_val.mpr lemma ext_iff {I J : fractional_ideal f} : (∀ x, (x ∈ I ↔ x ∈ J)) ↔ I = J := ⟨ λ h, ext (submodule.ext h), λ h x, h ▸ iff.rfl ⟩ lemma fractional_of_subset_one (I : submodule R f.codomain) (h : I ≤ (submodule.span R {1})) : is_fractional f I := begin use [1, S.one_mem], intros b hb, rw [f.to_map.map_one, one_mul], rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, rw (show b = f.to_map b', from b'_eq_b.symm), exact set.mem_range_self b', end lemma is_fractional_of_le {I : submodule R f.codomain} {J : fractional_ideal f} (hIJ : I ≤ J) : is_fractional f I := begin obtain ⟨a, a_mem, ha⟩ := J.2, use [a, a_mem], intros b b_mem, exact ha b (hIJ b_mem) end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) := ⟨ λ I, ⟨f.coe_submodule I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩ @[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal f) : submodule R f.codomain) = f.coe_submodule I := rfl @[simp] lemma mem_coe_ideal {x : f.codomain} {I : ideal R} : x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ @[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) := submodule.ext $ λ _, mem_zero_iff @[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal f) = 0 := rfl @[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) : (∃ x', x' ∈ I ∧ f.to_map x' = f.to_map x) ↔ x ∈ I := ⟨λ ⟨x', hx', eq⟩, f.injective h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) : function.injective (coe : ideal R → fractional_ideal f) := λ I J heq, have ∀ (x : R), f.to_map x ∈ (I : fractional_ideal f) ↔ f.to_map x ∈ (J : fractional_ideal f) := λ x, heq ▸ iff.rfl, ideal.ext (by { simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq h] using this }) lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal f) = 0 ↔ I = (⊥ : ideal R) := ⟨λ h, coe_to_fractional_ideal_injective hS h, λ h, by rw [h, coe_to_fractional_ideal_bot]⟩ lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal f) ≠ 0 ↔ I ≠ (⊥ : ideal R) := not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS) lemma coe_to_submodule_eq_bot {I : fractional_ideal f} : (I : submodule R f.codomain) = ⊥ ↔ I = 0 := ⟨λ h, ext (by simp [h]), λ h, by simp [h] ⟩ lemma coe_to_submodule_ne_bot {I : fractional_ideal f} : ↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 := not_iff_not.mpr coe_to_submodule_eq_bot instance : inhabited (fractional_ideal f) := ⟨0⟩ instance : has_one (fractional_ideal f) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨1, f.to_map.map_one⟩ /-- `(1 : fractional_ideal f)` is defined as the R-submodule `f(R) ≤ K`. However, this is not definitionally equal to `1 : submodule R K`, which is proved in the actual `simp` lemma `coe_one`. -/ lemma coe_one_eq_coe_submodule_one : ↑(1 : fractional_ideal f) = f.coe_submodule (1 : ideal R) := rfl @[simp, norm_cast] lemma coe_one : (↑(1 : fractional_ideal f) : submodule R f.codomain) = 1 := begin simp only [coe_one_eq_coe_submodule_one, ideal.one_eq_top], convert (submodule.one_eq_map_top).symm, end section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal f) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff_mem {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.rfl @[simp] lemma coe_le_coe {I J : fractional_ideal f} : (I : submodule R f.codomain) ≤ (J : submodule R f.codomain) ↔ I ≤ J := iff.rfl lemma zero_le (I : fractional_ideal f) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal f) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 := rfl @[simp] lemma le_zero_iff {I : fractional_ideal f} : I ≤ 0 ↔ I = 0 := le_bot_iff lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, mul_add], apply is_integer_add, { rw [mul_comm aI, f.to_map.map_mul, mul_assoc], apply is_integer_smul (hI bI hbI), }, { rw [f.to_map.map_mul, mul_assoc], apply is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal f) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal f) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal f) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl @[simp, norm_cast] lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n], erw ←hn', rw mul_assoc, apply hI, exact submodule.smul_mem _ _ hm }, { rw [mul_zero], exact ⟨0, f.to_map.map_zero⟩ }, { intros x y hx hy, rw [mul_add], apply is_integer_add hx hy }, { intros r x hx, show f.is_integer (_ * (f.to_map r * x)), rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc], apply is_integer_smul hx }, end /-- `fractional_ideal.mul` is the product of two fractional ideals, used to define the `has_mul` instance. This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`. Elaborated terms involving `fractional_ideal` tend to grow quite large, so by making definitions irreducible, we hope to avoid deep unfolds. -/ @[irreducible] def mul (I J : fractional_ideal f) : fractional_ideal f := ⟨I.1 * J.1, fractional_mul I J⟩ local attribute [semireducible] mul instance : has_mul (fractional_ideal f) := ⟨λ I J, mul I J⟩ @[simp] lemma mul_eq_mul (I J : fractional_ideal f) : mul I J = I * J := rfl @[simp, norm_cast] lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) lemma mul_mem_mul {I J : fractional_ideal f} {i j : f.codomain} (hi : i ∈ I) (hj : j ∈ J) : i * j ∈ I * J := submodule.mul_mem_mul hi hj lemma mul_le {I J K : fractional_ideal f} : I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) := submodule.mul_le @[elab_as_eliminator] protected theorem mul_induction_on {I J : fractional_ideal f} {C : f.codomain → Prop} {r : f.codomain} (hr : r ∈ I * J) (hm : ∀ (i ∈ I) (j ∈ J), C (i * j)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := submodule.mul_induction_on hr hm h0 ha hs instance comm_semiring : comm_semiring (fractional_ideal f) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, rw [←y'_eq_y, mul_comm], exact submodule.smul_mem _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one, rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, rw ←x'_eq_x, exact submodule.smul_mem _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h, rwa [one_mul] at this } end, mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.has_zero, ..fractional_ideal.has_add, ..fractional_ideal.has_one, ..fractional_ideal.has_mul } section order lemma add_le_add_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) : J' + I ≤ J' + J := sup_le_sup_left hIJ J' lemma mul_le_mul_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) : J' * I ≤ J' * J := mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj)) lemma le_self_mul_self {I : fractional_ideal f} (hI: 1 ≤ I) : I ≤ I * I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma mul_self_le_self {I : fractional_ideal f} (hI: I ≤ 1) : I * I ≤ I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal f) ≤ 1 := λ x hx, let ⟨y, _, hy⟩ := fractional_ideal.mem_coe_ideal.mp hx in fractional_ideal.mem_one_iff.mpr ⟨y, hy⟩ lemma le_one_iff_exists_coe_ideal {J : fractional_ideal f} : J ≤ (1 : fractional_ideal f) ↔ ∃ (I : ideal R), ↑I = J := begin split, { intro hJ, refine ⟨⟨{x : R | f.to_map x ∈ J}, _, _, _⟩, _⟩, { rw [mem_set_of_eq, ring_hom.map_zero], exact J.val.zero_mem }, { intros a b ha hb, rw [mem_set_of_eq, ring_hom.map_add], exact J.val.add_mem ha hb }, { intros c x hx, rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul], exact J.val.smul_mem c hx }, { ext x, split, { rintros ⟨y, hy, eq_y⟩, rwa ← eq_y }, { intro hx, obtain ⟨y, eq_x⟩ := fractional_ideal.mem_one_iff.mp (hJ hx), rw ← eq_x at *, exact ⟨y, hx, rfl⟩ } } }, { rintro ⟨I, hI⟩, rw ← hI, apply coe_ideal_le_one }, end end order variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'} variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''} lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : is_fractional f' (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'], refl end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : f.codomain →ₐ[R] f'.codomain) : fractional_ideal f → fractional_ideal f' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp, norm_cast] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma mem_map {I : fractional_ideal f} {g : f.codomain →ₐ[R] f'.codomain} {y : f'.codomain} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := submodule.mem_map variables (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) @[simp] lemma map_id : I.map (alg_hom.id _ _) = I := ext (submodule.map_id I.1) @[simp] lemma map_comp (g' : f'.codomain →ₐ[R] f''.codomain) : I.map (g'.comp g) = (I.map g).map g' := ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp, norm_cast] lemma map_coe_ideal (I : ideal R) : (I : fractional_ideal f).map g = I := begin ext x, simp only [coe_coe_ideal, mem_coe_submodule], split, { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩, exact ⟨y, hy, (g.commutes y).symm⟩ }, { rintro ⟨y, hy, rfl⟩, exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ }, end @[simp] lemma map_one : (1 : fractional_ideal f).map g = 1 := map_coe_ideal g 1 @[simp] lemma map_zero : (0 : fractional_ideal f).map g = 0 := map_coe_ideal g 0 @[simp] lemma map_add : (I + J).map g = I.map g + J.map g := ext (submodule.map_sup _ _ _) @[simp] lemma map_mul : (I * J).map g = I.map g * J.map g := ext (submodule.map_mul _ _ _) @[simp] lemma map_map_symm (g : f.codomain ≃ₐ[R] f'.codomain) : (I.map (g : f.codomain →ₐ[R] f'.codomain)).map (g.symm : f'.codomain →ₐ[R] f.codomain) = I := by rw [←map_comp, g.symm_comp, map_id] @[simp] lemma map_symm_map (I : fractional_ideal f') (g : f.codomain ≃ₐ[R] f'.codomain) : (I.map (g.symm : f'.codomain →ₐ[R] f.codomain)).map (g : f.codomain →ₐ[R] f'.codomain) = I := by rw [←map_comp, g.comp_symm, map_id] /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : fractional_ideal f ≃+* fractional_ideal f' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma coe_fun_map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : ⇑(map_equiv g) = map g := rfl @[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_symm (g : f.codomain ≃ₐ[R] f'.codomain) : (map_equiv g).symm = map_equiv g.symm := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) := ring_equiv.ext (λ x, by simp) lemma is_fractional_span_iff {s : set f.codomain} : is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) := ⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (by { rw mul_zero, exact f.is_integer_zero }) (λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩ lemma is_fractional_of_fg {I : submodule R f.codomain} (hI : I.fg) : is_fractional f I := begin rcases hI with ⟨I, rfl⟩, rcases localization_map.exist_integer_multiples_of_finset f I with ⟨⟨s, hs1⟩, hs⟩, rw is_fractional_span_iff, exact ⟨s, hs1, hs⟩, end /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `f.codomain` and in `f'.codomain` -/ @[irreducible] noncomputable def canonical_equiv (f : localization_map S P) (f' : localization_map S P') : fractional_ideal f ≃+* fractional_ideal f' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _, ..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R) (by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } @[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal f} {x : f'.codomain} : x ∈ canonical_equiv f f' I ↔ ∃ y ∈ I, @localization_map.map _ _ _ _ _ _ _ f (ring_hom.id _) _ (λ ⟨y, hy⟩, hy) _ _ f' y = x := begin rw [canonical_equiv, map_equiv_apply, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ end @[simp] lemma canonical_equiv_symm (f : localization_map S P) (f' : localization_map S P') : (canonical_equiv f f').symm = canonical_equiv f' f := ring_equiv.ext $ λ I, fractional_ideal.ext_iff.mp $ λ x, by { erw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ } @[simp] lemma canonical_equiv_flip (f : localization_map S P) (f' : localization_map S P') (I) : canonical_equiv f f' (canonical_equiv f' f I) = I := by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply] end semiring section fraction_map /-! ### `fraction_map` section This section concerns fractional ideals in the field of fractions, i.e. the type `fractional_ideal g` when `g` is a `fraction_map R K`. -/ variables {K K' : Type*} [field K] [field K'] {g : fraction_map R K} {g' : fraction_map R K'} variables {I J : fractional_ideal g} (h : g.codomain →ₐ[R] g'.codomain) /-- Nonzero fractional ideals contain a nonzero integer. -/ lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) : ∃ x ≠ (0 : R), g.to_map x ∈ I := begin obtain ⟨y, y_mem, y_not_mem⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr hI), have y_ne_zero : y ≠ 0 := by simpa using y_not_mem, obtain ⟨z, ⟨x, hx⟩⟩ := g.exists_integer_multiple y, refine ⟨x, _, _⟩, { rw [ne.def, ← g.to_map_eq_zero_iff, hx], exact mul_ne_zero (g.to_map_ne_zero_of_mem_non_zero_divisors _) y_ne_zero }, { rw hx, exact smul_mem _ _ y_mem } end lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := begin obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI, contrapose! x_ne_zero with map_eq_zero, refine g'.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)), exact ⟨g.to_map x, hx, h.commutes x⟩, end @[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨imp_of_not_imp_not _ _ (map_ne_zero _), λ hI, hI.symm ▸ map_zero h⟩ end fraction_map section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K} instance : nontrivial (fractional_ideal g) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal g) := by rw ←g.to_map.map_one; convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this) ⟩⟩ lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : is_fractional g (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero, have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ, contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'], exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal g) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ variables {I J : fractional_ideal g} [ J ≠ 0 ] @[simp] lemma div_zero {I : fractional_ideal g} : I / 0 = 0 := dif_pos rfl lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] lemma coe_div {I J : fractional_ideal g} (hJ : J ≠ 0) : (↑(I / J) : submodule R₁ g.codomain) = ↑I / (↑J : submodule R₁ g.codomain) := begin unfold has_div.div, simp only [dif_neg hJ, coe_mk, val_eq_coe], end lemma mem_div_iff_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem } lemma mul_one_div_le_one {I : fractional_ideal g} : I * (1 / I) ≤ 1 := begin by_cases hI : I = 0, { rw [hI, div_zero, mul_zero], exact zero_le 1 }, { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one], apply submodule.mul_one_div_le_one }, end lemma le_self_mul_one_div {I : fractional_ideal g} (hI : I ≤ (1 : fractional_ideal g)) : I ≤ I * (1 / I) := begin by_cases hI_nz : I = 0, { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 }, { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one], rw [← coe_le_coe, coe_one] at hI, exact submodule.le_self_mul_one_div hI }, end lemma le_div_iff_of_nonzero {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J := ⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx), λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩ lemma le_div_iff_mul_le {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := begin rw div_nonzero hJ', convert submodule.le_div_iff_mul_le using 1, rw [val_eq_coe, val_eq_coe, ←coe_mul], refl, end @[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (g.to_map.map_one ▸ coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw mul_comm, convert submodule.smul_mem _ y' h, rw ←y_eq_y', refl } end lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], }) theorem eq_one_div_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : J = 1 / I := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply mul_left_mono I, apply (le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact mul_mem_mul hx hy, end theorem mul_div_self_cancel_iff {I : fractional_ideal g} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one I J hJ]⟩ variables {K' : Type*} [field K'] {g' : fraction_map R₁ K'} @[simp] lemma map_div (I J : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) : (I / J).map (h : g.codomain →ₐ[R₁] g'.codomain) = I.map h / J.map h := begin by_cases H : J = 0, { rw [H, div_zero, map_zero, div_zero] }, { ext x, simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] } end @[simp] lemma map_one_div (I : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) : (1 / I).map (h : g.codomain →ₐ[R₁] g'.codomain) = 1 / I.map h := by rw [map_div, map_one] end quotient section principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K} open_locale classical open submodule submodule.is_principal lemma is_fractional_span_singleton (x : f.codomain) : is_fractional f (span R {x}) := let ⟨a, ha⟩ := f.exists_integer_multiple x in is_fractional_span_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩ /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ @[irreducible] def span_singleton (x : f.codomain) : fractional_ideal f := ⟨span R {x}, is_fractional_span_singleton x⟩ local attribute [semireducible] span_singleton @[simp] lemma coe_span_singleton (x : f.codomain) : (span_singleton x : submodule R f.codomain) = span R {x} := rfl @[simp] lemma mem_span_singleton {x y : f.codomain} : x ∈ span_singleton y ↔ ∃ (z : R), z • y = x := submodule.mem_span_singleton lemma mem_span_singleton_self (x : f.codomain) : x ∈ span_singleton x := mem_span_singleton.mpr ⟨1, one_smul _ _⟩ lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal (I : submodule R f.codomain)] : I = span_singleton (generator (I : submodule R f.codomain)) := ext (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal f) : is_principal (I : submodule R f.codomain) ↔ ∃ x, I = span_singleton x := ⟨λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 := ⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ lemma span_singleton_ne_zero_iff {y : f.codomain} : span_singleton y ≠ 0 ↔ y ≠ 0 := not_congr span_singleton_eq_zero_iff @[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 := begin ext, refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm), intro x', refine eq.congr (mul_one _) rfl, end @[simp] lemma span_singleton_mul_span_singleton (x y : f.codomain) : span_singleton x * span_singleton y = span_singleton (x * y) := begin ext, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) := begin ext y, refine mem_coe_ideal.trans (iff.trans _ mem_span_singleton.symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy', use x', rw [smul_eq_mul, f.to_map.map_mul], refl }, { rintros ⟨y', rfl⟩, exact ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ } end @[simp] lemma canonical_equiv_span_singleton (f : localization_map S P) {P'} [comm_ring P'] (f' : localization_map S P') (x : f.codomain) : canonical_equiv f f' (span_singleton x) = span_singleton (f.map (show ∀ (y : S), ring_hom.id _ y.1 ∈ S, from λ y, y.2) f' x) := begin apply ext_iff.mp, intro y, split; intro h, { apply mem_span_singleton.mpr, obtain ⟨x', hx', rfl⟩ := mem_canonical_equiv_apply.mp h, obtain ⟨z, rfl⟩ := mem_span_singleton.mp hx', use z, rw localization_map.map_smul, refl }, { apply mem_canonical_equiv_apply.mpr, obtain ⟨z, rfl⟩ := mem_span_singleton.mp h, use f.to_map z * x, use mem_span_singleton.mpr ⟨z, rfl⟩, rw [ring_hom.map_mul, localization_map.map_eq], refl } end lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} : y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply fractional_ideal.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := mem_span_singleton.mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' } end lemma one_div_span_singleton (x : g.codomain) : 1 / span_singleton x = span_singleton (x⁻¹) := if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one _ _ (by simp [h])).symm @[simp] lemma div_span_singleton (J : fractional_ideal g) (d : g.codomain) : J / span_singleton d = span_singleton (d⁻¹) * J := begin rw ← one_div_span_singleton, by_cases hd : d = 0, { simp only [hd, span_singleton_zero, div_zero, zero_mul] }, have h_spand : span_singleton d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd, apply le_antisymm, { intros x hx, rw [val_eq_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx, specialize hx d (mem_span_singleton_self d), have h_xd : x = d⁻¹ * (x * d), { field_simp }, rw [val_eq_coe, coe_mul, one_div_span_singleton, h_xd], exact submodule.mul_mem_mul (mem_span_singleton_self _) hx }, { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton, span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one], exact le_refl J }, end lemma exists_eq_span_singleton_mul (I : fractional_ideal g) : ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton (g.to_map a)⁻¹ * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero := mt g.to_map_eq_zero_iff.mp nonzero, use a_inv, use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe, split, exact nonzero, ext, refine iff.trans _ mem_singleton_mul.symm, split, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, refine ⟨g.to_map x', mem_coe_ideal.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩, erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := mem_coe_ideal.mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw lin_coe_apply at hx', erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul], exact hy' } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K} (I : fractional_ideal f) : (I : submodule R f.codomain).is_principal := begin obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I, use (f.to_map a)⁻¹ * f.to_map (generator aI), suffices : I = span_singleton ((f.to_map a)⁻¹ * f.to_map (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end end principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] variables {K : Type*} [field K] {g : fraction_map R₁ K} local attribute [instance] classical.prop_decidable lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal g) := is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal g)), by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot }) lemma is_noetherian_iff {I : fractional_ideal g} : is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ g.codomain).fg := is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩ lemma is_noetherian_coe_to_fractional_ideal [is_noetherian_ring R₁] (I : ideal R₁) : is_noetherian R₁ (I : fractional_ideal g) := begin rw is_noetherian_iff, intros J hJ, obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one), exact fg_map (is_noetherian.noetherian J), end lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal g} (hI : is_noetherian R₁ I) : is_noetherian R₁ (span_singleton (g.to_map x)⁻¹ * I : fractional_ideal g) := begin by_cases hx : x = 0, { rw [hx, g.to_map.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul], exact is_noetherian_zero }, have h_gx : g.to_map x ≠ 0, from mt (g.to_map.injective_iff.mp (fraction_map.injective g) x) hx, have h_spanx : span_singleton (g.to_map x) ≠ (0 : fractional_ideal g), from span_singleton_ne_zero_iff.mpr h_gx, rw is_noetherian_iff at ⊢ hI, intros J hJ, rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ, obtain ⟨s, hs⟩ := hI _ hJ, use s * {(g.to_map x)⁻¹}, rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton, ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx, span_singleton_one, mul_one], end /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem is_noetherian [is_noetherian_ring R₁] (I : fractional_ideal g) : is_noetherian R₁ I := begin obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I, apply is_noetherian_span_singleton_inv_to_map_mul, apply is_noetherian_coe_to_fractional_ideal, end end fractional_ideal end ring
0103c82067fe95f43d77f2fd7a579b4988771854
618003631150032a5676f229d13a079ac875ff77
/src/data/zsqrtd/basic.lean
680708991c3dfce0b217a1c2e1a62fdb0225bc45
[ "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
26,125
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import tactic.ring /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, ..}; { intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] } instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance instance : nonzero ℤ√d := { zero_ne_one := dec_trivial } @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b := by simp [ext, add_comm] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext] protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext, sub_eq_add_neg] protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext] protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_add_sub_cancel'] theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_square (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : decidable_linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ eq_of_mul_eq_mul_right w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ eq_of_mul_eq_mul_right z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain ℤ√d := { zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, ..zsqrtd.comm_ring } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : decidable_linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, zero_ne_one := zero_ne_one, mul_pos := @zsqrtd.mul_pos, zero_lt_one := dec_trivial, ..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order } instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end end zsqrtd
489f2dd93f654b92d384140c278fd0a6f36c554d
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/trace.lean
7435713f35d8e0d0cb45b1c853a25cc493bd9211
[ "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
1,375
lean
import Lean.CoreM open Lean structure MyState := (traceState : TraceState := {}) (s : Nat := 0) abbrev M := CoreM def tst1 : M Unit := do trace! `module (m!"hello" ++ MessageData.nest 9 (m!"\n" ++ "world")); trace! `module.aux "another message"; pure () def tst2 (b : Bool) : M Unit := traceCtx `module $ do tst1; trace! `bughunt "at test2"; when b $ throwError "error"; tst1; pure () partial def ack : Nat → Nat → Nat | 0, n => n+1 | m+1, 0 => ack m 1 | m+1, n+1 => ack m (ack (m+1) n) def slow (b : Bool) : Nat := ack 4 (cond b 0 1) def tst3 (b : Bool) : M Unit := do traceCtx `module $ do { tst2 b; tst1 }; trace! `bughunt "at end of tst3"; -- Messages are computed lazily. The following message will only be computed -- if `trace.slow is active. trace! `slow (m!"slow message: " ++ toString (slow b)) def run (x : M Unit) : M Unit := withReader (fun ctx => -- Try commeting/uncommeting the following `setBool`s let opts := ctx.options; let opts := opts.setBool `trace.module true; -- let opts := opts.setBool `trace.module.aux false; let opts := opts.setBool `trace.bughunt true; -- let opts := opts.setBool `trace.slow true; { ctx with options := opts }) (tryCatch (tryFinally x printTraces) (fun _ => IO.println "ERROR")) #eval run (tst3 true) #eval run (tst3 false)
6709c55c15a452c8686064ee168956a63aafcaaa
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/parser/stringliteral.lean
0440387bf3ca68a003226a8a9579718f3c14661e
[ "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
1,667
lean
/- Copyright (c) 2018 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.parser.parsec namespace Lean namespace Parser open MonadParsec variables {m : Type → Type} {μ : Type} [Monad m] [MonadParsec μ m] [Alternative m] def parseHexDigit : m Nat := ( (do d ← digit, pure $ d.toNat - '0'.toNat) <|> (do c ← satisfy (λ c, 'a'.val ≤ c.val && c.val ≤ 'f'.val), pure $ 10 + (c.toNat - 'a'.toNat)) <|> (do c ← satisfy (λ c, 'A'.val ≤ c.val && c.val ≤ 'F'.val), pure $ 10 + (c.toNat - 'A'.toNat))) <?> "hexadecimal" def parseQuotedChar : m Char := do it ← leftOver, c ← any, if c = '\\' then pure '\\' else if c = '\"' then pure '\"' else if c = '\'' then pure '\'' else if c = 'n' then pure '\n' else if c = 't' then pure '\t' else if c = 'x' then do { d₁ ← parseHexDigit, d₂ ← parseHexDigit, pure $ Char.ofNat (16*d₁ + d₂) } else if c = 'u' then do { d₁ ← parseHexDigit, d₂ ← parseHexDigit, d₃ ← parseHexDigit, d₄ ← parseHexDigit, pure $ Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄) } else unexpectedAt "quoted character" it def parseStringLiteralAux : Nat → String → m String | 0 s := ch '\"' *> pure s | (n+1) s := do c ← any, if c = '\\' then do c ← parseQuotedChar, parseStringLiteralAux n (s.push c) else if c = '\"' then pure s else parseStringLiteralAux n (s.push c) def parseStringLiteral : m String := do ch '\"', r ← remaining, parseStringLiteralAux r "" end Parser end Lean
4b1d7253e7b3370ecad45cb4fe52d23b33ebc473
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/topology/algebra/group.lean
c766b209e13f2e092ed405dd18ba239affb20477
[ "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
20,435
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of topological groups. -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph open classical set filter topological_space open_locale classical topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group section prio set_option default_priority 100 -- see Note [default priority] /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends topological_add_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive topological_add_group] class topological_group (α : Type*) [topological_space α] [group α] extends topological_monoid α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) end prio variables [topological_space α] [group α] @[to_additive] lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv @[to_additive] lemma continuous.inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf @[to_additive] lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) := tendsto.comp (continuous_iff_continuous_at.mp topological_group.continuous_inv a) hf @[to_additive] lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β} (hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x := hf.inv @[to_additive] lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) : continuous_within_at (λx, (f x)⁻¹) s x := hf.inv @[to_additive topological_add_group] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv } attribute [instance] prod.topological_add_group @[to_additive] protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive] protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv α } @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) := tendsto_mul (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) ((𝓝 (1:α)).prod (𝓝 (1:α))) (𝓝 1), { simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ (𝓝 (1:α)).prod (𝓝 (1:α)) := this (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1), { simpa using (@tendsto_id α (𝓝 1)).inv }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa }, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : set α) [normal_subgroup N] @[to_additive] instance {α : Type u} [group α] [topological_space α] (N : set α) [normal_subgroup N] : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance open quotient_group @[to_additive quotient_add_group_saturate] lemma quotient_group_saturate {α : Type u} [group α] (N : set α) [normal_subgroup N] (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left, hi]⟩ } end @[to_additive] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive topological_add_group_quotient] instance topological_group_quotient : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_fst.sub continuous_snd lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := continuous_sub.comp_continuous_on (hf.prod hg) lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x end topological_add_group section prio set_option default_priority 100 -- see Note [default priority] /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z [] : filter α) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) end prio namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ v w ∈ V, v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ (Z α).prod (Z α) := add_Z (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 b t0 hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ _ hxt hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : topological_add_monoid α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α)) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space α] [group α] [topological_group α] @[to_additive] lemma is_open_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : α), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : α), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (α) lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space α] : regular_space α := ⟨assume s a hs ha, let f := λ p : α × α, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in begin use s * t₂, use is_open_mul_left ht₂, use λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space α] [group α] [topological_group α] /-- Given a open neighborhood `U` of `1` there is a open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma one_open_separated_mul {U : set α} (h1U : is_open U) (h2U : (1 : α) ∈ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ V * V ⊆ U := begin rcases exists_nhds_square (continuous_mul U h1U) (by simp only [mem_preimage, one_mul, h2U] : ((1 : α), (1 : α)) ∈ (λ p : α × α, p.1 * p.2) ⁻¹' U) with ⟨V, h1V, h2V, h3V⟩, refine ⟨V, h1V, h2V, _⟩, rwa [← image_subset_iff, image_mul_prod] at h3V end /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ K * V ⊆ U := begin let W : α → set α := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, continuous_mul_left x U hU, have h2W : ∀ x ∈ K, (1 : α) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, one_open_separated_mul (h1W x) (h2W x.1 x.2), let X : K → set α := λ x, (λ y, (x : α)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, continuous_mul_left x⁻¹ (V x) (hV x).1) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : α)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set α} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset α, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : α, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space α] [comm_group α] [topological_group α] @[to_additive] lemma nhds_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
2202d001cc44bc499561f952932865cbc0a4956b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/int/cast.lean
bd7dee2ef7aab81afae3d28b8677d54c56e29c13
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
11,653
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.basic import data.nat.cast /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into a type `α` with `0`, `1`, `+` and `-` (typically a `ring`). ## Main declarations * `cast`: Canonical homomorphism `ℤ → α` where `α` has a `0`, `1`, `+` and `-`. * `cast_add_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. ## Implementation note Setting up the coercions priorities is tricky. See Note [coercion into rings]. -/ open nat namespace int @[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := by simpa only [sub_eq_add_neg] using cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x := int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left) lemma cast_comm [ring α] (m : ℤ) (x : α) : (m : α) * x = x * m := (cast_commute m x).eq lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) := begin intros m n h, rw ← sub_nonneg at h, lift n - m to ℕ using h with k, rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat], exact k.cast_nonneg end @[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one, by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le @[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) := strict_mono_of_le_iff_le $ λ m n, cast_le.symm @[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) < n ↔ m < n := cast_strict_mono.lt_iff_lt @[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [linear_ordered_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := monotone.map_min cast_mono @[simp, norm_cast] theorem cast_max [linear_ordered_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := monotone.map_max cast_mono @[simp, norm_cast] theorem cast_abs [linear_ordered_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] lemma cast_nat_abs {R : Type*} [linear_ordered_ring R] : ∀ (n : ℤ), (n.nat_abs : R) = abs n | (n : ℕ) := by simp only [int.nat_abs_of_nat, int.cast_coe_nat, nat.abs_cast] | -[1+n] := by simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast] lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (int.cast_ring_hom α) h end cast end int namespace prod variables {α : Type*} {β : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α] [has_zero β] [has_one β] [has_add β] [has_neg β] @[simp] lemma fst_int_cast (n : ℤ) : (n : α × β).fst = n := by induction n; simp * @[simp] lemma snd_int_cast (n : ℤ) : (n : α × β).snd = n := by induction n; simp * end prod open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1) variables [add_group A] [has_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n := ext_iff.1 (f.eq_int_cast_hom h1) end add_monoid_hom namespace monoid_hom variables {M : Type*} [monoid M] open multiplicative @[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g := monoid_hom.ext $ add_monoid_hom.ext_iff.mp $ @add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1 /-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) : f = g := begin ext (x | x), { exact (monoid_hom.congr_fun h_nat x : _), }, { rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul], congr' 1, exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), } end end monoid_hom namespace monoid_with_zero_hom variables {M : Type*} [monoid_with_zero M] /-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : monoid_with_zero_hom ℤ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom = g.comp int.of_nat_hom.to_monoid_with_zero_hom) : f = g := to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _) /-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/ theorem ext_int' {φ₁ φ₂ : monoid_with_zero_hom ℤ M} (h_neg_one : φ₁ (-1) = φ₂ (-1)) (h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ := ext_int h_neg_one $ ext_nat h_pos end monoid_with_zero_hom namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm namespace pi variables {α β : Type*} lemma int_apply [has_zero β] [has_one β] [has_add β] [has_neg β] : ∀ (n : ℤ) (a : α), (n : α → β) a = n | (n:ℕ) a := pi.nat_apply n a | -[1+n] a := by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, neg_apply, add_apply, one_apply, nat_apply] @[simp] lemma coe_int [has_zero β] [has_one β] [has_add β] [has_neg β] (n : ℤ) : (n : α → β) = λ _, n := by { ext, rw pi.int_apply } end pi
07912942dec64456caaa23843541073794da6b14
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/category_theory/functor.lean
ab227e097c52360d7d3d9e479d8f82e6fc56e481
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
3,111
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison Defines a functor between categories. (As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised by the underlying function on objects, the name is capitalised.) Introduces notations `C ⥤ D` for the type of all functors from `C` to `D`. (I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.) -/ import category_theory.category namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id_lemma` expresses preservation of identities, and `map_comp_lemma` expresses functoriality. -/ structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] : Type (max v₁ v₂ u₁ u₂) := (obj : C → D) (map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) -- A functor is basically a function, so give ⥤ a similar precedence to → (25). -- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`. infixr ` ⥤ `:26 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [simp] functor.map_comp namespace functor section variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 /-- `𝟭 C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } notation `𝟭` := functor.id variable {C} @[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl end section variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) (X Y : C) (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl end section variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 @[simp] def ulift_down : (ulift.{u₂} C) ⥤ C := { obj := λ X, X.down, map := λ X Y f, f } @[simp] def ulift_up : C ⥤ (ulift.{u₂} C) := { obj := λ X, ⟨ X ⟩, map := λ X Y f, f } end end functor end category_theory
800b05c0d98fa4ff802118bc6d6caf5140209cff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/prime_ideal.lean
1ca320f66c408d96bab6ffe9f74b60e0cc6ce5ce
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,286
lean
/- Copyright (c) 2021 Noam Atar. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Noam Atar -/ import order.ideal import order.pfilter /-! # Prime ideals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions Throughout this file, `P` is at least a preorder, but some sections require more structure, such as a bottom element, a top element, or a join-semilattice structure. - `order.ideal.prime_pair`: A pair of an `ideal` and a `pfilter` which form a partition of `P`. This is useful as giving the data of a prime ideal is the same as giving the data of a prime filter. - `order.ideal.is_prime`: a predicate for prime ideals. Dual to the notion of a prime filter. - `order.pfilter.is_prime`: a predicate for prime filters. Dual to the notion of a prime ideal. ## References - <https://en.wikipedia.org/wiki/Ideal_(order_theory)> ## Tags ideal, prime -/ open order.pfilter namespace order variables {P : Type*} namespace ideal /-- A pair of an `ideal` and a `pfilter` which form a partition of `P`. -/ @[nolint has_nonempty_instance] structure prime_pair (P : Type*) [preorder P] := (I : ideal P) (F : pfilter P) (is_compl_I_F : is_compl (I : set P) F) namespace prime_pair variables [preorder P] (IF : prime_pair P) lemma compl_I_eq_F : (IF.I : set P)ᶜ = IF.F := IF.is_compl_I_F.compl_eq lemma compl_F_eq_I : (IF.F : set P)ᶜ = IF.I := IF.is_compl_I_F.eq_compl.symm lemma I_is_proper : is_proper IF.I := begin cases IF.F.nonempty, apply is_proper_of_not_mem (_ : w ∉ IF.I), rwa ← IF.compl_I_eq_F at h, end lemma disjoint : disjoint (IF.I : set P) IF.F := IF.is_compl_I_F.disjoint lemma I_union_F : (IF.I : set P) ∪ IF.F = set.univ := IF.is_compl_I_F.sup_eq_top lemma F_union_I : (IF.F : set P) ∪ IF.I = set.univ := IF.is_compl_I_F.symm.sup_eq_top end prime_pair /-- An ideal `I` is prime if its complement is a filter. -/ @[mk_iff] class is_prime [preorder P] (I : ideal P) extends is_proper I : Prop := (compl_filter : is_pfilter (I : set P)ᶜ) section preorder variable [preorder P] /-- Create an element of type `order.ideal.prime_pair` from an ideal satisfying the predicate `order.ideal.is_prime`. -/ def is_prime.to_prime_pair {I : ideal P} (h : is_prime I) : prime_pair P := { I := I, F := h.compl_filter.to_pfilter, is_compl_I_F := is_compl_compl } lemma prime_pair.I_is_prime (IF : prime_pair P) : is_prime IF.I := { compl_filter := by { rw IF.compl_I_eq_F, exact IF.F.is_pfilter }, ..IF.I_is_proper } end preorder section semilattice_inf variables [semilattice_inf P] {x y : P} {I : ideal P} lemma is_prime.mem_or_mem (hI : is_prime I) {x y : P} : x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := begin contrapose!, let F := hI.compl_filter.to_pfilter, show x ∈ F ∧ y ∈ F → x ⊓ y ∈ F, exact λ h, inf_mem h.1 h.2, end lemma is_prime.of_mem_or_mem [is_proper I] (hI : ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I) : is_prime I := begin rw is_prime_iff, use ‹_›, apply is_pfilter.of_def, { exact set.nonempty_compl.2 (I.is_proper_iff.1 ‹_›) }, { intros x _ y _, refine ⟨x ⊓ y, _, inf_le_left, inf_le_right⟩, have := mt hI, tauto! }, { exact @mem_compl_of_ge _ _ _ } end lemma is_prime_iff_mem_or_mem [is_proper I] : is_prime I ↔ ∀ {x y : P}, x ⊓ y ∈ I → x ∈ I ∨ y ∈ I := ⟨is_prime.mem_or_mem, is_prime.of_mem_or_mem⟩ end semilattice_inf section distrib_lattice variables [distrib_lattice P] {I : ideal P} @[priority 100] instance is_maximal.is_prime [is_maximal I] : is_prime I := begin rw is_prime_iff_mem_or_mem, intros x y, contrapose!, rintro ⟨hx, hynI⟩ hxy, apply hynI, let J := I ⊔ principal x, have hJuniv : (J : set P) = set.univ := is_maximal.maximal_proper (lt_sup_principal_of_not_mem ‹_›), have hyJ : y ∈ ↑J := set.eq_univ_iff_forall.mp hJuniv y, rw coe_sup_eq at hyJ, rcases hyJ with ⟨a, ha, b, hb, hy⟩, rw hy, refine sup_mem ha (I.lower (le_inf hb _) hxy), rw hy, exact le_sup_right end end distrib_lattice section boolean_algebra variables [boolean_algebra P] {x : P} {I : ideal P} lemma is_prime.mem_or_compl_mem (hI : is_prime I) : x ∈ I ∨ xᶜ ∈ I := begin apply hI.mem_or_mem, rw inf_compl_eq_bot, exact I.bot_mem, end lemma is_prime.mem_compl_of_not_mem (hI : is_prime I) (hxnI : x ∉ I) : xᶜ ∈ I := hI.mem_or_compl_mem.resolve_left hxnI lemma is_prime_of_mem_or_compl_mem [is_proper I] (h : ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I) : is_prime I := begin simp only [is_prime_iff_mem_or_mem, or_iff_not_imp_left], intros x y hxy hxI, have hxcI : xᶜ ∈ I := h.resolve_left hxI, have ass : (x ⊓ y) ⊔ (y ⊓ xᶜ) ∈ I := sup_mem hxy (I.lower inf_le_right hxcI), rwa [inf_comm, sup_inf_inf_compl] at ass end lemma is_prime_iff_mem_or_compl_mem [is_proper I] : is_prime I ↔ ∀ {x : P}, x ∈ I ∨ xᶜ ∈ I := ⟨λ h _, h.mem_or_compl_mem, is_prime_of_mem_or_compl_mem⟩ @[priority 100] instance is_prime.is_maximal [is_prime I] : is_maximal I := begin simp only [is_maximal_iff, set.eq_univ_iff_forall, is_prime.to_is_proper, true_and], intros J hIJ x, rcases set.exists_of_ssubset hIJ with ⟨y, hyJ, hyI⟩, suffices ass : (x ⊓ y) ⊔ (x ⊓ yᶜ) ∈ J, { rwa sup_inf_inf_compl at ass }, exact sup_mem (J.lower inf_le_right hyJ) (hIJ.le $ I.lower inf_le_right $ is_prime.mem_compl_of_not_mem ‹_› hyI), end end boolean_algebra end ideal namespace pfilter variable [preorder P] /-- A filter `F` is prime if its complement is an ideal. -/ @[mk_iff] class is_prime (F : pfilter P) : Prop := (compl_ideal : is_ideal (F : set P)ᶜ) /-- Create an element of type `order.ideal.prime_pair` from a filter satisfying the predicate `order.pfilter.is_prime`. -/ def is_prime.to_prime_pair {F : pfilter P} (h : is_prime F) : ideal.prime_pair P := { I := h.compl_ideal.to_ideal, F := F, is_compl_I_F := is_compl_compl.symm } lemma _root_.order.ideal.prime_pair.F_is_prime (IF : ideal.prime_pair P) : is_prime IF.F := { compl_ideal := by { rw IF.compl_F_eq_I, exact IF.I.is_ideal } } end pfilter end order
3d4b5d6d10a476b96bb73ddef50629c1e7a05a61
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/measure_theory/l2_space.lean
08718edfc6e125e972da494e5df82bff5b19afd6
[ "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,746
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import analysis.normed_space.inner_product import measure_theory.set_integral /-! # `L^2` space If `E` is an inner product space over `𝕜` (`ℝ` or `ℂ`), then `Lp E 2 μ` (defined in `lp_space.lean`) is also an inner product space, with inner product defined as `inner f g = ∫ a, ⟪f a, g a⟫ ∂μ`. ### Main results * `mem_L1_inner` : for `f` and `g` in `Lp E 2 μ`, the pointwise inner product `λ x, ⟪f x, g x⟫` belongs to `Lp 𝕜 1 μ`. * `integrable_inner` : for `f` and `g` in `Lp E 2 μ`, the pointwise inner product `λ x, ⟪f x, g x⟫` is integrable. * `L2.inner_product_space` : `Lp E 2 μ` is an inner product space. -/ noncomputable theory open topological_space measure_theory measure_theory.Lp open_locale nnreal ennreal measure_theory namespace measure_theory namespace L2 variables {α E F 𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space α] {μ : measure α} [measurable_space E] [inner_product_space 𝕜 E] [borel_space E] [second_countable_topology E] [normed_group F] [measurable_space F] [borel_space F] [second_countable_topology F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y lemma snorm_rpow_two_norm_lt_top (f : Lp F 2 μ) : snorm (λ x, ∥f x∥ ^ (2 : ℝ)) 1 μ < ∞ := begin have h_two : ennreal.of_real (2 : ℝ) = 2, by simp [zero_le_one], rw [snorm_norm_rpow f zero_lt_two, one_mul, h_two], exact ennreal.rpow_lt_top_of_nonneg zero_le_two (Lp.snorm_ne_top f), end lemma snorm_inner_lt_top (f g : α →₂[μ] E) : snorm (λ (x : α), ⟪f x, g x⟫) 1 μ < ∞ := begin have h : ∀ x, is_R_or_C.abs ⟪f x, g x⟫ ≤ ∥f x∥ * ∥g x∥, from λ x, abs_inner_le_norm _ _, have h' : ∀ x, is_R_or_C.abs ⟪f x, g x⟫ ≤ is_R_or_C.abs (∥f x∥^2 + ∥g x∥^2), { refine λ x, le_trans (h x) _, rw [is_R_or_C.abs_to_real, abs_eq_self.mpr], swap, { exact add_nonneg (by simp) (by simp), }, refine le_trans _ (half_le_self (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _))), refine (le_div_iff (@zero_lt_two ℝ _ _)).mpr ((le_of_eq _).trans (two_mul_le_add_pow_two _ _)), ring, }, simp_rw [← is_R_or_C.norm_eq_abs, ← real.rpow_nat_cast] at h', refine (snorm_mono_ae (ae_of_all _ h')).trans_lt ((snorm_add_le _ _ le_rfl).trans_lt _), { exact (Lp.ae_measurable f).norm.pow_const _ }, { exact (Lp.ae_measurable g).norm.pow_const _ }, simp only [nat.cast_bit0, ennreal.add_lt_top, nat.cast_one], exact ⟨snorm_rpow_two_norm_lt_top f, snorm_rpow_two_norm_lt_top g⟩, end section inner_product_space variables [measurable_space 𝕜] [borel_space 𝕜] include 𝕜 instance : has_inner 𝕜 (α →₂[μ] E) := ⟨λ f g, ∫ a, ⟪f a, g a⟫ ∂μ⟩ lemma inner_def (f g : α →₂[μ] E) : inner f g = ∫ a : α, ⟪f a, g a⟫ ∂μ := rfl lemma integral_inner_eq_sq_snorm (f : α →₂[μ] E) : ∫ a, ⟪f a, f a⟫ ∂μ = ennreal.to_real ∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ (2:ℝ) ∂μ := begin simp_rw inner_self_eq_norm_sq_to_K, norm_cast, rw integral_eq_lintegral_of_nonneg_ae, swap, { exact filter.eventually_of_forall (λ x, pow_two_nonneg _), }, swap, { exact (Lp.ae_measurable f).norm.pow_const _ }, congr, ext1 x, have h_two : (2 : ℝ) = ((2 : ℕ) : ℝ), by simp, rw [← real.rpow_nat_cast _ 2, ← h_two, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) zero_le_two, of_real_norm_eq_coe_nnnorm], norm_cast, end private lemma norm_sq_eq_inner' (f : α →₂[μ] E) : ∥f∥ ^ 2 = is_R_or_C.re (inner f f : 𝕜) := begin have h_two : (2 : ℝ≥0∞).to_real = 2 := by simp, rw [inner_def, integral_inner_eq_sq_snorm, norm_def, ← ennreal.to_real_pow, is_R_or_C.of_real_re, ennreal.to_real_eq_to_real (ennreal.pow_lt_top (Lp.snorm_lt_top f) 2) _], { rw [←ennreal.rpow_nat_cast, snorm_eq_snorm' ennreal.two_ne_zero ennreal.two_ne_top, snorm', ← ennreal.rpow_mul, one_div, h_two], simp, }, { refine lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top zero_lt_two _, rw [← h_two, ← snorm_eq_snorm' ennreal.two_ne_zero ennreal.two_ne_top], exact Lp.snorm_lt_top f, }, end lemma mem_L1_inner (f g : α →₂[μ] E) : ae_eq_fun.mk (λ x, ⟪f x, g x⟫) ((Lp.ae_measurable f).inner (Lp.ae_measurable g)) ∈ Lp 𝕜 1 μ := by { simp_rw [mem_Lp_iff_snorm_lt_top, snorm_ae_eq_fun], exact snorm_inner_lt_top f g, } lemma integrable_inner (f g : α →₂[μ] E) : integrable (λ x : α, ⟪f x, g x⟫) μ := (integrable_congr (ae_eq_fun.coe_fn_mk (λ x, ⟪f x, g x⟫) ((Lp.ae_measurable f).inner (Lp.ae_measurable g)))).mp (ae_eq_fun.integrable_iff_mem_L1.mpr (mem_L1_inner f g)) private lemma add_left' (f f' g : α →₂[μ] E) : (inner (f + f') g : 𝕜) = inner f g + inner f' g := begin simp_rw [inner_def, ← integral_add (integrable_inner f g) (integrable_inner f' g), ←inner_add_left], refine integral_congr_ae ((coe_fn_add f f').mono (λ x hx, _)), congr, rwa pi.add_apply at hx, end private lemma smul_left' (f g : α →₂[μ] E) (r : 𝕜) : inner (r • f) g = is_R_or_C.conj r * inner f g := begin rw [inner_def, inner_def, ← smul_eq_mul, ← integral_smul], refine integral_congr_ae ((coe_fn_smul r f).mono (λ x hx, _)), rw [smul_eq_mul, ← inner_smul_left], congr, rwa pi.smul_apply at hx, end instance inner_product_space : inner_product_space 𝕜 (α →₂[μ] E) := { norm_sq_eq_inner := norm_sq_eq_inner', conj_sym := λ _ _, by simp_rw [inner_def, ← integral_conj, inner_conj_sym], add_left := add_left', smul_left := smul_left', } end inner_product_space end L2 end measure_theory
376d1cc15448f3e2c56640b3aec5c154110ec370
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/multiset/intervals.lean
8e88e9c9630dd2d839a6b0bcf477672e79258b95
[ "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
3,613
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.multiset.nodup import data.list.intervals /-! # Intervals in ℕ as multisets For now this only covers `Ico n m`, the "closed-open" interval containing `[n, ..., m-1]`. -/ namespace multiset open list /-! ### Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m ::ₘ Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n ::ₘ Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_le_of_bot {n m : ℕ} (hnm : n < m) : (Ico n m).filter (λ x, x ≤ n) = {n} := congr_arg coe $ list.Ico.filter_le_of_bot hnm lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := congr_arg coe $ list.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := congr_arg coe $ list.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := congr_arg coe $ list.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_le n m l end Ico end multiset
3c8bb443c11f97fe1dea1ef16aaf16787721e86b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/polynomial/coeff.lean
f1b419fa95fa2249d595a7fb6efce78c3dcbc705
[ "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
7,555
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.monomial import data.finset.nat_antidiagonal /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} variables [semiring R] {p q r : polynomial R} section coeff lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_monomial @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_sum [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply lemma sum_def [add_comm_monoid S] (f : ℕ → R → S) : p.sum f = ∑ n in p.support, f n (p.coeff n) := rfl @[simp] lemma coeff_smul (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply _ _ _ @[simp] lemma mem_support_iff : n ∈ p.support ↔ p.coeff n ≠ 0 := by simp [support, coeff] lemma not_mem_support_iff : n ∉ p.support ↔ p.coeff n = 0 := by simp variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : ℕ) : polynomial R →ₗ[R] R := finsupp.lapply n variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl @[simp] lemma finset_sum_coeff {ι : Type*} (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (∑ b in s, f b) n = ∑ b in s, coeff (f b) n := (s.sum_hom (λ q : polynomial R, lcoeff R n q)).symm /-- Decomposes the coefficient of the product `p * q` as a sum over `nat.antidiagonal`. A version which sums over `range (n + 1)` can be obtained by using `finset.nat.sum_antidiagonal_eq_sum_range_succ`. -/ lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := add_monoid_algebra.mul_apply_antidiagonal p q n _ (λ x, nat.mem_antidiagonal) @[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by simp lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 := by simp lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := add_monoid_algebra.single_zero_mul_apply p a n lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := ext $ λ n, coeff_C_mul f @[simp] lemma coeff_mul_C (p : polynomial R) (n : ℕ) (a : R) : coeff (p * C a) n = coeff p n * a := add_monoid_algebra.mul_single_zero_apply p a n lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by { simp only [X_pow_eq_monomial, monomial, single, eq_comm], congr } @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff (X^n : polynomial R) n = 1 := by simp [coeff_X_pow] theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, 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 [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : polynomial R) (n d : ℕ) : (p * X ^ n).coeff d = ite (n ≤ d) (p.coeff (d - n)) 0 := begin split_ifs, { rw [←@nat.sub_add_cancel d n h, coeff_mul_X_pow, nat.add_sub_cancel] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ne_of_lt (lt_of_le_of_lt (nat.le_of_add_le_right (le_of_eq (finset.nat.mem_antidiagonal.mp hx))) (not_le.mp h)) }, end @[simp] theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) lemma C_mul_X_pow_eq_monomial (c : R) (n : ℕ) : C c * X^n = monomial n c := by { ext1, rw [monomial_eq_smul_X, coeff_smul, coeff_C_mul] } lemma support_mul_X_pow (c : R) (n : ℕ) (H : c ≠ 0) : (C c * X^n).support = singleton n := by rw [C_mul_X_pow_eq_monomial, support_monomial n c H] lemma support_C_mul_X_pow' {c : R} {n : ℕ} : (C c * X^n).support ⊆ singleton n := by { rw [C_mul_X_pow_eq_monomial], exact support_monomial' n c } lemma C_dvd_iff_dvd_coeff (r : R) (φ : polynomial R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : ℕ → R := λ i, if i ∈ φ.support then c i else 0, let ψ : polynomial R := ∑ i in φ.support, monomial i (c' i), use ψ, ext i, simp only [ψ, c', coeff_C_mul, mem_support_iff, coeff_monomial, finset_sum_coeff, finset.sum_ite_eq'], split_ifs with hi hi, { rw hc }, { rw [not_not] at hi, rwa mul_zero } }, end end coeff open submodule polynomial set variables {f : polynomial R} {I : submodule (polynomial R) (polynomial R)} /-- If the coefficients of a polynomial belong to n ideal contains the submodule span of the coefficients of a polynomial. -/ lemma span_le_of_coeff_mem_C_inverse (cf : ∀ (i : ℕ), f.coeff i ∈ (C ⁻¹' I.carrier)) : (span (polynomial R) {g | ∃ i, g = C (f.coeff i)}) ≤ I := begin refine bInter_subset_of_mem _, rintros _ ⟨i, rfl⟩, exact set_like.mem_coe.mpr (cf i), end lemma mem_span_C_coeff : f ∈ span (polynomial R) {g : polynomial R | ∃ i : ℕ, g = (C (coeff f i))} := begin rw [← f.sum_single] {occs := occurrences.pos [1]}, refine sum_mem _ (λ i hi, _), change monomial i _ ∈ span _ _, rw [← C_mul_X_pow_eq_monomial, ← X_pow_mul, ← smul_eq_mul], exact smul_mem _ _ (subset_span ⟨i, rfl⟩), end lemma exists_coeff_not_mem_C_inverse : f ∉ I → ∃ i : ℕ , coeff f i ∉ (C ⁻¹' I.carrier) := imp_of_not_imp_not _ _ (λ cf, not_not.mpr ((span_le_of_coeff_mem_C_inverse (not_exists_not.mp cf)) mem_span_C_coeff)) section cast @[simp] lemma nat_cast_coeff_zero {n : ℕ} {R : Type*} [semiring R] : (n : polynomial R).coeff 0 = n := begin induction n with n ih, { simp, }, { simp [ih], }, end @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} {R : Type*} [semiring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (λ p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end @[simp] lemma int_cast_coeff_zero {i : ℤ} {R : Type*} [ring R] : (i : polynomial R).coeff 0 = i := by cases i; simp @[simp, norm_cast] theorem int_cast_inj {m n : ℤ} {R : Type*} [ring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (λ p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end end cast end polynomial
eb50ab69f5c69627c8cc98e151815384b98b5c80
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/set/intervals/disjoint.lean
fa32b6c29e8fa6c757a4016e5620089bcc7f2eeb
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,726
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, Yury Kudryashov -/ import data.set.lattice /-! # Extra lemmas about intervals This file contains lemmas about intervals that cannot be included into `data.set.intervals.basic` because this would create an `import` cycle. Namely, lemmas in this file can use definitions from `data.set.lattice`, including `disjoint`. -/ universes u v w variables {ι : Sort u} {α : Type v} {β : Type w} open set order_dual (to_dual) namespace set section preorder variables [preorder α] {a b c : α} @[simp] lemma Iic_disjoint_Ioi (h : a ≤ b) : disjoint (Iic a) (Ioi b) := λ x ⟨ha, hb⟩, not_le_of_lt (h.trans_lt hb) ha @[simp] lemma Iic_disjoint_Ioc (h : a ≤ b) : disjoint (Iic a) (Ioc b c) := (Iic_disjoint_Ioi h).mono le_rfl (λ _, and.left) @[simp] lemma Ioc_disjoint_Ioc_same {a b c : α} : disjoint (Ioc a b) (Ioc b c) := (Iic_disjoint_Ioc (le_refl b)).mono (λ _, and.right) le_rfl @[simp] lemma Ico_disjoint_Ico_same {a b c : α} : disjoint (Ico a b) (Ico b c) := λ x hx, not_le_of_lt hx.1.2 hx.2.1 @[simp] lemma Ici_disjoint_Iic : disjoint (Ici a) (Iic b) ↔ ¬(a ≤ b) := by rw [set.disjoint_iff_inter_eq_empty, Ici_inter_Iic, Icc_eq_empty_iff] @[simp] lemma Iic_disjoint_Ici : disjoint (Iic a) (Ici b) ↔ ¬(b ≤ a) := disjoint.comm.trans Ici_disjoint_Iic @[simp] lemma Union_Iic : (⋃ a : α, Iic a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, right_mem_Iic⟩ @[simp] lemma Union_Ici : (⋃ a : α, Ici a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, left_mem_Ici⟩ @[simp] lemma Union_Icc_right (a : α) : (⋃ b, Icc a b) = Ici a := by simp only [← Ici_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Ioc_right (a : α) : (⋃ b, Ioc a b) = Ioi a := by simp only [← Ioi_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Icc_left (b : α) : (⋃ a, Icc a b) = Iic b := by simp only [← Ici_inter_Iic, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Ico_left (b : α) : (⋃ a, Ico a b) = Iio b := by simp only [← Ici_inter_Iio, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Iio [no_max_order α] : (⋃ a : α, Iio a) = univ := Union_eq_univ_iff.2 exists_gt @[simp] lemma Union_Ioi [no_min_order α] : (⋃ a : α, Ioi a) = univ := Union_eq_univ_iff.2 exists_lt @[simp] lemma Union_Ico_right [no_max_order α] (a : α) : (⋃ b, Ico a b) = Ici a := by simp only [← Ici_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioo_right [no_max_order α] (a : α) : (⋃ b, Ioo a b) = Ioi a := by simp only [← Ioi_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioc_left [no_min_order α] (b : α) : (⋃ a, Ioc a b) = Iic b := by simp only [← Ioi_inter_Iic, ← Union_inter, Union_Ioi, univ_inter] @[simp] lemma Union_Ioo_left [no_min_order α] (b : α) : (⋃ a, Ioo a b) = Iio b := by simp only [← Ioi_inter_Iio, ← Union_inter, Union_Ioi, univ_inter] end preorder section linear_order variables [linear_order α] {a₁ a₂ b₁ b₂ : α} @[simp] lemma Ico_disjoint_Ico : disjoint (Ico a₁ a₂) (Ico b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := by simp_rw [set.disjoint_iff_inter_eq_empty, Ico_inter_Ico, Ico_eq_empty_iff, inf_eq_min, sup_eq_max, not_lt] @[simp] lemma Ioc_disjoint_Ioc : disjoint (Ioc a₁ a₂) (Ioc b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := have h : _ ↔ min (to_dual a₁) (to_dual b₁) ≤ max (to_dual a₂) (to_dual b₂) := Ico_disjoint_Ico, by simpa only [dual_Ico] using h /-- If two half-open intervals are disjoint and the endpoint of one lies in the other, then it must be equal to the endpoint of the other. -/ lemma eq_of_Ico_disjoint {x₁ x₂ y₁ y₂ : α} (h : disjoint (Ico x₁ x₂) (Ico y₁ y₂)) (hx : x₁ < x₂) (h2 : x₂ ∈ Ico y₁ y₂) : y₁ = x₂ := begin rw [Ico_disjoint_Ico, min_eq_left (le_of_lt h2.2), le_max_iff] at h, apply le_antisymm h2.1, exact h.elim (λ h, absurd hx (not_lt_of_le h)) id end @[simp] lemma Union_Ico_eq_Iio_self_iff {f : ι → α} {a : α} : (⋃ i, Ico (f i) a) = Iio a ↔ ∀ x < a, ∃ i, f i ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma Union_Ioc_eq_Ioi_self_iff {f : ι → α} {a : α} : (⋃ i, Ioc a (f i)) = Ioi a ↔ ∀ x, a < x → ∃ i, x ≤ f i := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] @[simp] lemma bUnion_Ico_eq_Iio_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ico (f i hi) a) = Iio a ↔ ∀ x < a, ∃ i hi, f i hi ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma bUnion_Ioc_eq_Ioi_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ioc a (f i hi)) = Ioi a ↔ ∀ x, a < x → ∃ i hi, x ≤ f i hi := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] end linear_order end set section Union_Ixx variables [linear_order α] {s : set α} {a : α} {f : ι → α} lemma is_glb.bUnion_Ioi_eq (h : is_glb s a) : (⋃ x ∈ s, Ioi x) = Ioi a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ioi_subset_Ioi (h.1 hx) }, { rcases h.exists_between hx with ⟨y, hys, hay, hyx⟩, exact mem_bUnion hys hyx } end lemma is_glb.Union_Ioi_eq (h : is_glb (range f) a) : (⋃ x, Ioi (f x)) = Ioi a := bUnion_range.symm.trans h.bUnion_Ioi_eq lemma is_lub.bUnion_Iio_eq (h : is_lub s a) : (⋃ x ∈ s, Iio x) = Iio a := h.dual.bUnion_Ioi_eq lemma is_lub.Union_Iio_eq (h : is_lub (range f) a) : (⋃ x, Iio (f x)) = Iio a := h.dual.Union_Ioi_eq end Union_Ixx
53edf0fda8d0ba5b443882353300eca54a968cec
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/nat/cast.lean
e4d68dc4b3f9b9a9b76c5f0605bbcfe262917a21
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
3,738
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 0] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] @[simp] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, n > 0 → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] end nat
b650631c4260f2e84b692549f73977c7cff4444c
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/finset.lean
7ebab1aa0233bf1cc68861dcc8bc8739ff173c49
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
101,603
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (↑s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[elim_cast] lemma coe_nonempty {s : finset α} : (↑s:set α).nonempty ↔ s.nonempty := iff.rfl lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.of_subset hst hs /-! ### empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, nonempty_of_ne_empty⟩ theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = finset.singleton a ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = finset.singleton a) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := ext.2 $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left, imp_and_distrib, and_iff_left id] @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_sdiff_self_eq_union, union_comm] lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm] lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := by rw [subset_iff, ext]; simp @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ } lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem ↑s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem ↑s h end end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[elim_cast] lemma piecewise_coe [∀j, decidable (j ∈ (↑s : set α))] : (↑s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] @[simp] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by { simp [piecewise, h], congr } lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) := by {ext, simp [and_assoc], rw [and.left_comm] } theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter(eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, insert_empty_eq_singleton, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset /-! ### map -/ section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h @[simp] lemma card_map {α β} [decidable_eq β] (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := by rw [map_eq_image, card_image_of_injective]; exact f.2 lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from function.injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)⟩, subtype.ext.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card /-! ### bind -/ section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := by { ext x, simp, exact ⟨λ ⟨xt, y, ys, xf⟩, ⟨y, ys, xt, xf⟩, λ ⟨y, ys, xt, xf⟩, ⟨xt, y, ys, xf⟩⟩ } theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind /-! ### prod-/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma /-! ### pi -/ section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi /-! ### powerset -/ section powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] lemma powerset_empty [decidable_eq α] : finset.powerset (∅ : finset α) = {∅} := rfl @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by { apply mt _ h, apply mem_powerset.1 ht } lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := begin ext t, simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff], by_cases h : a ∈ t, { split, { exact λH, or.inr ⟨_, H, insert_erase h⟩ }, { intros H, cases H, { exact subset.trans (erase_subset a t) H }, { rcases H with ⟨u, hu⟩, rw ← hu.2, exact subset.trans (erase_insert_subset a u) hu.1 } } }, { have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t, by simp [ne.symm (ne_insert_of_not_mem _ _ h)], simp [finset.erase_eq_of_not_mem h, this] } end end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] lemma fold_op_rel_iff_and [decidable_eq α] {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or [decidable_eq α] {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha section order variables [decidable_eq α] [decidable_linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff end order end fold /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /-! ### max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption lemma exists_min (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := begin cases min_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩ end end max_min /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S.nonempty) : α := @option.get _ S.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S.nonempty) : α := @option.get _ S.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S.nonempty) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /-! ### intervals -/ /- Ico (a closed open interval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty (n : ℕ) : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff theorem subset_iff {m₁ n₁ m₂ n₂ : ℕ} (hmn : m₁ < n₁) : Ico m₁ n₁ ⊆ Ico m₂ n₂ ↔ (m₂ ≤ m₁ ∧ n₁ ≤ n₂) := begin simp only [subset_iff, mem], refine ⟨λ h, ⟨_, _⟩, _⟩, { exact (h ⟨le_refl _, hmn⟩).1 }, { refine le_of_pred_lt (@h (pred n₁) ⟨le_pred_of_lt hmn, pred_lt _⟩).2, exact ne_of_gt (lt_of_le_of_lt (nat.zero_le m₁) hmn) }, { rintros ⟨hm, hn⟩ k ⟨hmk, hkn⟩, exact ⟨le_trans hm hmk, lt_of_lt_of_le hkn hn⟩ } end protected theorem subset {m₁ n₁ m₂ n₂ : ℕ} (hmm : m₂ ≤ m₁) (hnn : n₁ ≤ n₂) : Ico m₁ n₁ ⊆ Ico m₂ n₂ := begin simp only [finset.subset_iff, Ico.mem], assume x hx, exact ⟨le_trans hmm hx.1, lt_of_lt_of_le hx.2 hnn⟩ end lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end lemma disjoint_consecutive (n m l : ℕ) : disjoint (Ico n m) (Ico m l) := le_of_eq $ inter_consecutive n m l @[simp] theorem succ_singleton (n : ℕ) : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem insert_succ_bot {n m : ℕ} (h : n < m) : insert n (Ico (n + 1) m) = Ico n m := by rw [eq_comm, ← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := eq_of_veq $ multiset.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := eq_of_veq $ multiset.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := eq_of_veq $ multiset.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_le n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico -- TODO We don't yet attempt to reproduce the entire interface for `Ico` for `Ico_ℤ`. /-- `Ico_ℤ l u` is the set of integers `l ≤ k < u`. -/ def Ico_ℤ (l u : ℤ) : finset ℤ := (finset.range (u - l).to_nat).map { to_fun := λ n, n + l, inj := λ n m h, by simpa using h } namespace Ico_ℤ @[simp] lemma mem {n m l : ℤ} : l ∈ Ico_ℤ n m ↔ n ≤ l ∧ l < m := begin dsimp [Ico_ℤ], simp only [int.lt_to_nat, exists_prop, mem_range, add_comm, function.embedding.coe_fn_mk, mem_map], split, { rintro ⟨a, ⟨h, rfl⟩⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨h₁, h₂⟩, use (l - n).to_nat, split; simp [h₁, h₂], } end end Ico_ℤ end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := (multiset.nat.antidiagonal n).to_finset /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n) /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl } end nat end finset namespace finset /-! ### bUnion -/ variables [decidable_eq α] @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton @[simp] theorem supr_union {α} [complete_lattice α] {β} [decidable_eq β] {f : β → α} {s t : finset β} : (⨆ 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 _ $ funext $ λ x, by { convert supr_or, rw finset.mem_union, rw finset.mem_union, refl, refl } ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq lemma bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw insert_eq, simp only [bUnion_union, finset.bUnion_singleton] end end finset
91d04ec1a02d170a749f5d701a113c129b1c7742
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/order/compact.lean
c2aa39290434e0c6f0f817f3567c87dab5fe0b94
[ "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
19,141
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Yury Kudryashov -/ import topology.algebra.order.intermediate_value import topology.local_extr /-! # Compactness of a closed interval In this file we prove that a closed interval in a conditionally complete linear ordered type with order topology (or a product of such types) is compact. We prove the extreme value theorem (`is_compact.exists_forall_le`, `is_compact.exists_forall_ge`): a continuous function on a compact set takes its minimum and maximum values. We provide many variations of this theorem. We also prove that the image of a closed interval under a continuous map is a closed interval, see `continuous_on.image_Icc`. ## Tags compact, extreme value theorem -/ open filter order_dual topological_space function set open_locale filter topological_space /-! ### Compactness of a closed interval In this section we define a typeclass `compact_Icc_space α` saying that all closed intervals in `α` are compact. Then we provide an instance for a `conditionally_complete_linear_order` and prove that the product (both `α × β` and an indexed product) of spaces with this property inherits the property. We also prove some simple lemmas about spaces with this property. -/ /-- This typeclass says that all closed intervals in `α` are compact. This is true for all conditionally complete linear orders with order topology and products (finite or infinite) of such spaces. -/ class compact_Icc_space (α : Type*) [topological_space α] [preorder α] : Prop := (is_compact_Icc : ∀ {a b : α}, is_compact (Icc a b)) export compact_Icc_space (is_compact_Icc) /-- A closed interval in a conditionally complete linear order is compact. -/ @[priority 100] instance conditionally_complete_linear_order.to_compact_Icc_space (α : Type*) [conditionally_complete_linear_order α] [topological_space α] [order_topology α] : compact_Icc_space α := begin refine ⟨λ a b, _⟩, cases le_or_lt a b with hab hab, swap, { simp [hab] }, refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _), contrapose! hf, rw [le_principal_iff], have hpt : ∀ x ∈ Icc a b, {x} ∉ f, from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)), set s := {x ∈ Icc a b | Icc a x ∉ f}, have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2, have sbd : bdd_above s, from ⟨b, hsb⟩, have ha : a ∈ s, by simp [hpt, hab], rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 }, set c := Sup s, have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd, have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩, specialize hf c hc, have hcs : c ∈ s, { cases hc.1.eq_or_lt with heq hlt, { rwa ← heq }, refine ⟨hc, λ hcf, hf (λ U hU, _)⟩, rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU) with ⟨x, hxc, hxU⟩, rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually (Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists with ⟨y, ⟨hyab, hyf⟩, hy⟩, refine mem_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU), rw diff_subset_iff, exact subset.trans Icc_subset_Icc_union_Ioc (union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) }, cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 }, contrapose! hf, intros U hU, rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU) with ⟨y, hxy, hyU⟩, refine mem_of_superset _ hyU, clear_dependent U, have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩, by_cases hay : Icc a y ∈ f, { refine mem_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _, rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff], exact Icc_subset_Icc_union_Icc }, { exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim }, end instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, compact_Icc_space (α i)] : compact_Icc_space (Π i, α i) := ⟨λ a b, pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc⟩ instance pi.compact_Icc_space' {α β : Type*} [preorder β] [topological_space β] [compact_Icc_space β] : compact_Icc_space (α → β) := pi.compact_Icc_space instance {α β : Type*} [preorder α] [topological_space α] [compact_Icc_space α] [preorder β] [topological_space β] [compact_Icc_space β] : compact_Icc_space (α × β) := ⟨λ a b, (Icc_prod_eq a b).symm ▸ is_compact_Icc.prod is_compact_Icc⟩ /-- An unordered closed interval is compact. -/ lemma is_compact_uIcc {α : Type*} [linear_order α] [topological_space α] [compact_Icc_space α] {a b : α} : is_compact (uIcc a b) := is_compact_Icc /-- A complete linear order is a compact space. We do not register an instance for a `[compact_Icc_space α]` because this would only add instances for products (indexed or not) of complete linear orders, and we have instances with higher priority that cover these cases. -/ @[priority 100] -- See note [lower instance priority] instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α] [topological_space α] [order_topology α] : compact_space α := ⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩ section variables {α : Type*} [preorder α] [topological_space α] [compact_Icc_space α] instance compact_space_Icc (a b : α) : compact_space (Icc a b) := is_compact_iff_compact_space.mp is_compact_Icc end /-! ### Min and max elements of a compact set -/ variables {α β γ : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [topological_space β] [topological_space γ] lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Inf s ∈ s := hs.is_closed.cInf_mem ne_s hs.bdd_below lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s := @is_compact.Inf_mem αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_glb s (Inf s) := is_glb_cInf ne_s hs.bdd_below lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_lub s (Sup s) := @is_compact.is_glb_Inf αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_least s (Inf s) := ⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩ lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_greatest s (Sup s) := @is_compact.is_least_Inf αᵒᵈ _ _ _ _ hs ne_s lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_least s x := ⟨_, hs.is_least_Inf ne_s⟩ lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_greatest s x := ⟨_, hs.is_greatest_Sup ne_s⟩ lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_glb s x := ⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩ lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_lub s x := ⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩ lemma is_compact.exists_Inf_image_eq_and_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x ∧ ∀ y ∈ s, f x ≤ f y := let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f) in ⟨x, hxs, hx.symm, λ y hy, hx.trans_le $ cInf_le (hs.image_of_continuous_on hf).bdd_below $ mem_image_of_mem f hy⟩ lemma is_compact.exists_Sup_image_eq_and_ge {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Sup (f '' s) = f x ∧ ∀ y ∈ s, f y ≤ f x := @is_compact.exists_Inf_image_eq_and_le αᵒᵈ _ _ _ _ _ _ hs ne_s _ hf lemma is_compact.exists_Inf_image_eq {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x := let ⟨x, hxs, hx, _⟩ := hs.exists_Inf_image_eq_and_le ne_s hf in ⟨x, hxs, hx⟩ lemma is_compact.exists_Sup_image_eq : ∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s → ∃ x ∈ s, Sup (f '' s) = f x := @is_compact.exists_Inf_image_eq αᵒᵈ _ _ _ _ _ lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) : s = Icc (Inf s) (Sup s) := eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed /-! ### Extreme value theorem -/ /-- The **extreme value theorem**: a continuous function realizes its minimum on a compact set. -/ lemma is_compact.exists_forall_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty) {f : β → α} (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin rcases (hs.image_of_continuous_on hf).exists_is_least (ne_s.image f) with ⟨_, ⟨x, hxs, rfl⟩, hx⟩, exact ⟨x, hxs, ball_image_iff.1 hx⟩ end /-- The **extreme value theorem**: a continuous function realizes its maximum on a compact set. -/ lemma is_compact.exists_forall_ge : ∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @is_compact.exists_forall_le αᵒᵈ _ _ _ _ _ /-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is larger than a value in its image away from compact sets, then it has a minimum on this set. -/ lemma continuous_on.exists_forall_le' {s : set β} {f : β → α} (hf : continuous_on f s) (hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x₀ ≤ f x) : ∃ x ∈ s, ∀ y ∈ s, f x ≤ f y := begin rcases (has_basis_cocompact.inf_principal _).eventually_iff.1 hc with ⟨K, hK, hKf⟩, have hsub : insert x₀ (K ∩ s) ⊆ s, from insert_subset.2 ⟨h₀, inter_subset_right _ _⟩, obtain ⟨x, hx, hxf⟩ : ∃ x ∈ insert x₀ (K ∩ s), ∀ y ∈ insert x₀ (K ∩ s), f x ≤ f y := ((hK.inter_right hsc).insert x₀).exists_forall_le (insert_nonempty _ _) (hf.mono hsub), refine ⟨x, hsub hx, λ y hy, _⟩, by_cases hyK : y ∈ K, exacts [hxf _ (or.inr ⟨hyK, hy⟩), (hxf _ (or.inl rfl)).trans (hKf ⟨hyK, hy⟩)] end /-- The **extreme value theorem**: if a function `f` is continuous on a closed set `s` and it is smaller than a value in its image away from compact sets, then it has a maximum on this set. -/ lemma continuous_on.exists_forall_ge' {s : set β} {f : β → α} (hf : continuous_on f s) (hsc : is_closed s) {x₀ : β} (h₀ : x₀ ∈ s) (hc : ∀ᶠ x in cocompact β ⊓ 𝓟 s, f x ≤ f x₀) : ∃ x ∈ s, ∀ y ∈ s, f y ≤ f x := @continuous_on.exists_forall_le' αᵒᵈ _ _ _ _ _ _ _ hf hsc _ h₀ hc /-- The **extreme value theorem**: if a continuous function `f` is larger than a value in its range away from compact sets, then it has a global minimum. -/ lemma _root_.continuous.exists_forall_le' {f : β → α} (hf : continuous f) (x₀ : β) (h : ∀ᶠ x in cocompact β, f x₀ ≤ f x) : ∃ (x : β), ∀ (y : β), f x ≤ f y := let ⟨x, _, hx⟩ := hf.continuous_on.exists_forall_le' is_closed_univ (mem_univ x₀) (by rwa [principal_univ, inf_top_eq]) in ⟨x, λ y, hx y (mem_univ y)⟩ /-- The **extreme value theorem**: if a continuous function `f` is smaller than a value in its range away from compact sets, then it has a global maximum. -/ lemma _root_.continuous.exists_forall_ge' {f : β → α} (hf : continuous f) (x₀ : β) (h : ∀ᶠ x in cocompact β, f x ≤ f x₀) : ∃ (x : β), ∀ (y : β), f y ≤ f x := @continuous.exists_forall_le' αᵒᵈ _ _ _ _ _ _ hf x₀ h /-- The **extreme value theorem**: if a continuous function `f` tends to infinity away from compact sets, then it has a global minimum. -/ lemma _root_.continuous.exists_forall_le [nonempty β] {f : β → α} (hf : continuous f) (hlim : tendsto f (cocompact β) at_top) : ∃ x, ∀ y, f x ≤ f y := by { inhabit β, exact hf.exists_forall_le' default (hlim.eventually $ eventually_ge_at_top _) } /-- The **extreme value theorem**: if a continuous function `f` tends to negative infinity away from compact sets, then it has a global maximum. -/ lemma continuous.exists_forall_ge [nonempty β] {f : β → α} (hf : continuous f) (hlim : tendsto f (cocompact β) at_bot) : ∃ x, ∀ y, f y ≤ f x := @continuous.exists_forall_le αᵒᵈ _ _ _ _ _ _ _ hf hlim lemma is_compact.Sup_lt_iff_of_continuous {f : β → α} {K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) : Sup (f '' K) < y ↔ ∀ x ∈ K, f x < y := begin refine ⟨λ h x hx, (le_cSup (hK.bdd_above_image hf) $ mem_image_of_mem f hx).trans_lt h, λ h, _⟩, obtain ⟨x, hx, h2x⟩ := hK.exists_forall_ge h0K hf, refine (cSup_le (h0K.image f) _).trans_lt (h x hx), rintro _ ⟨x', hx', rfl⟩, exact h2x x' hx' end lemma is_compact.lt_Inf_iff_of_continuous {α β : Type*} [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [topological_space β] {f : β → α} {K : set β} (hK : is_compact K) (h0K : K.nonempty) (hf : continuous_on f K) (y : α) : y < Inf (f '' K) ↔ ∀ x ∈ K, y < f x := @is_compact.Sup_lt_iff_of_continuous αᵒᵈ β _ _ _ _ _ _ hK h0K hf y /-- A continuous function with compact support has a global minimum. -/ @[to_additive "A continuous function with compact support has a global minimum."] lemma continuous.exists_forall_le_of_has_compact_mul_support [nonempty β] [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : ∃ (x : β), ∀ (y : β), f x ≤ f y := begin obtain ⟨_, ⟨x, rfl⟩, hx⟩ := (h.is_compact_range hf).exists_is_least (range_nonempty _), rw [mem_lower_bounds, forall_range_iff] at hx, exact ⟨x, hx⟩, end /-- A continuous function with compact support has a global maximum. -/ @[to_additive "A continuous function with compact support has a global maximum."] lemma continuous.exists_forall_ge_of_has_compact_mul_support [nonempty β] [has_one α] {f : β → α} (hf : continuous f) (h : has_compact_mul_support f) : ∃ (x : β), ∀ (y : β), f y ≤ f x := @continuous.exists_forall_le_of_has_compact_mul_support αᵒᵈ _ _ _ _ _ _ _ _ hf h lemma is_compact.continuous_Sup {f : γ → β → α} {K : set β} (hK : is_compact K) (hf : continuous ↿f) : continuous (λ x, Sup (f x '' K)) := begin rcases eq_empty_or_nonempty K with rfl|h0K, { simp_rw [image_empty], exact continuous_const }, rw [continuous_iff_continuous_at], intro x, obtain ⟨y, hyK, h2y, hy⟩ := hK.exists_Sup_image_eq_and_ge h0K (show continuous (λ y, f x y), from hf.comp $ continuous.prod.mk x).continuous_on, rw [continuous_at, h2y, tendsto_order], have := tendsto_order.mp ((show continuous (λ x, f x y), from hf.comp $ continuous_id.prod_mk continuous_const).tendsto x), refine ⟨λ z hz, _, λ z hz, _⟩, { refine (this.1 z hz).mono (λ x' hx', hx'.trans_le $ le_cSup _ $ mem_image_of_mem (f x') hyK), exact hK.bdd_above_image (hf.comp $ continuous.prod.mk x').continuous_on }, { have h : ({x} : set γ) ×ˢ K ⊆ ↿f ⁻¹' (Iio z), { rintro ⟨x', y'⟩ ⟨hx', hy'⟩, cases hx', exact (hy y' hy').trans_lt hz }, obtain ⟨u, v, hu, hv, hxu, hKv, huv⟩ := generalized_tube_lemma is_compact_singleton hK (is_open_Iio.preimage hf) h, refine eventually_of_mem (hu.mem_nhds (singleton_subset_iff.mp hxu)) (λ x' hx', _), rw [hK.Sup_lt_iff_of_continuous h0K (show continuous (f x'), from (hf.comp $ continuous.prod.mk x')).continuous_on], exact λ y' hy', huv (mk_mem_prod hx' (hKv hy')) } end lemma is_compact.continuous_Inf {f : γ → β → α} {K : set β} (hK : is_compact K) (hf : continuous ↿f) : continuous (λ x, Inf (f x '' K)) := @is_compact.continuous_Sup αᵒᵈ β γ _ _ _ _ _ _ _ hK hf namespace continuous_on /-! ### Image of a closed interval -/ variables [densely_ordered α] [conditionally_complete_linear_order β] [order_topology β] {f : α → β} {a b c : α} open_locale interval lemma image_Icc (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (is_compact_Icc.image_of_continuous_on h) lemma image_uIcc_eq_Icc (h : continuous_on f $ [a, b]) : f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) := begin cases le_total a b with h2 h2, { simp_rw [uIcc_of_le h2] at h ⊢, exact h.image_Icc h2 }, { simp_rw [uIcc_of_ge h2] at h ⊢, exact h.image_Icc h2 }, end lemma image_uIcc (h : continuous_on f $ [a, b]) : f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] := begin refine h.image_uIcc_eq_Icc.trans (uIcc_of_le _).symm, refine cInf_le_cSup _ _ (nonempty_uIcc.image _); rw h.image_uIcc_eq_Icc, exacts [bdd_below_Icc, bdd_above_Icc] end lemma Inf_image_Icc_le (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) : Inf (f '' (Icc a b)) ≤ f c := begin rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)), exact cInf_le bdd_below_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩, le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩), end lemma le_Sup_image_Icc (h : continuous_on f $ Icc a b) (hc : c ∈ Icc a b) : f c ≤ Sup (f '' (Icc a b)) := begin rw h.image_Icc (nonempty_Icc.mp (set.nonempty_of_mem hc)), exact le_cSup bdd_above_Icc (mem_Icc.mpr ⟨cInf_le (is_compact_Icc.bdd_below_image h) ⟨c, hc, rfl⟩, le_cSup (is_compact_Icc.bdd_above_image h) ⟨c, hc, rfl⟩⟩), end end continuous_on lemma is_compact.exists_local_min_on_mem_subset {f : β → α} {s t : set β} {z : β} (ht : is_compact t) (hf : continuous_on f t) (hz : z ∈ t) (hfz : ∀ z' ∈ t \ s, f z < f z') : ∃ x ∈ s, is_local_min_on f t x := begin obtain ⟨x, hx, hfx⟩ : ∃ x ∈ t, ∀ y ∈ t, f x ≤ f y := ht.exists_forall_le ⟨z, hz⟩ hf, have key : ∀ ⦃y⦄, y ∈ t → (∀ z' ∈ t \ s, f y < f z') → y ∈ s := λ y hy hfy, by { by_contra; simpa using ((hfy y ((mem_diff y).mpr ⟨hy,h⟩))) }, have h1 : ∀ z' ∈ t \ s, f x < f z' := λ z' hz', (hfx z hz).trans_lt (hfz z' hz'), have h2 : x ∈ s := key hx h1, refine ⟨x, h2, eventually_nhds_within_of_forall hfx⟩ end lemma is_compact.exists_local_min_mem_open {f : β → α} {s t : set β} {z : β} (ht : is_compact t) (hst : s ⊆ t) (hf : continuous_on f t) (hz : z ∈ t) (hfz : ∀ z' ∈ t \ s, f z < f z') (hs : is_open s) : ∃ x ∈ s, is_local_min f x := begin obtain ⟨x, hx, hfx⟩ := ht.exists_local_min_on_mem_subset hf hz hfz, exact ⟨x, hx, hfx.is_local_min (filter.mem_of_superset (hs.mem_nhds hx) hst)⟩ end
1f8fd4492200edb5272c049ad0aad01839d2b26b
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/sec_param_pp.lean
bb7555f718e043db90591e85ecdbd854146cdb69
[ "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
281
lean
section parameters {A : Type*} (a : A) variable f : A → A → A definition id2 : A := a #check id2 definition pr (b : A) : A := f a b #check pr f id2 set_option pp.universes true #check pr f id2 definition pr2 (B : Type*) (b : B) : A := a #check pr2 num 10 end
f5cadb6a3d4b656908af1c4c1fd83840a7ae5ed9
675b8263050a5d74b89ceab381ac81ce70535688
/src/measure_theory/measurable_space.lean
4378d8ab74df1103e8e9bed9384cfaea93eb41f0
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,109
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import order.filter.basic /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function, measurable equivalence, dynkin system, π-λ theorem, π-system -/ open set encodable function open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀ s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀ f : ℕ → set α, (∀ i, is_measurable' (f i)) → is_measurable' (⋃ i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma set.finite.is_measurable_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := is_measurable.bUnion hs.countable h lemma finset.is_measurable_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := s.finite_to_set.is_measurable_bUnion h lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma set.finite.is_measurable_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := is_measurable.sUnion hs.countable h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.is_measurable_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.bInter hs.countable h lemma finset.is_measurable_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := s.finite_to_set.is_measurable_bInter h lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma set.finite.is_measurable_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := is_measurable.sInter hs.countable h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀ i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_is_measurable [measurable_space α] : generate_from {s : set α | is_measurable s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, is_measurable_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λ s, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λ s, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @is_measurable_empty _ ⊥) (λ s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂ m ∈ ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λ m, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @is_measurable _ m s} s := begin change @is_measurable' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @is_measurable _ (m i) s} s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λ s, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λ s, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃ i, s' i, m.is_measurable_Union _ (λ i, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥ : measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} : (⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤ : measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ t ∈ s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma subsingleton.measurable [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable.piecewise {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ lemma measurable.ite {p : α → Prop} {_ : decidable_pred p} {f g : α → β} (hp : is_measurable {a : α | p a}) (hf : measurable f) (hg : measurable g) : measurable (λ x, ite (p x) (f x) (g x)) := measurable.piecewise hp hf hg @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, is_measurable.const (a ∈ s) lemma measurable.indicator [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one [has_one α] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 end measurable_functions section constructions variables [measurable_space α] [measurable_space β] [measurable_space γ] instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit (f : unit → α) : measurable f := measurable_from_top section nat lemma measurable_from_nat {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {α} {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λ a : α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λ a : s, f a)) (hd : measurable (λ a : t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λ a, (f a).1)) (hf₂ : measurable (λ a, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λ a, (f a).1) ∧ measurable (λ a, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi variables {π : δ → Type*} instance measurable_space.pi [m : Π a, measurable_space (π a)] : measurable_space (Π a, π a) := ⨆ a, (m a).comap (λ b, b a) variables [Π a, measurable_space (π a)] [measurable_space γ] lemma measurable_pi_apply (a : δ) : measurable (λ f : Π a, π a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable_pi_lambda (f : α → Π a, π a) (hf : ∀ a, measurable (λ c, f c a)) : measurable f := measurable.of_le_map $ supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) lemma is_measurable_pi {s : set δ} {t : Π i : δ, set (π i)} (hs : countable s) (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (s.pi t) := begin rw [pi_def], exact is_measurable.bInter hs (λ i hi, measurable_pi_apply _ (ht i hi)) end end pi instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_elim {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {α} {β : α → Type*} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) infix ` ≃ᵐ `:25 := measurable_equiv namespace measurable_equiv variables (α β) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] instance : has_coe_to_fun (α ≃ᵐ β) := ⟨λ _, α → β, λ e, e.to_equiv⟩ variables {α β} lemma coe_eq (e : α ≃ᵐ β) : (e : α → β) = e.to_equiv := rfl protected lemma measurable (e : α ≃ᵐ β) : measurable (e : α → β) := e.measurable_to_fun /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : α ≃ᵐ α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance : inhabited (α ≃ᵐ α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ @[simps] def trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } /-- The inverse of an equivalence between measurable spaces. -/ @[simps] def symm (ab : α ≃ᵐ β) : β ≃ᵐ α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : α ≃ᵐ β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable_coe_iff {f : β → γ} (e : α ≃ᵐ β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λ h, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := (ab.measurable_to_fun.comp measurable_id.fst).prod_mk (cd.measurable_to_fun.comp measurable_id.snd), measurable_inv_fun := (ab.measurable_inv_fun.comp measurable_id.fst).prod_mk (cd.measurable_inv_fun.comp measurable_id.snd) } /-- Products of measurable spaces are symmetric. -/ def prod_comm : α × β ≃ᵐ β × α := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable_id.snd.prod_mk measurable_id.fst, measurable_inv_fun := measurable_id.snd.prod_mk measurable_id.fst } /-- Products of measurable spaces are associative. -/ def prod_assoc : (α × β) × γ ≃ᵐ α × (β × γ) := { to_equiv := equiv.prod_assoc α β γ, measurable_to_fun := measurable_fst.fst.prod_mk $ measurable_fst.snd.prod_mk measurable_snd, measurable_inv_fun := (measurable_fst.prod_mk measurable_snd.fst).prod_mk measurable_snd.snd } /-- Sums of measurable spaces are symmetric. -/ def sum_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod (s : set α) (t : set β) : s.prod t ≃ᵐ s × t := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable_id.subtype_coe.fst.subtype_mk.prod_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable_id.fst.subtype_coe.prod_mk measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : (univ : set α) ≃ᵐ α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton (a : α) : ({a} : set α) ≃ᵐ unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image (f : α → β) (s : set α) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : s ≃ᵐ (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, equiv.set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range (f : α → β) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : α ≃ᵐ (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl : (range sum.inl : set (α ⊕ β)) ≃ᵐ α := { to_fun := λ ab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ a, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr : (range sum.inr : set (α ⊕ β)) ≃ᵐ β := { to_fun := λ ab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ b, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : (α ⊕ β) × γ ≃ᵐ (α × γ) ⊕ (β × γ) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp measurable_fst).prod_mk measurable_snd) ((measurable_inr.comp measurable_fst).prod_mk measurable_snd) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : α × (β ⊕ γ) ≃ᵐ (α × β) ⊕ (α × γ) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ ((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ)) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_is_measurable [measurable_space α] : is_pi_system {s : set α | is_measurable s} := λ s t hs ht _, hs.inter ht /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀ n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃ n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, is_measurable t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, is_measurable (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning (C : set (set α)) : Prop := ∃ (s : ℕ → set α), (∀ n, s n ∈ C) ∧ (⋃ n, s n) = univ lemma is_countably_spanning_is_measurable [measurable_space α] : is_countably_spanning {s : set α | is_measurable s} := ⟨λ _, univ, λ _, is_measurable.univ, Union_const _⟩
9e4899ba70e32daac66c93e983ebc4666c23ca0e
618003631150032a5676f229d13a079ac875ff77
/src/tactic/monotonicity/interactive.lean
fba1aae0844c8931b0b4d0e93d23f74e8bfe95b1
[ "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
23,491
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity.basic import control.traversable import control.traversable.derive import data.dlist variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function | assoc_comm : expr elab → expr elab → mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function → tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr → expr → expr → tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr → tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr → tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr → list expr → tactic (list expr × list expr × list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (unif : bool) (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr → list expr → tactic (list expr × list expr × list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr × list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse l₂,reverse r₂,reverse suf) meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr → option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr → list expr → expr → expr → tactic (expr × list expr × list expr) | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) := same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁ | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁) meta def same_function : expr → expr → tactic (expr × list expr × list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr × expr × list expr × mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac tt <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ ¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- ¬ a (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs, return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx) | `(%%e₀ → %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%e₀ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel e₀) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr → expr → expr | none e := e | (some e₀) e₁ := f.mk_app [e₀,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr → option expr → expr | e none := e | e₀ (some e₁) := f.mk_app [e₀,e₁] meta def mk_fun_app : mono_function → expr → expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove x+(y₀+z) R x+(y₁+z); if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/ | assoc : expr × expr → expr × expr → mono_law /- `congr r` gives the rule to prove `x = y → f x = f y` -/ | congr : expr → mono_law | other : expr → mono_law meta def mono_law.to_tactic_format : mono_law → tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := do x₀ ← pp x₀, x₁ ← pp x₁, y₀ ← pp y₀, y₁ ← pp y₁, return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f x₀ x₁) := if (x₀ <|> x₁).is_some then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (λ i, bin_op f x (bin_op f i y)) , mk_rel ctx (λ i, bin_op f i y)) ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y) , mk_rel ctx (λ i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name → tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ → %%x₀), r₀ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> r₀ <*> r₁) meta def find_rule (ls : list name) : mono_law → tactic (list expr) | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := (match_chaining_rules ls x₀ x₁) <|> (match_chaining_rules ls y₀ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (λ v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ λ _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {α β} [decidable_linear_order β] (f : α → β) : list α → list α | [] := [] | (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit := do t ← target, xs ← xs.mmap (λ x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (λ ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" (list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg)), let msg := foldl compose "" lmms, fail format!"ambiguous match: {msg}\n\nTip: try asserting a side condition to distinguish between the lemmas" end meta def mono_aux (dir : parse side) (cfg : mono_cfg := { mono_cfg . }) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≤ w` and `y < z` or - right: `x < w` and `y ≤ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg? To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊢ k + 3 + x ≤ k + 4 + x mono, -- apply add_le_add, refl -- ⊢ k + 3 ≤ k + 4 mono }, { -- ⊢ -y ≤ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) (cfg : mono_cfg := { mono_cfg . }) : tactic unit := do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var), hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr), when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none])), if many.is_some then repeat $ mono_aux dir cfg else mono_aux dir cfg, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ λ asms, do try `[dunfold has_sub.sub algebra.sub int.sub], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (λ rule, do t₀ ← mk_meta_var `(Prop), v₀ ← mk_meta_var t₀, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁), solve_mvar v₀ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit → tactic unit → tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : ℕ) | many meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly' n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := rep_arity.many <$ tk "*" <|> rep_arity.exactly <$> (tk "^" *> small_nat) <|> pure rep_arity.one /-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a monotonic function `f` to `x ≺ y`. `ac_mono*` unwraps monotonic functions until it can't. `ac_mono^k`, for some literal number `k` applies monotonicity `k` times. `ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and uses `h` to solve the remaining goal. Can be combined with `*` or `^k`: `ac_mono* h` `ac_mono : p` asserts `p` and uses it to discharge the goal result unwrapping a series of monotonic functions. Can be combined with * or ^k: `ac_mono* : p` In the case where `f` is an associative or commutative operator, `ac_mono` will consider any possible permutation of its arguments and use the one the minimizes the difference between the left-hand side and the right-hand side. To use it, first import `tactic.monotonicity`. `ac_mono` can be used as follows: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end ``` As with `mono*`, `ac_mono*` solves the goal in one go and so does `ac_mono* h₁`. The latter syntax becomes especially interesting in the following example: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by ac_mono* h₁. ``` By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to stop earlier than it would normally would. -/ meta def ac_mono (rep : parse arity) : parse assert_or_rule? → opt_param mono_cfg { mono_cfg . } → tactic unit | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none | (some (inl h)) opt := do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine) | (some (inr t)) opt := do h ← i_to_expr t >>= assert `h, tactic.swap, focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h) /- TODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining gaol if the provided rule does not solve it completely. -/ add_tactic_doc { name := "ac_mono", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_mono], tags := ["monotonicity"] } attribute [mono] and.imp or.imp end tactic.interactive
65cf814f8c7632621fef69fb184011edb6ed1894
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world5/level1.lean
d5c1c51aa0ce80ce7f5140cbb7b17391550c14d3
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
1,302
lean
import category_theory.category.default import category_theory.functor import category_theory.isomorphism universes v₁ v₂ u₁ u₂ -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] /- # Naturality world ## Level 1: Definition of natural transformation Given categories `C` and `D` and functors `F G : C ⥤ D`, a natural transformation α consists of * an arrow `α.app X : F.obj X ⟶ G.obj X` for each object `X` in `C`. In other words, a functor consists of a mapping on objects and a mapping on morphisms that preserves all of the structure of a category, namely domains and codomains, composition, and identities. -/ /- Axiom : F.map f ≫ F.map g = F.map (f ≫ g)-/ /- Axiom: F.map (𝟙 X) : 𝟙 (F.obj X)-/ /-- A functor `F : C ⥤ D` sends isomorphisms `i : X ≅ Y` to isomorphisms `F.obj X ≅ F.obj Y` -/ def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } end category_theory
d9d4a2df45e43c2d7cc48424c01525576b595837
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/evalWithMVar.lean
e6795fa5495351e18c94243291f29960efb795b6
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
263
lean
new_frontend def c {α} : Sum α Nat := Sum.inr 10 def Sum.someRight {α β} (s : Sum α β) : Option β := match s with | Sum.inl _ => none | Sum.inr b => some b #check Sum.someRight c #eval Sum.someRight c #check Sum.someRight (s := c) #check c.someRight
e1905fdc846f22fa7e748a35bf86b0f55d6d62e7
b29f946a2f0afd23ef86b9219116968babbb9f4f
/src/limsup.lean
532ce749a2a80dcf889bee8a354c56f38d22eebb
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1P1-lean
58be7394fded719d95e45e6b10e1ecf2ed3c7c4c
3723468cc50f8bebd00a9811caf25224a578de17
refs/heads/master
1,587,063,867,779
1,572,727,164,000
1,572,727,164,000
165,845,802
14
4
Apache-2.0
1,549,730,698,000
1,547,554,675,000
Lean
UTF-8
Lean
false
false
1,704
lean
-- amazing theory of limsups import limits namespace M1P1 /- Section Sequences, subsequences, and monotonic subsequences. -/ /- Sub-section Definitions -/ /- We model a sequence $a₀, a₁, a₂, \dots$ of real numbers as a function from $ℕ := \{0,1,2,\dots\}$ to $ℝ$, sending $n$ to $a_n$. We sometimes write such a sequence as $(a_n)_{n≥0}$ or just $(a_n)$. -/ /- Definition A sequence $(a_n)$ is *increasing* if forall $n∈ℕ$ we have $a_n≤a_{n+1}$. Note that equality is allowed here -- so for example the sequence $3, 3, 3, 3, …$ is increasing. A sequence is *strictly increasing* if for all $n∈ℕ$ we have $a_n<a_{n+1}$; constant sequences are not strictly increasing. -/ def is_increasing {X : Type*} [has_le X] (a : ℕ → X) : Prop := ∀ n : ℕ, a n ≤ a (n + 1) def is_strictly_increasing {X : Type*} [has_lt X] (a : ℕ → X) : Prop := ∀ n : ℕ, a n < a (n + 1) /- Definition Similarly a sequence $(a_n)$ is *decreasing* if $∀ n∈ℕ, a_{n+1}≤ a_n$ and is *strictly decreasing* if $∀ n∈ℕ, a_{n+1}<a_n$. -/ def is_decreasing {X : Type*} [has_le X] (a : ℕ → X) : Prop := ∀ n : ℕ, a (n + 1) ≤ a n def is_strictly_decreasing {X : Type*} [has_lt X] (a : ℕ → X) : Prop := ∀ n : ℕ, a (n + 1) < a n /- A *subsequence* of a sequence $(a_n)$ is a sequence $(b_m)$ of the form $a_{k_0}$, $a_{k_1}$, $a_{k_2}$, where the indices $0≤ k_0<k_1<k_2<…$ are strictly increasing. -/ def is_subsequence {X : Type*} (a : ℕ → X) (b : ℕ → X) := ∃ k : ℕ → ℕ, is_strictly_increasing k ∧ ∀ n, a (k n) = b n definition is_limit_point (a : ℕ → ℝ) (l : ℝ) := ∃ (b : ℕ → ℝ), is_subsequence a b ∧ is_limit b l end M1P1
1cee9147634cb36014835f698feccc6b2c82b541
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Elab/Exception.lean
5487038638558921f8ee463fb28618052a1d4f71
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,906
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.InternalExceptionId import Lean.Meta.Exception namespace Lean namespace Elab def registerPostponeId : IO InternalExceptionId := registerInternalExceptionId `postpone @[init registerPostponeId] constant postponeExceptionId : InternalExceptionId := arbitrary _ def registerUnsupportedSyntaxId : IO InternalExceptionId := registerInternalExceptionId `unsupportedSyntax @[init registerUnsupportedSyntaxId] constant unsupportedSyntaxExceptionId : InternalExceptionId := arbitrary _ def registerAbortElabId : IO InternalExceptionId := registerInternalExceptionId `abortElab @[init registerAbortElabId] constant abortExceptionId : InternalExceptionId := arbitrary _ def throwPostpone {α m} [MonadExceptOf Exception m] : m α := throw $ Exception.internal postponeExceptionId def throwUnsupportedSyntax {α m} [MonadExceptOf Exception m] : m α := throw $ Exception.internal unsupportedSyntaxExceptionId def throwIllFormedSyntax {α m} [Monad m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] : m α := throwError "ill-formed syntax" def throwAlreadyDeclaredUniverseLevel {α m} [Monad m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] (u : Name) : m α := throwError ("a universe level named '" ++ toString u ++ "' has already been declared") -- Throw exception to abort elaboration without producing any error message def throwAbort {α m} [MonadExcept Exception m] : m α := throw $ Exception.internal abortExceptionId def mkMessageCore (fileName : String) (fileMap : FileMap) (msgData : MessageData) (severity : MessageSeverity) (pos : String.Pos) : Message := let pos := fileMap.toPosition pos; { fileName := fileName, pos := pos, data := msgData, severity := severity } end Elab end Lean
c550426fa9bb84814518647a3c9a0297001ff1b9
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/bench/rbmap_checkpoint.lean
be612f81babba356ade37b3e80625b5aca22a5f4
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
3,325
lean
/- Copyright (c) 2017 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.ordering.basic init.coe init.data.option.basic init.io universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree instance : Inhabited Tree := ⟨Tree.Leaf⟩ variables {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf b := b | (Node _ l k v r) b := fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv vv t (Node _ (Node Red l kx vx r₁) ky vy r₂) := Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv vv t (Node _ l₁ ky vy (Node Red l₂ kx vx r)) := Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv vv t (Node _ l ky vy r) := Node Black (Node Red l ky vy r) kv vv t | _ _ _ _ := Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t kv vv (Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂) := Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t kv vv (Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂)) := Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t kv vv (Node _ l ky vy r) := Node Black t kv vv (Node Red l ky vy r) | _ _ _ _ := Leaf def isRed : Tree → Bool | (Node Red _ _ _ _) := true | _ := false def ins : Tree → Nat → Bool → Tree | Leaf kx vx := Node Red Leaf kx vx Leaf | (Node Red a ky vy b) kx vx := (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | (Node Black a ky vy b) kx vx := if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | (Node _ l k v r) := Node Black l k v r | e := e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux (freq : Nat) : Nat → Tree → List Tree → List Tree | 0 m r := m::r | (n+1) m r := let m := insert m n (n % 10 = 0); let r := if n % freq == 0 then m::r else r; mkMapAux n m r def mkMap (n : Nat) (freq : Nat) : List Tree := mkMapAux freq n Leaf [] def myLen : List Tree → Nat → Nat | (Node _ _ _ _ _ :: xs) r := myLen xs (r + 1) | (_ :: xs) r := myLen xs r | [] r := r def main (xs : List String) : IO UInt32 := do [n, freq] ← pure xs | throw "invalid input"; let n := n.toNat; let freq := freq.toNat; let freq := if freq == 0 then 1 else freq; let mList := mkMap n freq; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) mList.head 0; IO.println (toString (myLen mList 0) ++ " " ++ toString v) *> pure 0
2bc8d352e6d4efdbb75f9e570dcec4c8d5e72d7a
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/number_theory/pythagorean_triples.lean
f2a311b5b8db582f199e8f760dbdfee5375d9f29
[ "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
23,774
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Paul van Wamelen. -/ import algebra.field import algebra.gcd_domain import algebra.group_with_zero_power import tactic /-! # Pythagorean Triples The main result is the classification of pythagorean triples. The final result is for general pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := begin by_cases hk : k = 0, { simp only [pythagorean_triple, hk, zero_mul, zero_add], }, { calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring } end omit h lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A pythogorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `(x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, have hz : (z * z) % 4 = 2, { rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, simp only [int.add_mod, int.mul_mod_right, int.mod_mod, zero_add], refl }, have : ∀ (k : ℤ), 0 ≤ k → k < 4 → k * k % 4 ≠ 2 := dec_trivial, have h4 : (4 : ℤ) ≠ 0 := dec_trivial, apply this (z % 4) (int.mod_nonneg z h4) (int.mod_lt z h4), rwa [← int.mul_mod] }, end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), pow_two z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa nat.pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩; { apply and.intro _ co, rw one_mul, rw one_mul, tauto } end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, simpa only [] }, rw [← h.eq, ← pow_two, ← pow_two], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (pow_two_pos_of_ne_zero x hxz) (pow_two_nonneg y) }, { apply lt_add_of_le_of_pos (pow_two_nonneg x) (pow_two_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp _ _) hpy, rw [pow_two, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub (dvd_mul_of_dvd_left (hpz) _) (dvd_mul_of_dvd_left (hpy) _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, h3, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy }, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h2, h3, h4], ring }, { field_simp [h2, h3, h4], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_pow_two_sub_pow_two_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m }, have hnc : p = 2 ∨ p ∣ int.nat_abs n, { exact prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n }, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [pow_two, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_pow_two_sub_pow_two_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_pow_two_sub_pow_two_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_pow_two_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2, { exact le_antisymm (nat.le_of_dvd two_pos hp2) (nat.prime.two_le hp) }, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [pow_two, int.sub_mod, int.mul_mod, hm, hn], }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpn) n end private lemma coprime_pow_two_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_pow_two_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_pow_two_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_pow_two_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_pow_two_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_pow_two_sub_pow_two_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, pow_two], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_square, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (pow_two_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m, { rw [int.cast_coe_nat], exact (rat.cast_id q).symm }, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (pow_two_nonneg n), exact lt_of_le_of_ne (pow_two_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, (rat.denom_ne_zero q)] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_pow_two_sub_pow_two_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_pow_two_sub_pow_two_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_pow_two_sub_pow_two_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_pow_two_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_pow_two_sub_mul co pp } } end theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
22feea53a1dfa016c4d97ad8a89990844c54f035
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/reduce1.lean
342ac55419a93f63df4f806a25bec675ce72b8cd
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,279
lean
partial def fact : Nat → Nat | 0 => 1 | (n+1) => (n+1)*fact n #eval fact 10 #eval fact 100 theorem tst1 : fact 10 = 3628800 := by nativeDecide theorem tst2 : fact 100 = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 := by nativeDecide theorem tst3 : decide (10000000000000000 < 200000000000000000000) = true := by nativeDecide theorem tst4 : 10000000000000000 < 200000000000000000000 := by decide theorem tst5 : 10000000000000000 < 200000000000000000000 := by nativeDecide theorem tst6 : 10000000000000000 < 200000000000000000000 := let h₁ : 10000000000000000 < 10000000000000010 := by nativeDecide let h₂ : 10000000000000010 < 200000000000000000000 := by nativeDecide Nat.ltTrans h₁ h₂ theorem tst7 : 10000000000000000 < 200000000000000000000 := by decide theorem tst8 : 10000000000000000 < 200000000000000000000 := let h₁ : 10000000000000000 < 10000000000000010 := by decide let h₂ : 10000000000000010 < 200000000000000000000 := by decide Nat.ltTrans h₁ h₂ theorem tst9 : 10000000000000000 < 200000000000000000000 := by decide theorem tst10 : 10000000000000000 < 200000000000000000000 := by nativeDecide
5b7dacc0067f5ede350c003db176ccedd397c2f2
26b290e100179c46233060ff9972c0758106c196
/test/cpdt3.lean
56673d7f51b2b281da6e667468816d88ebae6d65
[]
no_license
seanpm2001/LeanProver_Mini_Crush
f95f9e06230b171dd84cc49808f5b2f8378c5e03
cea4166b1b2970fba47907798e7fe0511e426cfd
refs/heads/master
1,688,908,222,650
1,547,825,246,000
1,547,825,246,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,717
lean
import mini_crush /- This corresponds to Chapter 2 of CPDT, Some Quick Examples -/ open list inductive binop : Type | Plus | Times open binop inductive exp : Type | Const : nat → exp | Binop : binop → exp → exp → exp open exp def binop_denote : binop → nat → nat → nat | Plus := (+) | Times := (*) def exp_denote : exp → nat | (Const n) := n | (Binop b e1 e2) := (binop_denote b) (exp_denote e1) (exp_denote e2) inductive instr : Type | iConst : ℕ → instr | iBinop : binop → instr open instr @[reducible] def prog := list instr def stack := list nat def instr_denote (i : instr) (s : stack) : option stack := match i with | (iConst n) := some (n :: s) | (iBinop b) := match s with | (arg1 :: arg2 :: s') := some ((binop_denote b) arg1 arg2 :: s') | _ := none end end def prog_denote : prog → stack → option stack | nil s := some s | (i :: p') s := match instr_denote i s with | none := none | (some s') := prog_denote p' s' end def compile : exp → prog | (Const n) := iConst n :: nil | (Binop b e1 e2) := compile e2 ++ compile e1 ++ iBinop b :: nil /- This example needs a few facts from the list library. -/ @[simp] lemma compile_correct' : ∀ e p s, prog_denote (compile e ++ p) s = prog_denote p (exp_denote e :: s) := by mini_crush @[simp] lemma compile_correct : ∀ e, prog_denote (compile e) nil = some (exp_denote e :: nil) := by mini_crush inductive type : Type | Nat | Bool open type inductive tbinop : type → type → type → Type | TPlus : tbinop Nat Nat Nat | TTimes : tbinop Nat Nat Nat | TEq : ∀ t, tbinop t t Bool | TLt : tbinop Nat Nat Bool open tbinop inductive texp : type → Type | TNConst : nat → texp Nat | TBConst : bool → texp Bool | TBinop : ∀ {t1 t2 t}, tbinop t1 t2 t → texp t1 → texp t2 → texp t open texp def type_denote : type → Type | Nat := nat | Bool := bool /- To simulate CPDT we need the next three operations. -/ def beq_nat (m n : ℕ) : bool := if m = n then tt else ff def eqb (b₁ b₂ : bool) : bool := if b₁ = b₂ then tt else ff def leb (m n : ℕ) : bool := if m < n then tt else ff def tbinop_denote : Π {arg1 arg2 res : type}, tbinop arg1 arg2 res → type_denote arg1 → type_denote arg2 → type_denote res | ._ ._ ._ TPlus := ((+) : ℕ → ℕ → ℕ) | ._ ._ ._ TTimes := ((*) : ℕ → ℕ → ℕ) | ._ ._ ._ (TEq Nat) := beq_nat | ._ ._ ._ (TEq Bool) := eqb | ._ ._ ._ TLt := leb def texp_denote : Π {t : type}, texp t → type_denote t | ._ (TNConst n) := n | ._ (TBConst b) := b | ._ (@TBinop _ _ _ b e1 e2) := (tbinop_denote b) (texp_denote e1) (texp_denote e2) @[reducible] def tstack := list type inductive tinstr : tstack → tstack → Type | TiNConst : Π s, nat → tinstr s (Nat :: s) | TiBConst : Π s, bool → tinstr s (Bool :: s) | TiBinop : Π {arg1 arg2 res s}, tbinop arg1 arg2 res → tinstr (arg1 :: arg2 :: s) (res :: s) open tinstr inductive tprog : tstack → tstack → Type | TNil : Π {s}, tprog s s | TCons : Π {s1 s2 s3}, tinstr s1 s2 → tprog s2 s3 → tprog s1 s3 open tprog def vstack : tstack → Type | nil := unit | (t :: ts') := type_denote t × vstack ts' def tinstr_denote : Π {ts ts' : tstack}, tinstr ts ts' → vstack ts → vstack ts' | ._ ._ (TiNConst ts n) := λ s, (n, s) | ._ ._ (TiBConst ts b) := λ s, (b, s) | ._ ._ (@TiBinop arg1 arg2 res s b) := λ ⟨arg1, ⟨arg2, s'⟩⟩, ((tbinop_denote b) arg1 arg2, s') def tprog_denote : Π {ts ts' : tstack}, tprog ts ts' → vstack ts → vstack ts' | ._ ._ (@TNil _) := λ s, s | ._ ._ (@TCons _ _ _ i p') := λ s, tprog_denote p' (tinstr_denote i s) def tconcat : Π {ts ts' ts'' : tstack}, tprog ts ts' → tprog ts' ts'' → tprog ts ts'' | ._ ._ ts'' (@TNil _) p' := p' | ._ ._ ts'' (@TCons _ _ _ i p1) p' := TCons i (tconcat p1 p') def tcompile : Π {t : type}, texp t → Π ts : tstack, tprog ts (t :: ts) | ._ (TNConst n) ts := TCons (TiNConst _ n) TNil | ._ (TBConst b) ts := TCons (TiBConst _ b) TNil | ._ (@TBinop _ _ _ b e1 e2) ts := tconcat (tcompile e2 _) (tconcat (tcompile e1 _) (TCons (TiBinop b) TNil)) @[simp] lemma tconcat_correct : ∀ ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'') (s : vstack ts), tprog_denote (tconcat p p') s = tprog_denote p' (tprog_denote p s) := by mini_crush @[simp] lemma tcompile_correct' : ∀ t (e : texp t) ts (s : vstack ts), tprog_denote (tcompile e ts) s = (texp_denote e, s) := by mini_crush lemma tcompile_correct : ∀ t (e : texp t), tprog_denote (tcompile e nil) () = (texp_denote e, ()) := by mini_crush
3c68eb02f8ae1b1441f2167034b7fc16d8271a5a
b815abf92ce063fe0d1fabf5b42da483552aa3e8
/library/init/data/default.lean
6fd0e7a95974af837e7a7bacf4242853e94547b1
[ "Apache-2.0" ]
permissive
yodalee/lean
a368d842df12c63e9f79414ed7bbee805b9001ef
317989bf9ef6ae1dec7488c2363dbfcdc16e0756
refs/heads/master
1,610,551,176,860
1,481,430,138,000
1,481,646,441,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
311
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.basic init.data.sigma init.data.nat init.data.char init.data.string import init.data.list init.data.sum init.data.subtype
56a0c4ad99daeb7634b56be831898b429be12306
4727251e0cd73359b15b664c3170e5d754078599
/archive/100-theorems-list/42_inverse_triangle_sum.lean
bb722ed24db984ea48a6061a0acf6b1ae40c53e4
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,068
lean
/- Copyright (c) 2020. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Yury Kudryashov -/ import data.real.basic /-! # Sum of the Reciprocals of the Triangular Numbers This file proves Theorem 42 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). We interpret “triangular numbers” as naturals of the form $\frac{k(k+1)}{2}$ for natural `k`. We prove that the sum of the reciprocals of the first `n` triangular numbers is $2 - \frac2n$. ## Tags discrete_sum -/ open_locale big_operators open finset /-- **Sum of the Reciprocals of the Triangular Numbers** -/ lemma inverse_triangle_sum : ∀ n, ∑ k in range n, (2 : ℚ) / (k * (k + 1)) = if n = 0 then 0 else 2 - (2 : ℚ) / n := begin refine sum_range_induction _ _ (if_pos rfl) _, rintro (_|n), { rw [if_neg, if_pos]; norm_num }, simp_rw [if_neg (nat.succ_ne_zero _), nat.succ_eq_add_one], have A : (n + 1 + 1 : ℚ) ≠ 0, by { norm_cast, norm_num }, push_cast, field_simp [nat.cast_add_one_ne_zero], ring end
45e6c389bcde11b8d6a9cca0da8fe12549995708
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/geometry/manifold/times_cont_mdiff_map.lean
8f1b506b3e8518a71e8dfa66059bac240e156d24
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,388
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import geometry.manifold.times_cont_mdiff import topology.continuous_map /-! # Smooth bundled map In this file we define the type `times_cont_mdiff_map` of `n` times continuously differentiable bundled maps. -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] (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''] [smooth_manifold_with_corners I'' M''] (n : with_top ℕ) /-- Bundled `n` times continuously differentiable maps. -/ @[protect_proj] structure times_cont_mdiff_map := (to_fun : M → M') (times_cont_mdiff_to_fun : times_cont_mdiff I I' n to_fun) /-- Bundled smooth maps. -/ @[reducible] def smooth_map := times_cont_mdiff_map I I' M M' ⊤ localized "notation `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` := times_cont_mdiff_map I I' M M' n" in manifold localized "notation `C^` n `⟮` I `, ` M `; ` k `⟯` := times_cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold open_locale manifold namespace times_cont_mdiff_map variables {I} {I'} {M} {M'} {n} instance : has_coe_to_fun C^n⟮I, M; I', M'⟯ := ⟨_, times_cont_mdiff_map.to_fun⟩ instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') := ⟨λ f, ⟨f.to_fun, f.times_cont_mdiff_to_fun.continuous⟩⟩ variables {f g : C^n⟮I, M; I', M'⟯} protected lemma times_cont_mdiff (f : C^n⟮I, M; I', M'⟯) : times_cont_mdiff I I' n f := f.times_cont_mdiff_to_fun protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) : smooth I I' f := f.times_cont_mdiff_to_fun lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext h /-- The identity as a smooth map. -/ def id : C^n⟮I, M; I, M⟯ := ⟨id, times_cont_mdiff_id⟩ /-- The composition of smooth maps, as a smooth map. -/ def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ := { to_fun := λ a, f (g a), times_cont_mdiff_to_fun := f.times_cont_mdiff_to_fun.comp g.times_cont_mdiff_to_fun, } @[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) : f.comp g x = f (g x) := rfl instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ := ⟨⟨λ _, default _, times_cont_mdiff_const⟩⟩ /-- Constant map as a smooth map -/ def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, times_cont_mdiff_const⟩ end times_cont_mdiff_map instance continuous_linear_map.has_coe_to_times_cont_mdiff_map : has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ := ⟨λ f, ⟨f.to_fun, f.times_cont_mdiff⟩⟩
5508b6a10765391f3c14ea4d130971508f939a03
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/type_class_performance1.lean
8de8faeba09f36fe2470bf303aa15ad92177aaa7
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
190
lean
new_frontend #print USize def foo1 (a b : UInt64) : Bool := a = b def foo2 (a b : UInt16) : Bool := a = b def foo3 (a b : UInt32) : Bool := a = b def foo4 (a b : USize) : Bool := a = b
6bba0e459288df81720e92802bfd847a5da012bf
7541ac8517945d0f903ff5397e13e2ccd7c10573
/src/category_theory/idempotent_completion.lean
3880863a09027e69bc6bbc228acc9a50cd98be22
[]
no_license
ramonfmir/lean-category-theory
29b6bad9f62c2cdf7517a3135e5a12b340b4ed90
be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad
refs/heads/master
1,586,110,684,637
1,541,927,184,000
1,541,927,184,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,174
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.equivalence namespace category_theory universes u u₁ u₂ structure Idempotent (C : Type (u+1)) [large_category C] := (object : C) (idempotent : object ⟶ object) (witness' : idempotent ≫ idempotent = idempotent . obviously) restate_axiom Idempotent.witness' attribute [simp,search] Idempotent.witness variables {C : Type (u+1)} [large_category C] namespace Idempotent structure morphism (X Y : Idempotent C) := (morphism : X.object ⟶ Y.object) (left' : X.idempotent ≫ morphism = morphism . obviously) (right' : morphism ≫ Y.idempotent = morphism . obviously) restate_axiom morphism.left' restate_axiom morphism.right' attribute [simp,search] morphism.left morphism.right @[extensionality] lemma ext {X Y : Idempotent C} (f g : morphism X Y) (w : f.morphism = g.morphism) : f = g := begin induction f, induction g, tidy end end Idempotent instance IdempotentCompletion : large_category (Idempotent C) := { hom := Idempotent.morphism, id := λ X, ⟨ X.idempotent ⟩, comp := λ X Y Z f g, ⟨ f.morphism ≫ g.morphism ⟩ } namespace IdempotentCompletion def functor_to_completion (C : Type (u+1)) [large_category C] : C ⥤ (Idempotent C) := { obj := λ X, { object := X, idempotent := 𝟙 X }, map := λ _ _ f, { morphism := f } } -- -- PROJECT -- def IdempotentCompletion_functorial (C : Type u) [category C] (D : Type u) [category D] : Functor (Functor C D) (Functor (Idempotent C) (Idempotent D)) := { -- FIXME -- lemma embedding' (C : Type (u+1)) [large_category C] : embedding (functor_to_completion C) := by obviously variable {D : Type (u₂+1)} variable [large_category D] def restrict_Functor_from (F : (Idempotent C) ⥤ D) : C ⥤ D := (functor_to_completion C) ⋙ F @[simp] private lemma double_idempotent_morphism_left (X Y : Idempotent (Idempotent C)) (f : X ⟶ Y) : (X.idempotent).morphism ≫ (f.morphism).morphism = (f.morphism).morphism := congr_arg Idempotent.morphism.morphism f.left @[simp] private lemma double_idempotent_morphism_right (X Y : Idempotent (Idempotent C)) (f : X ⟶ Y) : (f.morphism).morphism ≫ (Y.idempotent).morphism = (f.morphism).morphism := congr_arg Idempotent.morphism.morphism f.right private def idempotent_functor (C : Type (u+1)) [large_category C] : (Idempotent (Idempotent C)) ⥤ (Idempotent C) := { obj := λ X, ⟨ X.object.object, X.idempotent.morphism, congr_arg Idempotent.morphism.morphism X.witness ⟩, -- PROJECT think about automation here map := λ X Y f, ⟨ f.morphism.morphism, by obviously ⟩ } private def idempotent_inverse (C : Type (u+1)) [large_category C] : (Idempotent C) ⥤ (Idempotent (Idempotent C)) := { obj := λ X, ⟨ X, ⟨ X.idempotent, by obviously ⟩, by obviously ⟩, map := λ X Y f, ⟨ f, by obviously ⟩ } -- PROJECT prove these lemmas about idempotent completion -- lemma IdempotentCompletion_idempotent (C : Type u) [category C] : -- equivalence (IdempotentCompletion (IdempotentCompletion C)) (IdempotentCompletion C) := -- { -- functor := IdempotentCompletion_idempotent_functor C, -- inverse := IdempotentCompletion_idempotent_inverse C, -- isomorphism_1 := begin tidy, exact C.identity _, tidy, induction f_2, tidy, end, -- PROJECT very slow?? -- isomorphism_2 := sorry --} def extend_Functor_to_completion (F : C ⥤ (Idempotent D)) : (Idempotent C) ⥤ (Idempotent D) := { obj := λ X, { object := (F.obj X.object).object, idempotent := (F.map X.idempotent).morphism }, map := λ X Y f, { morphism := (F.map f.morphism).morphism } } -- lemma Functor_from_IdempotentCompletion_determined_by_restriction -- {C D : Category} (F : Functor (IdempotentCompletion C) (IdempotentCompletion D)) : -- NaturalIsomorphism (extend_Functor_to_IdempotentCompletion (restrict_Functor_from_IdempotentCompletion F)) F := -- sorry -- PROJECT idempotent completion left adjoint to the forgetful functor from categories to semicategories? end IdempotentCompletion end category_theory
28a4c3b41ace737f2476b4aff836d3d2b616449a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebraic_geometry/ringed_space.lean
7b145c23260892119b164abc46d1ed28a62fac33
[ "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
4,781
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import algebraic_geometry.sheafed_space import algebraic_geometry.stalks import algebra.category.CommRing.limits import algebra.category.CommRing.colimits import algebra.category.CommRing.filtered_colimits /-! # Ringed spaces We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`. The facts collected in this file are typically stated for locally ringed spaces, but never actually make use of the locality of stalks. See for instance https://stacks.math.columbia.edu/tag/01HZ. -/ universe v open category_theory open topological_space open opposite open Top open Top.presheaf namespace algebraic_geometry /-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/ abbreviation RingedSpace : Type* := SheafedSpace CommRing namespace RingedSpace open SheafedSpace variables (X : RingedSpace.{v}) /-- If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small neighborhood around `x`. -/ lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U) (h : is_unit (X.presheaf.germ x f)) : ∃ (V : opens X) (i : V ⟶ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) := begin obtain ⟨g', heq⟩ := h.exists_right_inv, obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g', let W := U ⊓ V, have hxW : x.1 ∈ W := ⟨x.2, hxV⟩, erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f, ← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g, ← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq, obtain ⟨W', hxW', i₁, i₂, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq, use [W', i₁ ≫ opens.inf_le_left U V, hxW'], rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq', exact is_unit_of_mul_eq_one _ _ heq', end /-- If a section `f` is a unit in each stalk, `f` must be a unit. -/ lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (h : ∀ x : U, is_unit (X.presheaf.germ x f)) : is_unit f := begin -- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`. choose V iVU m h_unit using λ x : U, X.is_unit_res_of_is_unit_germ U f x (h x), have hcover : U ≤ supr V, { intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, -- Let `g x` denote the inverse of `f` in `U x`. choose g hg using λ x : U, is_unit.exists_right_inv (h_unit x), -- We claim that these local inverses glue together to a global inverse of `f`. obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _, swap, { intros x y, apply section_ext X.sheaf (V x ⊓ V y), rintro ⟨z, hzVx, hzVy⟩, rw [germ_res_apply, germ_res_apply], apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp, erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply, ← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), ring_hom.map_one, ring_hom.map_one] }, apply is_unit_of_mul_eq_one f gl, apply X.sheaf.eq_of_locally_eq' V U iVU hcover, intro i, rw [ring_hom.map_one, ring_hom.map_mul, gl_spec], exact hg i, end /-- The basic open of a global section `f` is the set of all points `x`, such that the germ of `f` at `x` is a unit. -/ def basic_open (f : Γ.obj (op X)) : opens X := { val := { x : X | is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens X)) f) }, property := begin rw is_open_iff_forall_mem_open, intros x hx, obtain ⟨U, i, hxU, hf⟩ := X.is_unit_res_of_is_unit_germ ⊤ f ⟨x, trivial⟩ hx, use U.1, refine ⟨_, U.2, hxU⟩, intros y hy, rw set.mem_set_of_eq, convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf, exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm, end } @[simp] lemma mem_basic_open (f : Γ.obj (op X)) (x : X) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens X)) f) := iff.rfl /-- The restriction of a global section `f` to the basic open of `f` is a unit. -/ lemma is_unit_res_basic_open (f : Γ.obj (op X)) : is_unit (X.presheaf.map (opens.le_top (X.basic_open f)).op f) := begin apply is_unit_of_is_unit_germ, rintro ⟨x, hx⟩, convert hx, rw germ_res_apply, refl, end end RingedSpace end algebraic_geometry
1de4904e872353daa622c37c9c5b06e73ea353a1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/projective.lean
c147cd4606636d20c68dfa38e02d5b1c272a80e0
[ "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
9,682
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Antoine Labelle -/ import algebra.module.basic import linear_algebra.finsupp import linear_algebra.free_module.basic /-! # Projective modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains a definition of a projective module, the proof that our definition is equivalent to a lifting property, and the proof that all free modules are projective. ## Main definitions Let `R` be a ring (or a semiring) and let `M` be an `R`-module. * `is_projective R M` : the proposition saying that `M` is a projective `R`-module. ## Main theorems * `is_projective.lifting_property` : a map from a projective module can be lifted along a surjection. * `is_projective.of_lifting_property` : If for all R-module surjections `A →ₗ B`, all maps `M →ₗ B` lift to `M →ₗ A`, then `M` is projective. * `is_projective.of_free` : Free modules are projective ## Implementation notes The actual definition of projective we use is that the natural R-module map from the free R-module on the type M down to M splits. This is more convenient than certain other definitions which involve quantifying over universes, and also universe-polymorphic (the ring and module can be in different universes). We require that the module sits in at least as high a universe as the ring: without this, free modules don't even exist, and it's unclear if projective modules are even a useful notion. ## References https://en.wikipedia.org/wiki/Projective_module ## TODO - Direct sum of two projective modules is projective. - Arbitrary sum of projective modules is projective. All of these should be relatively straightforward. ## Tags projective module -/ universes u v open linear_map finsupp /- The actual implementation we choose: `P` is projective if the natural surjection from the free `R`-module on `P` to `P` splits. -/ /-- An R-module is projective if it is a direct summand of a free module, or equivalently if maps from the module lift along surjections. There are several other equivalent definitions. -/ class module.projective (R : Type*) [semiring R] (P : Type*) [add_comm_monoid P] [module R P] : Prop := (out : ∃ s : P →ₗ[R] (P →₀ R), function.left_inverse (finsupp.total P P R id) s) namespace module section semiring variables {R : Type*} [semiring R] {P : Type*} [add_comm_monoid P] [module R P] {M : Type*} [add_comm_monoid M] [module R M] {N : Type*} [add_comm_monoid N] [module R N] lemma projective_def : projective R P ↔ (∃ s : P →ₗ[R] (P →₀ R), function.left_inverse (finsupp.total P P R id) s) := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem projective_def' : projective R P ↔ (∃ s : P →ₗ[R] (P →₀ R), (finsupp.total P P R id) ∘ₗ s = id) := by simp_rw [projective_def, fun_like.ext_iff, function.left_inverse, coe_comp, id_coe, id.def] /-- A projective R-module has the property that maps from it lift along surjections. -/ theorem projective_lifting_property [h : projective R P] (f : M →ₗ[R] N) (g : P →ₗ[R] N) (hf : function.surjective f) : ∃ (h : P →ₗ[R] M), f.comp h = g := begin /- Here's the first step of the proof. Recall that `X →₀ R` is Lean's way of talking about the free `R`-module on a type `X`. The universal property `finsupp.total` says that to a map `X → N` from a type to an `R`-module, we get an associated R-module map `(X →₀ R) →ₗ N`. Apply this to a (noncomputable) map `P → M` coming from the map `P →ₗ N` and a random splitting of the surjection `M →ₗ N`, and we get a map `φ : (P →₀ R) →ₗ M`. -/ let φ : (P →₀ R) →ₗ[R] M := finsupp.total _ _ _ (λ p, function.surj_inv hf (g p)), -- By projectivity we have a map `P →ₗ (P →₀ R)`; cases h.out with s hs, -- Compose to get `P →ₗ M`. This works. use φ.comp s, ext p, conv_rhs {rw ← hs p}, simp [φ, finsupp.total_apply, function.surj_inv_eq hf], end variables {Q : Type*} [add_comm_monoid Q] [module R Q] instance [hP : projective R P] [hQ : projective R Q] : projective R (P × Q) := begin rw module.projective_def', cases hP.out with sP hsP, cases hQ.out with sQ hsQ, use coprod (lmap_domain R R (inl R P Q)) (lmap_domain R R (inr R P Q)) ∘ₗ sP.prod_map sQ, ext; simp only [coe_inl, coe_inr, coe_comp, function.comp_app, prod_map_apply, map_zero, coprod_apply, lmap_domain_apply, map_domain_zero, add_zero, zero_add, id_comp, total_map_domain], { rw [←fst_apply _, apply_total R], exact hsP x, }, { rw [←snd_apply _, apply_total R], exact finsupp.total_zero_apply _ (sP x), }, { rw [←fst_apply _, apply_total R], exact finsupp.total_zero_apply _ (sQ x), }, { rw [←snd_apply _, apply_total R], exact hsQ x, }, end variables {ι : Type*} (A : ι → Type*) [Π (i : ι), add_comm_monoid (A i)] [Π (i : ι), module R (A i)] instance [h : Π (i : ι), projective R (A i)] : projective R (Π₀ i, A i) := begin classical, rw module.projective_def', simp_rw projective_def at h, choose s hs using h, letI : Π (i : ι), add_comm_monoid (A i →₀ R) := λ i, by apply_instance, letI : Π (i : ι), module R (A i →₀ R) := λ i, by apply_instance, letI : add_comm_monoid (Π₀ (i : ι), A i →₀ R) := @dfinsupp.add_comm_monoid ι (λ i, A i →₀ R) _, letI : module R (Π₀ (i : ι), A i →₀ R) := @dfinsupp.module ι R (λ i, A i →₀ R) _ _ _, let f := λ i, lmap_domain R R (dfinsupp.single i : A i → Π₀ i, A i), use dfinsupp.coprod_map f ∘ₗ dfinsupp.map_range.linear_map s, ext i x j, simp only [dfinsupp.coprod_map, direct_sum.lof, total_map_domain, coe_comp, coe_lsum, id_coe, linear_equiv.coe_to_linear_map, finsupp_lequiv_dfinsupp_symm_apply, function.comp_app, dfinsupp.lsingle_apply, dfinsupp.map_range.linear_map_apply, dfinsupp.map_range_single, lmap_domain_apply, dfinsupp.to_finsupp_single, finsupp.sum_single_index, id.def, function.comp.left_id, dfinsupp.single_apply], rw [←dfinsupp.lapply_apply j, apply_total R], obtain rfl | hij := eq_or_ne i j, { convert (hs i) x, { ext, simp }, { simp } }, { convert finsupp.total_zero_apply _ ((s i) x), { ext, simp [hij] }, { simp [hij] } } end end semiring section ring variables {R : Type*} [ring R] {P : Type*} [add_comm_group P] [module R P] /-- Free modules are projective. -/ theorem projective_of_basis {ι : Type*} (b : basis ι R P) : projective R P := begin -- need P →ₗ (P →₀ R) for definition of projective. -- get it from `ι → (P →₀ R)` coming from `b`. use b.constr ℕ (λ i, finsupp.single (b i) (1 : R)), intro m, simp only [b.constr_apply, mul_one, id.def, finsupp.smul_single', finsupp.total_single, linear_map.map_finsupp_sum], exact b.total_repr m, end @[priority 100] instance projective_of_free [module.free R P] : module.projective R P := projective_of_basis $ module.free.choose_basis R P end ring --This is in a different section because special universe restrictions are required. section of_lifting_property /-- A module which satisfies the universal property is projective. Note that the universe variables in `huniv` are somewhat restricted. -/ theorem projective_of_lifting_property' {R : Type u} [semiring R] {P : Type (max u v)} [add_comm_monoid P] [module R P] -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_monoid M] [add_comm_monoid N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. projective R P := begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end /-- A variant of `of_lifting_property'` when we're working over a `[ring R]`, which only requires quantifying over modules with an `add_comm_group` instance. -/ theorem projective_of_lifting_property {R : Type u} [ring R] {P : Type (max u v)} [add_comm_group P] [module R P] -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_group M] [add_comm_group N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. projective R P := -- We could try and prove this *using* `of_lifting_property`, -- but this quickly leads to typeclass hell, -- so we just prove it over again. begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end end of_lifting_property end module
c1ba3f18cb7c1141cbd5ef1ec3d802f743102cea
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/group_with_zero.lean
05ff3d8d95f23e9480bacf7c841aa4b026bf273f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
37,725
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import logic.nontrivial import algebra.group.units_hom import algebra.group.inj_surj /-! # Groups with an adjoined zero element This file describes structures that are not usually studied on their own right in mathematics, namely a special sort of monoid: apart from a distinguished “zero element” they form a group, or in other words, they are groups with an adjoined zero element. Examples are: * division rings; * the value monoid of a multiplicative valuation; * in particular, the non-negative real numbers. ## Main definitions * `group_with_zero` * `comm_group_with_zero` ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ set_option old_structure_cmd true open_locale classical open function variables {M₀ G₀ M₀' G₀' : Type*} mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." section /-- Typeclass for expressing that a type `M₀` with multiplication and a zero satisfies `0 * a = 0` and `a * 0 = 0` for all `a : M₀`. -/ @[protect_proj, ancestor has_mul has_zero] class mul_zero_class (M₀ : Type*) extends has_mul M₀, has_zero M₀ := (zero_mul : ∀ a : M₀, 0 * a = 0) (mul_zero : ∀ a : M₀, a * 0 = 0) section mul_zero_class variables [mul_zero_class M₀] {a b : M₀} @[ematch, simp] lemma zero_mul (a : M₀) : 0 * a = 0 := mul_zero_class.zero_mul a @[ematch, simp] lemma mul_zero (a : M₀) : a * 0 = 0 := mul_zero_class.mul_zero a /-- Pullback a `mul_zero_class` instance along an injective function. -/ protected def function.injective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : mul_zero_class M₀' := { mul := (*), zero := 0, zero_mul := λ a, hf $ by simp only [mul, zero, zero_mul], mul_zero := λ a, hf $ by simp only [mul, zero, mul_zero] } /-- Pushforward a `mul_zero_class` instance along an surjective function. -/ protected def function.surjective.mul_zero_class [has_mul M₀'] [has_zero M₀'] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (mul : ∀ a b, f (a * b) = f a * f b) : mul_zero_class M₀' := { mul := (*), zero := 0, mul_zero := hf.forall.2 $ λ x, by simp only [← zero, ← mul, mul_zero], zero_mul := hf.forall.2 $ λ x, by simp only [← zero, ← mul, zero_mul] } lemma mul_eq_zero_of_left (h : a = 0) (b : M₀) : a * b = 0 := h.symm ▸ zero_mul b lemma mul_eq_zero_of_right (a : M₀) (h : b = 0) : a * b = 0 := h.symm ▸ mul_zero a lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b) lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a) lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := ⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩ end mul_zero_class /-- Predicate typeclass for expressing that `a * b = 0` implies `a = 0` or `b = 0` for all `a` and `b` of type `G₀`. -/ class no_zero_divisors (M₀ : Type*) [has_mul M₀] [has_zero M₀] : Prop := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ {a b : M₀}, a * b = 0 → a = 0 ∨ b = 0) export no_zero_divisors (eq_zero_or_eq_zero_of_mul_eq_zero) /-- Pushforward a `no_zero_divisors` instance along an injective function. -/ protected lemma function.injective.no_zero_divisors [has_mul M₀] [has_zero M₀] [has_mul M₀'] [has_zero M₀'] [no_zero_divisors M₀'] (f : M₀ → M₀') (hf : injective f) (zero : f 0 = 0) (mul : ∀ x y, f (x * y) = f x * f y) : no_zero_divisors M₀ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y H, have f x * f y = 0, by rw [← mul, H, zero], (eq_zero_or_eq_zero_of_mul_eq_zero this).imp (λ H, hf $ by rwa zero) (λ H, hf $ by rwa zero) } lemma eq_zero_of_mul_self_eq_zero [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀] {a : M₀} (h : a * a = 0) : a = 0 := (eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id section variables [mul_zero_class M₀] [no_zero_divisors M₀] {a b : M₀} /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem mul_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, o.elim (λ h, mul_eq_zero_of_left h b) (mul_eq_zero_of_right a)⟩ /-- If `α` has no zero divisors, then the product of two elements equals zero iff one of them equals zero. -/ @[simp] theorem zero_eq_mul : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] /-- If `α` has no zero divisors, then the product of two elements is nonzero iff both of them are nonzero. -/ theorem mul_ne_zero_iff : a * b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := (not_congr mul_eq_zero).trans not_or_distrib theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := mul_ne_zero_iff.2 ⟨ha, hb⟩ /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` equals zero iff so is `b * a`. -/ theorem mul_eq_zero_comm : a * b = 0 ↔ b * a = 0 := mul_eq_zero.trans $ (or_comm _ _).trans mul_eq_zero.symm /-- If `α` has no zero divisors, then for elements `a, b : α`, `a * b` is nonzero iff so is `b * a`. -/ theorem mul_ne_zero_comm : a * b ≠ 0 ↔ b * a ≠ 0 := not_congr mul_eq_zero_comm lemma mul_self_eq_zero : a * a = 0 ↔ a = 0 := by simp lemma zero_eq_mul_self : 0 = a * a ↔ a = 0 := by simp end end /-- A type `M` is a “monoid with zero” if it is a monoid with zero element, and `0` is left and right absorbing. -/ @[protect_proj] class monoid_with_zero (M₀ : Type*) extends monoid M₀, mul_zero_class M₀. /-- A type `M` is a `cancel_monoid_with_zero` if it is a monoid with zero element, `0` is left and right absorbing, and left/right multiplication by a non-zero element is injective. -/ @[protect_proj] class cancel_monoid_with_zero (M₀ : Type*) extends monoid_with_zero M₀ := (mul_left_cancel_of_ne_zero : ∀ {a b c : M₀}, a ≠ 0 → a * b = a * c → b = c) (mul_right_cancel_of_ne_zero : ∀ {a b c : M₀}, b ≠ 0 → a * b = c * b → a = c) section variables [monoid_with_zero M₀] [nontrivial M₀] {a b : M₀} /-- In a nontrivial monoid with zero, zero and one are different. -/ @[simp] lemma zero_ne_one : 0 ≠ (1:M₀) := begin assume h, rcases exists_pair_ne M₀ with ⟨x, y, hx⟩, apply hx, calc x = 1 * x : by rw [one_mul] ... = 0 : by rw [← h, zero_mul] ... = 1 * y : by rw [← h, zero_mul] ... = y : by rw [one_mul] end @[simp] lemma one_ne_zero : (1:M₀) ≠ 0 := zero_ne_one.symm lemma ne_zero_of_eq_one {a : M₀} (h : a = 1) : a ≠ 0 := calc a = 1 : h ... ≠ 0 : one_ne_zero lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 := left_ne_zero_of_mul $ ne_zero_of_eq_one h lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 := right_ne_zero_of_mul $ ne_zero_of_eq_one h /-- Pullback a `nontrivial` instance along a function sending `0` to `0` and `1` to `1`. -/ protected lemma pullback_nonzero [has_zero M₀'] [has_one M₀'] (f : M₀' → M₀) (zero : f 0 = 0) (one : f 1 = 1) : nontrivial M₀' := ⟨⟨0, 1, mt (congr_arg f) $ by { rw [zero, one], exact zero_ne_one }⟩⟩ end /-- A type `M` is a commutative “monoid with zero” if it is a commutative monoid with zero element, and `0` is left and right absorbing. -/ @[protect_proj] class comm_monoid_with_zero (M₀ : Type*) extends comm_monoid M₀, monoid_with_zero M₀. /-- A type `M` is a `comm_cancel_monoid_with_zero` if it is a commutative monoid with zero element, `0` is left and right absorbing, and left/right multiplication by a non-zero element is injective. -/ @[protect_proj] class comm_cancel_monoid_with_zero (M₀ : Type*) extends comm_monoid_with_zero M₀, cancel_monoid_with_zero M₀. /-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. Examples include division rings and the ordered monoids that are the target of valuations in general valuation theory.-/ class group_with_zero (G₀ : Type*) extends monoid_with_zero G₀, has_inv G₀, nontrivial G₀ := (inv_zero : (0 : G₀)⁻¹ = 0) (mul_inv_cancel : ∀ a:G₀, a ≠ 0 → a * a⁻¹ = 1) /-- A type `G₀` is a commutative “group with zero” if it is a commutative monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/ class comm_group_with_zero (G₀ : Type*) extends comm_monoid_with_zero G₀, group_with_zero G₀. /-- The division operation on a group with zero element. -/ @[priority 100] -- see Note [lower instance priority] instance group_with_zero.has_div {G₀ : Type*} [group_with_zero G₀] : has_div G₀ := ⟨λ g h, g * h⁻¹⟩ section monoid_with_zero /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [monoid_with_zero M₀] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid_with_zero M₀' := { .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [monoid_with_zero M₀] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : monoid_with_zero M₀' := { .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [comm_monoid_with_zero M₀] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := { .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul } /-- Pushforward a `monoid_with_zero` class along a surjective function. -/ protected def function.surjective.comm_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] [comm_monoid_with_zero M₀] (f : M₀ → M₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : comm_monoid_with_zero M₀' := { .. hf.comm_monoid f one mul, .. hf.mul_zero_class f zero mul } variables [monoid_with_zero M₀] namespace units /-- An element of the unit group of a nonzero monoid with zero represented as an element of the monoid is nonzero. -/ @[simp] lemma ne_zero [nontrivial M₀] (u : units M₀) : (u : M₀) ≠ 0 := left_ne_zero_of_mul_eq_one u.mul_inv -- We can't use `mul_eq_zero` + `units.ne_zero` in the next two lemmas because we don't assume -- `nonzero M₀`. @[simp] lemma mul_left_eq_zero (u : units M₀) {a : M₀} : a * u = 0 ↔ a = 0 := ⟨λ h, by simpa using mul_eq_zero_of_left h ↑u⁻¹, λ h, mul_eq_zero_of_left h u⟩ @[simp] lemma mul_right_eq_zero (u : units M₀) {a : M₀} : ↑u * a = 0 ↔ a = 0 := ⟨λ h, by simpa using mul_eq_zero_of_right ↑u⁻¹ h, mul_eq_zero_of_right u⟩ end units namespace is_unit lemma ne_zero [nontrivial M₀] {a : M₀} (ha : is_unit a) : a ≠ 0 := let ⟨u, hu⟩ := ha in hu ▸ u.ne_zero lemma mul_right_eq_zero {a b : M₀} (ha : is_unit a) : a * b = 0 ↔ b = 0 := let ⟨u, hu⟩ := ha in hu ▸ u.mul_right_eq_zero lemma mul_left_eq_zero {a b : M₀} (hb : is_unit b) : a * b = 0 ↔ a = 0 := let ⟨u, hu⟩ := hb in hu ▸ u.mul_left_eq_zero end is_unit /-- In a monoid with zero, if zero equals one, then zero is the only element. -/ lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 := by rw [← mul_one a, ← h, mul_zero] /-- In a monoid with zero, if zero equals one, then zero is the unique element. Somewhat arbitrarily, we define the default element to be `0`. All other elements will be provably equal to it, but not necessarily definitionally equal. -/ def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ := { default := 0, uniq := eq_zero_of_zero_eq_one h } /-- In a monoid with zero, if zero equals one, then all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : M₀) = 1) : subsingleton M₀ := @unique.subsingleton _ (unique_of_zero_eq_one h) lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b := @subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b @[simp] theorem is_unit_zero_iff : is_unit (0 : M₀) ↔ (0:M₀) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, ⟨⟨0, 0, eq_of_zero_eq_one h _ _, eq_of_zero_eq_one h _ _⟩, rfl⟩⟩ @[simp] theorem not_is_unit_zero [nontrivial M₀] : ¬ is_unit (0 : M₀) := mt is_unit_zero_iff.1 zero_ne_one variable (M₀) /-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) := not_or_of_imp eq_zero_of_zero_eq_one end monoid_with_zero section cancel_monoid_with_zero variables [cancel_monoid_with_zero M₀] {a b c : M₀} @[priority 10] -- see Note [lower instance priority] instance comm_cancel_monoid_with_zero.no_zero_divisors : no_zero_divisors M₀ := ⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right, apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩ lemma mul_left_cancel' (ha : a ≠ 0) (h : a * b = a * c) : b = c := cancel_monoid_with_zero.mul_left_cancel_of_ne_zero ha h lemma mul_right_cancel' (hb : b ≠ 0) (h : a * b = c * b) : a = c := cancel_monoid_with_zero.mul_right_cancel_of_ne_zero hb h lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := ⟨mul_right_cancel' hc, λ h, h ▸ rfl⟩ lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := ⟨mul_left_cancel' ha, λ h, h ▸ rfl⟩ /-- Pullback a `monoid_with_zero` class along an injective function. -/ protected def function.injective.cancel_monoid_with_zero [has_zero M₀'] [has_mul M₀'] [has_one M₀'] (f : M₀' → M₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : cancel_monoid_with_zero M₀' := { mul_left_cancel_of_ne_zero := λ x y z hx H, hf $ mul_left_cancel' ((hf.ne_iff' zero).2 hx) $ by erw [← mul, ← mul, H]; refl, mul_right_cancel_of_ne_zero := λ x y z hx H, hf $ mul_right_cancel' ((hf.ne_iff' zero).2 hx) $ by erw [← mul, ← mul, H]; refl, .. hf.monoid f one mul, .. hf.mul_zero_class f zero mul } /-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel' ha $ h₂.symm ▸ (mul_one a).symm /-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel' ha $ h₂.symm ▸ (one_mul a).symm end cancel_monoid_with_zero section group_with_zero variables [group_with_zero G₀] lemma div_eq_mul_inv {a b : G₀} : a / b = a * b⁻¹ := rfl alias div_eq_mul_inv ← division_def @[simp] lemma inv_zero : (0 : G₀)⁻¹ = 0 := group_with_zero.inv_zero @[simp] lemma mul_inv_cancel {a : G₀} (h : a ≠ 0) : a * a⁻¹ = 1 := group_with_zero.mul_inv_cancel a h /-- Pullback a `group_with_zero` class along an injective function. -/ protected def function.injective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : group_with_zero G₀' := { inv := has_inv.inv, inv_zero := hf $ by erw [inv, zero, inv_zero], mul_inv_cancel := λ x hx, hf $ by erw [one, mul, inv, mul_inv_cancel ((hf.ne_iff' zero).2 hx)], .. hf.monoid_with_zero f zero one mul, .. pullback_nonzero f zero one } /-- Pushforward a `group_with_zero` class along an surjective function. -/ protected def function.surjective.group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : group_with_zero G₀' := { inv := has_inv.inv, inv_zero := by erw [← zero, ← inv, inv_zero], mul_inv_cancel := hf.forall.2 $ λ x hx, by erw [← inv, ← mul, mul_inv_cancel (mt (congr_arg f) $ trans_rel_left ne hx zero.symm)]; exact one, exists_pair_ne := ⟨0, 1, h01⟩, .. hf.monoid_with_zero f zero one mul } @[simp] lemma mul_inv_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) : (a * b) * b⁻¹ = a := calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma mul_inv_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] lemma inv_ne_zero {a : G₀} (h : a ≠ 0) : a⁻¹ ≠ 0 := assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h @[simp] lemma inv_mul_cancel {a : G₀} (h : a ≠ 0) : a⁻¹ * a = 1 := calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h] ... = a⁻¹ * a⁻¹⁻¹ : by simp [h] ... = 1 : by simp [inv_ne_zero h] @[simp] lemma inv_mul_cancel_right' {b : G₀} (h : b ≠ 0) (a : G₀) : (a * b⁻¹) * b = a := calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma inv_mul_cancel_left' {a : G₀} (h : a ≠ 0) (b : G₀) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] @[simp] lemma inv_one : 1⁻¹ = (1:G₀) := calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul] ... = (1:G₀) : by simp @[simp] lemma inv_inv' (a : G₀) : a⁻¹⁻¹ = a := begin classical, by_cases h : a = 0, { simp [h] }, calc a⁻¹⁻¹ = a * (a⁻¹ * a⁻¹⁻¹) : by simp [h] ... = a : by simp [inv_ne_zero h] end /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_assoc, mul_inv_cancel h, mul_one] } end /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_inv_cancel h, one_mul] } end /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a := begin classical, by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [inv_mul_cancel h, one_mul] } end /-- Multiplying `a` by itself and then dividing by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a := mul_self_mul_inv a /-- Dividing `a` by itself and then multiplying by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a := mul_inv_mul_self a lemma inv_involutive' : function.involutive (has_inv.inv : G₀ → G₀) := inv_inv' lemma eq_inv_of_mul_right_eq_one {a b : G₀} (h : a * b = 1) : b = a⁻¹ := by rw [← inv_mul_cancel_left' (left_ne_zero_of_mul_eq_one h) b, h, mul_one] lemma eq_inv_of_mul_left_eq_one {a b : G₀} (h : a * b = 1) : a = b⁻¹ := by rw [← mul_inv_cancel_right' (right_ne_zero_of_mul_eq_one h) a, h, one_mul] lemma inv_injective' : function.injective (@has_inv.inv G₀ _) := inv_involutive'.injective @[simp] lemma inv_inj' {g h : G₀} : g⁻¹ = h⁻¹ ↔ g = h := inv_injective'.eq_iff lemma inv_eq_iff {g h : G₀} : g⁻¹ = h ↔ h⁻¹ = g := by rw [← inv_inj', eq_comm, inv_inv'] end group_with_zero namespace units variables [group_with_zero G₀] variables {a b : G₀} /-- Embed a non-zero element of a `group_with_zero` into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : G₀) (ha : a ≠ 0) : units G₀ := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] lemma coe_mk0 {a : G₀} (h : a ≠ 0) : (mk0 a h : G₀) = a := rfl @[simp] lemma mk0_coe (u : units G₀) (h : (u : G₀) ≠ 0) : mk0 (u : G₀) h = u := units.ext rfl @[simp, norm_cast] lemma coe_inv' (u : units G₀) : ((u⁻¹ : units G₀) : G₀) = u⁻¹ := eq_inv_of_mul_left_eq_one u.inv_mul @[simp] lemma mul_inv' (u : units G₀) : (u : G₀) * u⁻¹ = 1 := mul_inv_cancel u.ne_zero @[simp] lemma inv_mul' (u : units G₀) : (u⁻¹ : G₀) * u = 1 := inv_mul_cancel u.ne_zero @[simp] lemma mk0_inj {a b : G₀} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ @[simp] lemma exists_iff_ne_zero {x : G₀} : (∃ u : units G₀, ↑u = x) ↔ x ≠ 0 := ⟨λ ⟨u, hu⟩, hu ▸ u.ne_zero, assume hx, ⟨mk0 x hx, rfl⟩⟩ end units section group_with_zero variables [group_with_zero G₀] lemma is_unit.mk0 (x : G₀) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) lemma is_unit_iff_ne_zero {x : G₀} : is_unit x ↔ x ≠ 0 := units.exists_iff_ne_zero @[priority 10] -- see Note [lower instance priority] instance group_with_zero.no_zero_divisors : no_zero_divisors G₀ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin classical, contrapose! h, exact ((units.mk0 a h.1) * (units.mk0 b h.2)).ne_zero end, .. (‹_› : group_with_zero G₀) } @[priority 10] -- see Note [lower instance priority] instance group_with_zero.cancel_monoid_with_zero : cancel_monoid_with_zero G₀ := { mul_left_cancel_of_ne_zero := λ x y z hx h, by rw [← inv_mul_cancel_left' hx y, h, inv_mul_cancel_left' hx z], mul_right_cancel_of_ne_zero := λ x y z hy h, by rw [← mul_inv_cancel_right' hy x, h, mul_inv_cancel_right' hy z], .. (‹_› : group_with_zero G₀) } lemma mul_inv_rev' (x y : G₀) : (x * y)⁻¹ = y⁻¹ * x⁻¹ := begin classical, by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, symmetry, apply eq_inv_of_mul_left_eq_one, simp [mul_assoc, hx, hy] end @[simp] lemma div_self {a : G₀} (h : a ≠ 0) : a / a = 1 := mul_inv_cancel h @[simp] lemma div_one (a : G₀) : a / 1 = a := by simp [div_eq_mul_inv] @[simp] lemma one_div (a : G₀) : 1 / a = a⁻¹ := one_mul _ @[simp] lemma zero_div (a : G₀) : 0 / a = 0 := zero_mul _ @[simp] lemma div_zero (a : G₀) : a / 0 = 0 := show a * 0⁻¹ = 0, by rw [inv_zero, mul_zero] @[simp] lemma div_mul_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a / b * b = a := inv_mul_cancel_right' h a lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a := classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a) @[simp] lemma mul_div_cancel (a : G₀) {b : G₀} (h : b ≠ 0) : a * b / b = a := mul_inv_cancel_right' h a lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a := classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a) lemma mul_div_assoc {a b c : G₀} : a * b / c = a * (b / c) := mul_assoc _ _ _ local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm lemma div_eq_mul_one_div (a b : G₀) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel {a : G₀} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel {a : G₀} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:G₀) := div_self (ne.symm zero_ne_one) lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := by simpa only [one_div] using inv_ne_zero h lemma eq_one_div_of_mul_eq_one {a b : G₀} (h : a * b = 1) : b = 1 / a := by simpa only [one_div] using eq_inv_of_mul_right_eq_one h lemma eq_one_div_of_mul_eq_one_left {a b : G₀} (h : b * a = 1) : b = 1 / a := by simpa only [one_div] using eq_inv_of_mul_left_eq_one h @[simp] lemma one_div_div (a b : G₀) : 1 / (a / b) = b / a := by rw [one_div, div_eq_mul_inv, mul_inv_rev', inv_inv', div_eq_mul_inv] lemma one_div_one_div (a : G₀) : 1 / (1 / a) = a := by simp lemma eq_of_one_div_eq_one_div {a b : G₀} (h : 1 / a = 1 / b) : a = b := by rw [← one_div_one_div a, h, one_div_one_div] variables {a b c : G₀} @[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 := by rw [inv_eq_iff, inv_zero, eq_comm] @[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a := eq_comm.trans $ inv_eq_zero.trans eq_comm lemma one_div_mul_one_div_rev (a b : G₀) : (1 / a) * (1 / b) = 1 / (b * a) := by simp only [div_eq_mul_inv, one_mul, mul_inv_rev'] theorem divp_eq_div (a : G₀) (u : units G₀) : a /ₚ u = a / u := congr_arg _ $ u.coe_inv' @[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div : (a / b)⁻¹ = b / a := (mul_inv_rev' _ _).trans (by rw inv_inv'; refl) lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_rev' _ _).symm lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := mul_ne_zero ha (inv_ne_zero hb) @[simp] lemma div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = 0:= by simp [div_eq_mul_inv] lemma div_ne_zero_iff : a / b ≠ 0 ↔ a ≠ 0 ∧ b ≠ 0 := (not_congr div_eq_zero_iff).trans not_or_distrib lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_left_inj] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b := by rw [eq_comm, div_eq_iff_mul_eq hc] lemma div_eq_of_eq_mul {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : y = z * x) : y / x = z := (div_eq_iff_mul_eq hx).2 h.symm lemma eq_div_of_mul_eq {x : G₀} (hx : x ≠ 0) {y z : G₀} (h : z * x = y) : z = y / x := eq.symm $ div_eq_of_eq_mul hx h.symm lemma eq_of_div_eq_one (h : a / b = 1) : a = b := begin classical, by_cases hb : b = 0, { rw [hb, div_zero] at h, exact eq_of_zero_eq_one h a b }, { rwa [div_eq_iff_mul_eq hb, one_mul, eq_comm] at h } end lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b := ⟨eq_of_div_eq_one, λ h, h.symm ▸ div_self hb⟩ lemma div_mul_left {a b : G₀} (hb : b ≠ 0) : b / (a * b) = 1 / a := by simp only [div_eq_mul_inv, mul_inv_rev', mul_inv_cancel_left' hb, one_mul] lemma mul_div_mul_right (a b : G₀) {c : G₀} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by simp only [div_eq_mul_inv, mul_inv_rev', mul_assoc, mul_inv_cancel_left' hc] lemma mul_mul_div (a : G₀) {b : G₀} (hb : b ≠ 0) : a = a * b * (1 / b) := by simp [hb] end group_with_zero section comm_group_with_zero -- comm variables [comm_group_with_zero G₀] {a b c : G₀} @[priority 10] -- see Note [lower instance priority] instance comm_group_with_zero.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero G₀ := { ..group_with_zero.cancel_monoid_with_zero, ..comm_group_with_zero.to_comm_monoid_with_zero G₀ } /-- Pullback a `comm_group_with_zero` class along an injective function. -/ protected def function.injective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (f : G₀' → G₀) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : comm_group_with_zero G₀' := { .. hf.group_with_zero f zero one mul inv, .. hf.comm_semigroup f mul } /-- Pushforward a `comm_group_with_zero` class along an surjective function. -/ protected def function.surjective.comm_group_with_zero [has_zero G₀'] [has_mul G₀'] [has_one G₀'] [has_inv G₀'] (h01 : (0:G₀') ≠ 1) (f : G₀ → G₀') (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f x⁻¹ = (f x)⁻¹) : comm_group_with_zero G₀' := { .. hf.group_with_zero h01 f zero one mul inv, .. hf.comm_semigroup f mul } lemma mul_inv' : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev', mul_comm] lemma one_div_mul_one_div (a b : G₀) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div_rev, mul_comm b] lemma div_mul_right {a : G₀} (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := by rw [mul_comm, div_mul_left ha] lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b := by rw [mul_comm, mul_div_cancel_of_imp h] lemma mul_div_cancel_left {a : G₀} (b : G₀) (ha : a ≠ 0) : a * b / a = b := mul_div_cancel_left_of_imp $ λ h, (ha h).elim lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a := by rw [mul_comm, div_mul_cancel_of_imp h] lemma mul_div_cancel' (a : G₀) {b : G₀} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] local attribute [simp] mul_assoc mul_comm mul_left_comm lemma div_mul_div (a b c d : G₀) : (a / b) * (c / d) = (a * c) / (b * d) := by { simp [div_eq_mul_inv], rw [mul_inv_rev', mul_comm d⁻¹] } lemma mul_div_mul_left (a b : G₀) {c : G₀} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [mul_comm c, mul_comm c, mul_div_mul_right _ _ hc] @[field_simps] lemma div_mul_eq_mul_div (a b c : G₀) : (b / c) * a = (b * a) / c := by simp [div_eq_mul_inv] lemma div_mul_eq_mul_div_comm (a b c : G₀) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div, div_one, one_mul] lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb, ← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd] @[field_simps] lemma div_div_eq_mul_div (a b c : G₀) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc] @[field_simps] lemma div_div_eq_div_mul (a b c : G₀) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a : G₀) {b c d : G₀} : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_mul_eq_div_mul_one_div (a b c : G₀) : a / (b * c) = (a / b) * (1 / c) := by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div] /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_div_self (a : G₀) : a / (a / a) = a := begin rw div_div_eq_mul_div, exact mul_self_div_self a end lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (assume ha, ha) (assume ha, ((one_div_ne_zero ha) h).elim) lemma div_helper {a : G₀} (b : G₀) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h] end comm_group_with_zero section comm_group_with_zero variables [comm_group_with_zero G₀] {a b c d : G₀} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma mul_div_right_comm (a b c : G₀) : (a * b) / c = (a / c) * b := by rw [div_eq_mul_inv, mul_assoc, mul_comm b, ← mul_assoc]; refl lemma mul_comm_div' (a b c : G₀) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm' (a b c : G₀) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : G₀) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma div_right_comm (a : G₀) : (a / b) / c = (a / c) / b := by rw [div_div_eq_div_mul, div_div_eq_div_mul, mul_comm] lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [div_div_eq_mul_div, div_mul_cancel _ hc] lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] @[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := calc a / b = c / d ↔ a / b * (b * d) = c / d * (b * d) : by rw [mul_left_inj' (mul_ne_zero hb hd)] ... ↔ a * d = c * b : by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] @[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div, mul_div_cancel' _ ha] end comm_group_with_zero namespace semiconj_by @[simp] lemma zero_right [mul_zero_class G₀] (a : G₀) : semiconj_by a 0 0 := by simp only [semiconj_by, mul_zero, zero_mul] @[simp] lemma zero_left [mul_zero_class G₀] (x y : G₀) : semiconj_by 0 x y := by simp only [semiconj_by, mul_zero, zero_mul] variables [group_with_zero G₀] {a x y x' y' : G₀} @[simp] lemma inv_symm_left_iff' : semiconj_by a⁻¹ x y ↔ semiconj_by a y x := classical.by_cases (λ ha : a = 0, by simp only [ha, inv_zero, semiconj_by.zero_left]) (λ ha, @units_inv_symm_left_iff _ _ (units.mk0 a ha) _ _) lemma inv_symm_left' (h : semiconj_by a x y) : semiconj_by a⁻¹ y x := semiconj_by.inv_symm_left_iff'.2 h lemma inv_right' (h : semiconj_by a x y) : semiconj_by a x⁻¹ y⁻¹ := begin classical, by_cases ha : a = 0, { simp only [ha, zero_left] }, by_cases hx : x = 0, { subst x, simp only [semiconj_by, mul_zero, @eq_comm _ _ (y * a), mul_eq_zero] at h, simp [h.resolve_right ha] }, { have := mul_ne_zero ha hx, rw [h.eq, mul_ne_zero_iff] at this, exact @units_inv_right _ _ _ (units.mk0 x hx) (units.mk0 y this.1) h }, end @[simp] lemma inv_right_iff' : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y := ⟨λ h, inv_inv' x ▸ inv_inv' y ▸ h.inv_right', inv_right'⟩ lemma div_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x / x') (y / y') := h.mul_right h'.inv_right' end semiconj_by namespace commute @[simp] theorem zero_right [mul_zero_class G₀] (a : G₀) :commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left [mul_zero_class G₀] (a : G₀) : commute 0 a := semiconj_by.zero_left a a variables [group_with_zero G₀] {a b c : G₀} @[simp] theorem inv_left_iff' : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff' theorem inv_left' (h : commute a b) : commute a⁻¹ b := inv_left_iff'.2 h @[simp] theorem inv_right_iff' : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff' theorem inv_right' (h : commute a b) : commute a b⁻¹ := inv_right_iff'.2 h theorem inv_inv' (h : commute a b) : commute a⁻¹ b⁻¹ := h.inv_left'.inv_right' @[simp] theorem div_right (hab : commute a b) (hac : commute a c) : commute a (b / c) := hab.div_right hac @[simp] theorem div_left (hac : commute a c) (hbc : commute b c) : commute (a / b) c := hac.mul_left hbc.inv_left' end commute namespace monoid_hom variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero M₀] [nontrivial M₀] section monoid_with_zero variables (f : G₀ →* M₀) (h0 : f 0 = 0) {a : G₀} include h0 lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 := ⟨λ hfa ha, hfa $ ha.symm ▸ h0, λ ha, ((is_unit.mk0 a ha).map f).ne_zero⟩ lemma map_eq_zero : f a = 0 ↔ a = 0 := by { classical, exact not_iff_not.1 (f.map_ne_zero h0) } end monoid_with_zero section group_with_zero variables (f : G₀ →* G₀') (h0 : f 0 = 0) (a b : G₀) include h0 /-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/ lemma map_inv' : f a⁻¹ = (f a)⁻¹ := begin classical, by_cases h : a = 0, by simp [h, h0], apply eq_inv_of_mul_left_eq_one, rw [← f.map_mul, inv_mul_cancel h, f.map_one] end lemma map_div : f (a / b) = f a / f b := (f.map_mul _ _).trans $ _root_.congr_arg _ $ f.map_inv' h0 b omit h0 @[simp] lemma map_units_inv {M G₀ : Type*} [monoid M] [group_with_zero G₀] (f : M →* G₀) (u : units M) : f ↑u⁻¹ = (f u)⁻¹ := by rw [← units.coe_map, ← units.coe_map, ← units.coe_inv', map_inv] end group_with_zero end monoid_hom
1e58622d62540e45411779d6dc9202f3a1b49f73
ce4db867008cc96ee6ea6a34d39c2fa7c6ccb536
/src/tactiques.lean
eb0e959c865d649141744279420caa9f2d2be99e
[]
no_license
PatrickMassot/lean-bavard
ab0ceedd6bab43dc0444903a80b911c5fbfb23c3
92a1a8c7ff322e4f575ec709b8c5348990d64f18
refs/heads/master
1,679,565,084,665
1,616,158,570,000
1,616,158,570,000
348,144,867
1
1
null
null
null
null
UTF-8
Lean
false
false
99
lean
import .interactive_expr import .tokens import .Soit .Montrons .On .Par .Posons .Supposons .Fait
f75ff36b9ca257876f3d7972533ba15b71f2593f
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/13_More_Tactics.org.11.lean
179fc3147fd58fdf951172eead38c827d36fcf33
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
218
lean
import standard variable p : nat → Prop variable q : nat → Prop variables a b c : nat example : p c → p b → q b → p a → ∃ x, p x ∧ q x := by intros; apply exists.intro; split; eassumption; eassumption
a49af8d1f63e4cb5f86e650966cb50f55bf36d4f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/category/NonemptyFinLinOrd.lean
ce6b0d711c3c1be8cd1f17fb24c9ad50cbacfc34
[]
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,168
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.sort import Mathlib.data.fin import Mathlib.order.category.LinearOrder import Mathlib.PostPort universes u_1 l u v namespace Mathlib /-! # Nonempty finite linear orders Nonempty finite linear orders form the index category for simplicial objects. -/ /-- A typeclass for nonempty finite linear orders. -/ class nonempty_fin_lin_ord (α : Type u_1) extends order_bot α, fintype α, order_top α, linear_order α where protected instance punit.nonempty_fin_lin_ord : nonempty_fin_lin_ord PUnit := nonempty_fin_lin_ord.mk (fintype.elems PUnit) fintype.complete linear_ordered_cancel_add_comm_monoid.le linear_ordered_cancel_add_comm_monoid.lt linear_ordered_cancel_add_comm_monoid.le_refl linear_ordered_cancel_add_comm_monoid.le_trans linear_ordered_cancel_add_comm_monoid.le_antisymm linear_ordered_cancel_add_comm_monoid.le_total linear_ordered_cancel_add_comm_monoid.decidable_le linear_ordered_cancel_add_comm_monoid.decidable_eq linear_ordered_cancel_add_comm_monoid.decidable_lt PUnit.unit sorry PUnit.unit sorry protected instance fin.nonempty_fin_lin_ord (n : ℕ) : nonempty_fin_lin_ord (fin (n + 1)) := nonempty_fin_lin_ord.mk (fintype.elems (fin (n + 1))) sorry linear_order.le linear_order.lt sorry sorry sorry sorry linear_order.decidable_le linear_order.decidable_eq linear_order.decidable_lt 0 fin.zero_le (fin.last n) fin.le_last protected instance ulift.nonempty_fin_lin_ord (α : Type u) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (ulift α) := nonempty_fin_lin_ord.mk (fintype.elems (ulift α)) sorry linear_order.le linear_order.lt sorry sorry sorry sorry linear_order.decidable_le linear_order.decidable_eq linear_order.decidable_lt (ulift.up ⊥) sorry (ulift.up ⊤) sorry /-- The category of nonempty finite linear orders. -/ def NonemptyFinLinOrd := category_theory.bundled nonempty_fin_lin_ord namespace NonemptyFinLinOrd protected instance nonempty_fin_lin_ord.to_linear_order.category_theory.bundled_hom.parent_projection : category_theory.bundled_hom.parent_projection nonempty_fin_lin_ord.to_linear_order := category_theory.bundled_hom.parent_projection.mk protected instance large_category : category_theory.large_category NonemptyFinLinOrd := category_theory.bundled_hom.category (category_theory.bundled_hom.map_hom (category_theory.bundled_hom.map_hom (category_theory.bundled_hom.map_hom preorder_hom partial_order.to_preorder) linear_order.to_partial_order) nonempty_fin_lin_ord.to_linear_order) /-- Construct a bundled NonemptyFinLinOrd from the underlying type and typeclass. -/ def of (α : Type u_1) [nonempty_fin_lin_ord α] : NonemptyFinLinOrd := category_theory.bundled.of α protected instance inhabited : Inhabited NonemptyFinLinOrd := { default := of PUnit } protected instance nonempty_fin_lin_ord (α : NonemptyFinLinOrd) : nonempty_fin_lin_ord ↥α := category_theory.bundled.str α
6c66b83eb57d4a2d650f7ef83ab26c7d17df5bbb
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/tactic/interactive.lean
9e454f1b9eb50461b507d18588336719c5bdd29d
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
21,972
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import data.dlist data.dlist.basic data.prod category.basic tactic.basic tactic.rcases tactic.generalize_proofs tactic.split_ifs logic.basic tactic.ext tactic.tauto tactic.replacer open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. `rcases` also has special support for quotient types: quotient induction into Prop works like matching on the constructor `quot.mk`. `rcases? e` will perform case splits on `e` in the same way as `rcases e`, but rather than accepting a pattern, it does a maximal cases and prints the pattern that would produce this case splitting. The default maximum depth is 5, but this can be modified with `rcases? e : n`. -/ meta def rcases : parse rcases_parse → tactic unit | (p, sum.inl ids) := tactic.rcases p ids | (p, sum.inr depth) := do patt ← tactic.rcases_hint p depth, pe ← pp p, trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt /-- The `rintro` tactic is a combination of the `intros` tactic with `rcases` to allow for destructuring patterns while introducing variables. See `rcases` for a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩` will introduce two variables, and then do case splits on both of them producing two subgoals, one with variables `a d e` and the other with `b c d e`. `rintro?` will introduce and case split on variables in the same way as `rintro`, but will also print the `rintro` invocation that would have the same result. Like `rcases?`, `rintro? : n` allows for modifying the depth of splitting; the default is 5. -/ meta def rintro : parse rintro_parse → tactic unit | (sum.inl []) := intros [] | (sum.inl l) := tactic.rintro l | (sum.inr depth) := do ps ← tactic.rintro_hint depth, trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p, format.space ++ format.group (p.format tt)) /-- Alias for `rintro`. -/ meta def rintros := rintro /-- This is a "finishing" tactic modification of `simp`. The tactic `simpa [rules, ...] using e` will simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and try to close the goal using `assumption`. If `e` is a term instead of a local constant, it is first added to the local context using `have`. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at (lc) := try (simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg) >> (assumption <|> trivial) in match tgt with | none := get_local `this >> simp_at [some `this, none] <|> simp_at [none] | some e := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, match e with | local_const _ lc _ _ := simp_at [some lc, none] | e := do t ← infer_type e, assertv `this t e >> simp_at [some `this, none] end end /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [``coe,``lift_t,``has_lift_t.lift,``coe_t,``has_coe_t.coe,``coe_b,``has_coe.coe, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the currently declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs : parse ident_* → tactic unit := tactic.generalize_proofs /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core >> all_goals (reflexivity <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. alternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`, after the main approach failed, the goal is dismissed and `sg₀` and `sg₁` are made into the new goal. optional arguments: - asms: list of rules to consider instead of the local constants - tac: a tactic to run on each subgoals after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (asms : option (list expr) := none) (tac : tactic unit := return ()) : tactic unit := tactic.apply_assumption asms tac open nat /-- `solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches and repeated calls `apply_assumption` on the generated subgoals until no subgoals remains or up to `depth` times. `solve_by_elim` discharges the current goal or fails `solve_by_elim` does some back-tracking if `apply_assumption` chooses an unproductive assumption optional arguments: - discharger: a subsidiary tactic to try at each step (`cc` is often helpful) - asms: list of assumptions / rules to consider instead of local constants - depth: number of attempts at discharging generated sub-goals The optional arguments can be specified as ``solve_by_elim { discharger := `[cc] }``. -/ meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := tactic.solve_by_elim opt /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology := tactic.tautology /-- Shorter name for the tactic `tautology`. -/ meta def tauto := tautology private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], congr' n, gs' ← get_goals, set_goals $ gs' ++ gs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> to_expr ``(@id %%(expr.sort u : expr)), t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) end interactive end tactic
b688925a9a02588ee46c23b745005f140c78355c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/inner_product_space/lax_milgram.lean
b7ed91982ec9e44c3914459a6a27b875934cf083
[ "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,653
lean
/- Copyright (c) 2022 Daniel Roca González. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Roca González -/ import analysis.inner_product_space.projection import analysis.inner_product_space.dual import analysis.normed_space.banach import analysis.normed_space.operator_norm import topology.metric_space.antilipschitz /-! # The Lax-Milgram Theorem We consider an Hilbert space `V` over `ℝ` equipped with a bounded bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ`. Recall that a bilinear form `B : V →L[ℝ] V →L[ℝ] ℝ` is *coercive* iff `∃ C, (0 < C) ∧ ∀ u, C * ‖u‖ * ‖u‖ ≤ B u u`. Under the hypothesis that `B` is coercive we prove the Lax-Milgram theorem: that is, the map `inner_product_space.continuous_linear_map_of_bilin` from `analysis.inner_product_space.dual` can be upgraded to a continuous equivalence `is_coercive.continuous_linear_equiv_of_bilin : V ≃L[ℝ] V`. ## References * We follow the notes of Peter Howard's Spring 2020 *M612: Partial Differential Equations* lecture, see[howard] ## Tags dual, Lax-Milgram -/ noncomputable theory open is_R_or_C linear_map continuous_linear_map inner_product_space linear_map (ker range) open_locale real_inner_product_space nnreal universe u namespace is_coercive variables {V : Type u} [inner_product_space ℝ V] [complete_space V] variables {B : V →L[ℝ] V →L[ℝ] ℝ} local postfix `♯`:1025 := @continuous_linear_map_of_bilin ℝ V _ _ _ lemma bounded_below (coercive : is_coercive B) : ∃ C, 0 < C ∧ ∀ v, C * ‖v‖ ≤ ‖B♯ v‖ := begin rcases coercive with ⟨C, C_ge_0, coercivity⟩, refine ⟨C, C_ge_0, _⟩, intro v, by_cases h : 0 < ‖v‖, { refine (mul_le_mul_right h).mp _, calc C * ‖v‖ * ‖v‖ ≤ B v v : coercivity v ... = ⟪B♯ v, v⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B v v).symm ... ≤ ‖B♯ v‖ * ‖v‖ : real_inner_le_norm (B♯ v) v, }, { have : v = 0 := by simpa using h, simp [this], } end lemma antilipschitz (coercive : is_coercive B) : ∃ C : ℝ≥0, 0 < C ∧ antilipschitz_with C B♯ := begin rcases coercive.bounded_below with ⟨C, C_pos, below_bound⟩, refine ⟨(C⁻¹).to_nnreal, real.to_nnreal_pos.mpr (inv_pos.mpr C_pos), _⟩, refine continuous_linear_map.antilipschitz_of_bound B♯ _, simp_rw [real.coe_to_nnreal', max_eq_left_of_lt (inv_pos.mpr C_pos), ←inv_mul_le_iff (inv_pos.mpr C_pos)], simpa using below_bound, end lemma ker_eq_bot (coercive : is_coercive B) : ker B♯ = ⊥ := begin rw [linear_map_class.ker_eq_bot], rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩, exact antilipschitz.injective, end lemma closed_range (coercive : is_coercive B) : is_closed (range B♯ : set V) := begin rcases coercive.antilipschitz with ⟨_, _, antilipschitz⟩, exact antilipschitz.is_closed_range B♯.uniform_continuous, end lemma range_eq_top (coercive : is_coercive B) : range B♯ = ⊤ := begin haveI := coercive.closed_range.complete_space_coe, rw ← (range B♯).orthogonal_orthogonal, rw submodule.eq_top_iff', intros v w mem_w_orthogonal, rcases coercive with ⟨C, C_pos, coercivity⟩, obtain rfl : w = 0, { rw [←norm_eq_zero, ←mul_self_eq_zero, ←mul_right_inj' C_pos.ne', mul_zero, ←mul_assoc], apply le_antisymm, { calc C * ‖w‖ * ‖w‖ ≤ B w w : coercivity w ... = ⟪B♯ w, w⟫_ℝ : (continuous_linear_map_of_bilin_apply ℝ B w w).symm ... = 0 : mem_w_orthogonal _ ⟨w, rfl⟩ }, { exact mul_nonneg (mul_nonneg C_pos.le (norm_nonneg w)) (norm_nonneg w) } }, exact inner_zero_left, end /-- The Lax-Milgram equivalence of a coercive bounded bilinear operator: for all `v : V`, `continuous_linear_equiv_of_bilin B v` is the unique element `V` such that `⟪continuous_linear_equiv_of_bilin B v, w⟫ = B v w`. The Lax-Milgram theorem states that this is a continuous equivalence. -/ def continuous_linear_equiv_of_bilin (coercive : is_coercive B) : V ≃L[ℝ] V := continuous_linear_equiv.of_bijective B♯ coercive.ker_eq_bot coercive.range_eq_top @[simp] lemma continuous_linear_equiv_of_bilin_apply (coercive : is_coercive B) (v w : V) : ⟪coercive.continuous_linear_equiv_of_bilin v, w⟫_ℝ = B v w := continuous_linear_map_of_bilin_apply ℝ B v w lemma unique_continuous_linear_equiv_of_bilin (coercive : is_coercive B) {v f : V} (is_lax_milgram : (∀ w, ⟪f, w⟫_ℝ = B v w)) : f = coercive.continuous_linear_equiv_of_bilin v := unique_continuous_linear_map_of_bilin ℝ B is_lax_milgram end is_coercive
3358fcfa5e4c4c737c5fce67915ed5689bf57b40
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world8/level2.lean
357c20506c55b12554e84db094d55faaa571fcd2
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
198
lean
import mynat.definition namespace mynat theorem succ_succ_inj (a b : mynat) (h : succ(succ(a)) = succ(succ(b))) : a = b := begin apply succ_inj, apply succ_inj, exact h, end end mynat
3552bd065424a2263d18f92744e7c5f8d91044d9
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp23.lean
05aa0f6ed91bc5a318fbd0088d92b964816fdd4a
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,227
lean
variable vec : Nat → Type variable concat {n m : Nat} (v : vec n) (w : vec m) : vec (n + m) infixl 65 ; : concat axiom concat_assoc {n1 n2 n3 : Nat} (v1 : vec n1) (v2 : vec n2) (v3 : vec n3) : (v1 ; v2) ; v3 = cast (to_heq (congr2 vec (symm (Nat::add_assoc n1 n2 n3)))) (v1 ; (v2 ; v3)) variable empty : vec 0 axiom concat_empty {n : Nat} (v : vec n) : v ; empty = cast (to_heq (congr2 vec (symm (Nat::add_zeror n)))) v rewrite_set simple add_rewrite concat_assoc concat_empty Nat::add_assoc Nat::add_zeror and_truer eq_id : simple universe M >= 1 definition TypeM := (Type M) variable n : Nat variable v : vec n variable w : vec n variable f {A : TypeM} : A → A variable p {A : TypeM} : A → Bool axiom fax {n m : Nat} (v : vec n) (w : vec m) : f (v; (w; v)) = v; (w; v) add_rewrite fax : simple (* local opts = options({"simplifier", "heq"}, true) local t = parse_lean([[ p (f ((v ; w) ; empty ; (v ; empty))) ∧ v = cast (to_heq (congr2 vec (Nat::add_zeror n))) (v ; empty) ]]) print(t) print("===>") local t2, pr = simplify(t, "simple", opts) print(t2) print("checking proof") print (get_environment():type_check(pr)) *)
d9e773d53aafcfa38c1c39790435a3c7b0dee5bf
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/algebra/ring_bigops.lean
d0ac89458c498048be83e5f65896ab0f3b3f6ade
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
6,130
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Properties of finite sums and products in various structures, including ordered rings and fields. There are two versions of every theorem: one for finsets, and one for finite sets. -/ import .group_bigops .ordered_field variables {A B : Type} variable [deceqA : decidable_eq A] /- -- finset versions -/ namespace finset section comm_semiring variable [csB : comm_semiring B] include deceqA csB proposition mul_Sum (f : A → B) {s : finset A} (b : B) : b * (∑ x ∈ s, f x) = ∑ x ∈ s, b * f x := begin induction s with a s ans ih, {rewrite [+Sum_empty, mul_zero]}, rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem (λ x, b * f x) ans], rewrite [-ih, left_distrib] end proposition Sum_mul (f : A → B) {s : finset A} (b : B) : (∑ x ∈ s, f x) * b = ∑ x ∈ s, f x * b := by rewrite [mul.comm _ b, mul_Sum]; apply Sum_ext; intros; apply mul.comm proposition Prod_eq_zero (f : A → B) {s : finset A} {a : A} (H : a ∈ s) (fa0 : f a = 0) : (∏ x ∈ s, f x) = 0 := begin induction s with b s bns ih, {exact absurd H !not_mem_empty}, rewrite [Prod_insert_of_not_mem f bns], have a = b ∨ a ∈ s, from eq_or_mem_of_mem_insert H, cases this with aeqb ains, {rewrite [-aeqb, fa0, zero_mul]}, rewrite [ih ains, mul_zero] end end comm_semiring section ordered_comm_group variable [ocgB : ordered_comm_group B] include deceqA ocgB proposition Sum_le_Sum (f g : A → B) {s : finset A} (H: ∀ x, x ∈ s → f x ≤ g x) : (∑ x ∈ s, f x) ≤ (∑ x ∈ s, g x) := begin induction s with a s ans ih, {exact le.refl _}, have H1 : f a ≤ g a, from H _ !mem_insert, have H2 : (∑ x ∈ s, f x) ≤ (∑ x ∈ s, g x), from ih (forall_of_forall_insert H), rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem g ans], apply add_le_add H1 H2 end proposition Sum_nonneg (f : A → B) {s : finset A} (H : ∀x, x ∈ s → f x ≥ 0) : (∑ x ∈ s, f x) ≥ 0 := calc 0 = (∑ x ∈ s, 0) : Sum_zero ... ≤ (∑ x ∈ s, f x) : Sum_le_Sum (λ x, 0) f H proposition Sum_nonpos (f : A → B) {s : finset A} (H : ∀x, x ∈ s → f x ≤ 0) : (∑ x ∈ s, f x) ≤ 0 := calc 0 = (∑ x ∈ s, 0) : Sum_zero ... ≥ (∑ x ∈ s, f x) : Sum_le_Sum f (λ x, 0) H end ordered_comm_group section decidable_linear_ordered_comm_group variable [dloocgB : decidable_linear_ordered_comm_group B] include deceqA dloocgB proposition abs_Sum_le (f : A → B) (s : finset A) : abs (∑ x ∈ s, f x) ≤ (∑ x ∈ s, abs (f x)) := begin induction s with a s ans ih, {rewrite [+Sum_empty, abs_zero], apply le.refl}, rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem _ ans], apply le.trans, apply abs_add_le_abs_add_abs, apply add_le_add_left ih end end decidable_linear_ordered_comm_group end finset /- -- set versions -/ namespace set open classical section comm_semiring variable [csB : comm_semiring B] include csB proposition mul_Sum (f : A → B) {s : set A} (b : B) : b * (∑ x ∈ s, f x) = ∑ x ∈ s, b * f x := begin cases (em (finite s)) with fins nfins, rotate 1, {rewrite [+Sum_of_not_finite nfins, mul_zero]}, induction fins with a s fins ans ih, {rewrite [+Sum_empty, mul_zero]}, rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem (λ x, b * f x) ans], rewrite [-ih, left_distrib] end proposition Sum_mul (f : A → B) {s : set A} (b : B) : (∑ x ∈ s, f x) * b = ∑ x ∈ s, f x * b := by rewrite [mul.comm _ b, mul_Sum]; apply Sum_ext; intros; apply mul.comm proposition Prod_eq_zero (f : A → B) {s : set A} [fins : finite s] {a : A} (H : a ∈ s) (fa0 : f a = 0) : (∏ x ∈ s, f x) = 0 := begin induction fins with b s fins bns ih, {exact absurd H !not_mem_empty}, rewrite [Prod_insert_of_not_mem f bns], have a = b ∨ a ∈ s, from eq_or_mem_of_mem_insert H, cases this with aeqb ains, {rewrite [-aeqb, fa0, zero_mul]}, rewrite [ih ains, mul_zero] end end comm_semiring section ordered_comm_group variable [ocgB : ordered_comm_group B] include ocgB proposition Sum_le_Sum (f g : A → B) {s : set A} (H: ∀₀ x ∈ s, f x ≤ g x) : (∑ x ∈ s, f x) ≤ (∑ x ∈ s, g x) := begin cases (em (finite s)) with fins nfins, {induction fins with a s fins ans ih, {rewrite +Sum_empty; apply le.refl}, {rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem g ans], have H1 : f a ≤ g a, from H !mem_insert, have H2 : (∑ x ∈ s, f x) ≤ (∑ x ∈ s, g x), from ih (forall_of_forall_insert H), apply add_le_add H1 H2}}, rewrite [+Sum_of_not_finite nfins], apply le.refl end proposition Sum_nonneg (f : A → B) {s : set A} (H : ∀₀ x ∈ s, f x ≥ 0) : (∑ x ∈ s, f x) ≥ 0 := calc 0 = (∑ x ∈ s, 0) : Sum_zero ... ≤ (∑ x ∈ s, f x) : Sum_le_Sum (λ x, 0) f H proposition Sum_nonpos (f : A → B) {s : set A} (H : ∀₀ x ∈ s, f x ≤ 0) : (∑ x ∈ s, f x) ≤ 0 := calc 0 = (∑ x ∈ s, 0) : Sum_zero ... ≥ (∑ x ∈ s, f x) : Sum_le_Sum f (λ x, 0) H end ordered_comm_group section decidable_linear_ordered_comm_group variable [dloocgB : decidable_linear_ordered_comm_group B] include deceqA dloocgB proposition abs_Sum_le (f : A → B) (s : set A) : abs (∑ x ∈ s, f x) ≤ (∑ x ∈ s, abs (f x)) := begin cases (em (finite s)) with fins nfins, rotate 1, {rewrite [+Sum_of_not_finite nfins, abs_zero], apply le.refl}, induction fins with a s fins ans ih, {rewrite [+Sum_empty, abs_zero], apply le.refl}, rewrite [Sum_insert_of_not_mem f ans, Sum_insert_of_not_mem _ ans], apply le.trans, apply abs_add_le_abs_add_abs, apply add_le_add_left ih end end decidable_linear_ordered_comm_group end set
898e679ec952a45c2500c025ede7e8bb69ead444
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/div_wf.lean
23ba2c665d781a5bc7e53ccf95e2d42ec03c656d
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,739
lean
open nat well_founded decidable prod set_option pp.all true -- Auxiliary lemma used to justify recursive call private definition lt_aux {x y : nat} (H : 0 < y ∧ y ≤ x) : x - y < x := and.rec_on H (λ ypos ylex, sub_lt (nat.lt_of_lt_of_le ypos ylex) ypos) definition wdiv.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (lt_aux H) y + 1 else 0 definition wdiv (x y : nat) := fix lt_wf wdiv.F x y theorem wdiv_def (x y : nat) : wdiv x y = if H : 0 < y ∧ y ≤ x then wdiv (x - y) y + 1 else 0 := congr_fun (well_founded.fix_eq lt_wf wdiv.F x) y /- See comment at fib_wrec. example : wdiv 5 2 = 2 := rfl example : wdiv 9 3 = 3 := rfl -/ -- There is a little bit of cheating in the definition above. -- I avoid the packing/unpacking into tuples. -- The actual definitional package would not do that. -- It will always pack things. definition pair_nat.lt := lex nat.lt nat.lt -- Could also be (lex lt empty_rel) definition pair_nat.lt.wf : well_founded pair_nat.lt := prod.lex_wf lt_wf lt_wf infixl `≺`:50 := pair_nat.lt -- Recursive lemma used to justify recursive call definition plt_aux (x y : nat) (H : 0 < y ∧ y ≤ x) : (x - y, y) ≺ (x, y) := lex.left _ _ (lt_aux H) definition pdiv.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat := prod.cases_on p₁ (λ x y f, if H : 0 < y ∧ y ≤ x then f (x - y, y) (plt_aux x y H) + 1 else 0) definition pdiv (x y : nat) := fix pair_nat.lt.wf pdiv.F (x, y) theorem pdiv_def (x y : nat) : pdiv x y = if H : 0 < y ∧ y ≤ x then pdiv (x - y) y + 1 else 0 := well_founded.fix_eq pair_nat.lt.wf pdiv.F (x, y) /- See comment at fib_wrec. example : pdiv 17 2 = 8 := rfl -/
886673e9bacd8ff90bb1a6ab9e6808a28eb91294
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/topology/uniform_space/complete_separated.lean
d598987b8507715440293a958c2b21afde52d9e8
[ "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
1,358
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 Theory of complete separated uniform spaces. This file is for elementary lemmas that depend on both Cauchy filters and separation. -/ import topology.uniform_space.cauchy import topology.uniform_space.separation import topology.dense_embedding open filter open_locale topological_space filter variables {α : Type*} /-In a separated space, a complete set is closed -/ lemma is_complete.is_closed [uniform_space α] [separated_space α] {s : set α} (h : is_complete s) : is_closed s := is_closed_iff_cluster_pt.2 $ λ a ha, begin let f := 𝓝 a ⊓ 𝓟 s, have : cauchy f := cauchy_downwards (cauchy_nhds) ha (inf_le_left), rcases h f this (inf_le_right) with ⟨y, ys, fy⟩, rwa (tendsto_nhds_unique ha inf_le_left fy : a = y) end namespace dense_inducing open filter variables [topological_space α] {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated_space γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_inducing e) (h : ∀ b : β, cauchy (map f (comap e $ 𝓝 b))) : continuous (de.extend f) := de.continuous_extend $ λ b, complete_space.complete (h b) end dense_inducing
3eeef3e755f84fd1d32a017198ecc2350c5ad698
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/sum_bug.lean
0cecf9d7df4c77e3cb4f95cb12036b3217eac84a
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,332
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, Jeremy Avigad import logic open inhabited decidable namespace play -- TODO: take this outside the namespace when the inductive package handles it better inductive sum (A B : Type) : Type := inl : A → sum A B, inr : B → sum A B namespace sum reserve infixr `+`:25 infixr `+` := sum open eq theorem inl_inj {A B : Type} {a1 a2 : A} (H : inl B a1 = inl B a2) : a1 = a2 := let f := λs, rec_on s (λa, a1 = a) (λb, false) in have H1 : f (inl B a1), from rfl, have H2 : f (inl B a2), from subst H H1, H2 theorem inl_neq_inr {A B : Type} {a : A} {b : B} (H : inl B a = inr A b) : false := let f := λs, rec_on s (λa', a = a') (λb, false) in have H1 : f (inl B a), from rfl, have H2 : f (inr A b), from subst H H1, H2 theorem inr_inj {A B : Type} {b1 b2 : B} (H : inr A b1 = inr A b2) : b1 = b2 := let f := λs, rec_on s (λa, false) (λb, b1 = b) in have H1 : f (inr A b1), from rfl, have H2 : f (inr A b2), from subst H H1, H2 theorem sum_inhabited_left [instance] {A B : Type} (H : inhabited A) : inhabited (A + B) := inhabited.mk (inl B (default A)) theorem sum_inhabited_right [instance] {A B : Type} (H : inhabited B) : inhabited (A + B) := inhabited.mk (inr A (default B)) theorem sum_eq_decidable [instance] {A B : Type} (s1 s2 : A + B) (H1 : ∀a1 a2 : A, decidable (inl B a1 = inl B a2)) (H2 : ∀b1 b2 : B, decidable (inr A b1 = inr A b2)) : decidable (s1 = s2) := rec_on s1 (take a1, show decidable (inl B a1 = s2), from rec_on s2 (take a2, show decidable (inl B a1 = inl B a2), from H1 a1 a2) (take b2, have H3 : (inl B a1 = inr A b2) ↔ false, from iff.intro inl_neq_inr (assume H4, false.elim H4), show decidable (inl B a1 = inr A b2), from decidable_of_decidable_of_iff _ (iff.symm H3))) (take b1, show decidable (inr A b1 = s2), from rec_on s2 (take a2, have H3 : (inr A b1 = inl B a2) ↔ false, from iff.intro (assume H4, inl_neq_inr (symm H4)) (assume H4, false.elim H4), show decidable (inr A b1 = inl B a2), from decidable_of_decidable_of_iff _ (iff.symm H3)) (take b2, show decidable (inr A b1 = inr A b2), from H2 b1 b2)) end sum end play
2d1f34caf6917a7ceaf6c311fcba8e3b09d64e00
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/linarith/preprocessing.lean
a8c3b621e165747529ad412b233b10a1d112297f
[ "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
12,230
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.datatypes import tactic.zify import tactic.cancel_denoms /-! # Linarith preprocessing This file contains methods used to preprocess inputs to `linarith`. In particular, `linarith` works over comparisons of the form `t R 0`, where `R ∈ {<,≤,=}`. It assumes that expressions in `t` have integer coefficients and that the type of `t` has well-behaved subtraction. ## Implementation details A `global_preprocessor` is a function `list expr → tactic(list expr)`. Users can add custom preprocessing steps by adding them to the `linarith_config` object. `linarith.default_preprocessors` is the main list, and generally none of these should be skipped unless you know what you're doing. -/ open native tactic expr namespace linarith /-! ### Preprocessing -/ open tactic set_option eqn_compiler.max_steps 50000 /-- If `prf` is a proof of `¬ e`, where `e` is a comparison, `rem_neg prf e` flips the comparison in `e` and returns a proof. For example, if `prf : ¬ a < b`, ``rem_neg prf `(a < b)`` returns a proof of `a ≥ b`. -/ meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := mk_app ``lt_of_not_ge [prf] | `(_ < _) := mk_app ``le_of_not_gt [prf] | `(_ > _) := mk_app ``le_of_not_gt [prf] | `(_ ≥ _) := mk_app ``lt_of_not_ge [prf] | e := failed private meta def rearr_comp_aux : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(%%a > 0) := mk_app `neg_neg_of_pos [prf] | prf `(0 ≥ %%a) := to_expr ``(id_rhs (%%a ≤ 0) %%prf) | prf `(0 > %%a) := to_expr ``(id_rhs (%%a < 0) %%prf) | prf `(0 = %%a) := mk_app `eq.symm [prf] | prf `(0 ≤ %%a) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(0 < %%a) := mk_app `neg_neg_of_pos [prf] | prf `(%%a ≤ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(%%a < %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a = %%b) := mk_app `sub_eq_zero_of_eq [prf] | prf `(%%a > %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a ≥ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp_aux nprf tp | prf a := trace a >> fail "couldn't rearrange comp" /-- `rearr_comp e` takes a proof `e` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`. -/ meta def rearr_comp (e : expr) : tactic expr := infer_type e >>= rearr_comp_aux e /-- If `e` is of the form `((n : ℕ) : ℤ)`, `is_nat_int_coe e` returns `n : ℕ`. -/ meta def is_nat_int_coe : expr → option expr | `(@coe ℕ ℤ %%_ %%n) := some n | _ := none /-- If `e : ℕ`, returns a proof of `0 ≤ (e : ℤ)`. -/ meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] /-- `get_nat_comps e` returns a list of all subexpressions of `e` of the form `((t : ℕ) : ℤ)`. -/ meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end /-- If `pf` is a proof of a strict inequality `(a : ℤ) < b`, `mk_non_strict_int_pf_of_strict_int_pf pf` returns a proof of `a + 1 ≤ b`, and similarly if `pf` proves a negated weak inequality. -/ meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(%%a > %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(¬ %%a ≤ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | `(¬ %%a ≥ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end /-- `is_nat_prop tp` is true iff `tp` is an inequality or equality between natural numbers or the negation thereof. -/ meta def is_nat_prop : expr → bool | `(@eq ℕ %%_ _) := tt | `(@has_le.le ℕ %%_ _ _) := tt | `(@has_lt.lt ℕ %%_ _ _) := tt | `(@ge ℕ %%_ _ _) := tt | `(@gt ℕ %%_ _ _) := tt | `(¬ %%p) := is_nat_prop p | _ := ff /-- `is_strict_int_prop tp` is true iff `tp` is a strict inequality between integers or the negation of a weak inequality between integers. -/ meta def is_strict_int_prop : expr → bool | `(@has_lt.lt ℤ %%_ _ _) := tt | `(@gt ℤ %%_ _ _) := tt | `(¬ @has_le.le ℤ %%_ _ _) := tt | `(¬ @ge ℤ %%_ _ _) := tt | _ := ff private meta def filter_comparisons_aux : expr → bool | `(¬ %%p) := p.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge] | tp := tp.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge, `eq] /-- Removes any expressions that are not proofs of inequalities, equalities, or negations thereof. -/ meta def filter_comparisons : preprocessor := { name := "filter terms that are not proofs of comparisons", transform := λ h, (do tp ← infer_type h, is_prop tp >>= guardb, guardb (filter_comparisons_aux tp), return [h]) <|> return [] } /-- Replaces proofs of negations of comparisons with proofs of the reversed comparisons. For example, a proof of `¬ a < b` will become a proof of `a ≥ b`. -/ meta def remove_negations : preprocessor := { name := "replace negations of comparisons", transform := λ h, do tp ← infer_type h, match tp with | `(¬ %%p) := singleton <$> rem_neg h p | _ := return [h] end } /-- If `h` is an equality or inequality between natural numbers, `nat_to_int` lifts this inequality to the integers. It also adds the facts that the integers involved are nonnegative. To avoid adding the same nonnegativity facts many times, it is a global preprocessor. -/ meta def nat_to_int : global_preprocessor := { name := "move nats to ints", transform := λ l, do l ← l.mmap (λ h, infer_type h >>= guardb ∘ is_nat_prop >> zify_proof [] h <|> return h), nonnegs ← l.mfoldl (λ (es : expr_set) h, do (a, b) ← infer_type h >>= get_rel_sides, return $ (es.insert_list (get_nat_comps a)).insert_list (get_nat_comps b)) mk_rb_set, (++) l <$> nonnegs.to_list.mmap mk_coe_nat_nonneg_prf } /-- `strengthen_strict_int h` turns a proof `h` of a strict integer inequality `t1 < t2` into a proof of `t1 ≤ t2 + 1`. -/ meta def strengthen_strict_int : preprocessor := { name := "strengthen strict inequalities over int", transform := λ h, do tp ← infer_type h, guardb (is_strict_int_prop tp) >> singleton <$> mk_non_strict_int_pf_of_strict_int_pf h <|> return [h] } /-- `mk_comp_with_zero h` takes a proof `h` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≤, <}`. -/ meta def make_comp_with_zero : preprocessor := { name := "make comparisons with zero", transform := λ e, singleton <$> rearr_comp e <|> return [] } /-- `normalize_denominators_in_lhs h lhs` assumes that `h` is a proof of `lhs R 0`. It creates a proof of `lhs' R 0`, where all numeric division in `lhs` has been cancelled. -/ meta def normalize_denominators_in_lhs (h lhs : expr) : tactic expr := do (v, lhs') ← cancel_factors.derive lhs, if v = 1 then return h else do (ih, h'') ← mk_single_comp_zero_pf v h, (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' /-- `cancel_denoms pf` assumes `pf` is a proof of `t R 0`. If `t` contains the division symbol `/`, it tries to scale `t` to cancel out division by numerals. -/ meta def cancel_denoms : preprocessor := { name := "cancel denominators", transform := λ pf, (do some (_, lhs) ← parse_into_comp_and_expr <$> infer_type pf, guardb $ lhs.contains_constant (= `has_div.div), singleton <$> normalize_denominators_in_lhs pf lhs) <|> return [pf] } /-- `find_squares m e` collects all terms of the form `a ^ 2` and `a * a` that appear in `e` and adds them to the set `m`. A pair `(a, tt)` is added to `m` when `a^2` appears in `e`, and `(a, ff)` is added to `m` when `a*a` appears in `e`. -/ meta def find_squares : rb_set (expr × bool) → expr → tactic (rb_set (expr × bool)) | s `(%%a ^ 2) := do s ← find_squares s a, return (s.insert (a, tt)) | s e@`(%%e1 * %%e2) := if e1 = e2 then do s ← find_squares s e1, return (s.insert (e1, ff)) else e.mfoldl find_squares s | s e := e.mfoldl find_squares s /-- `nlinarith_extras` is the preprocessor corresponding to the `nlinarith` tactic. * For every term `t` such that `t^2` or `t*t` appears in the input, adds a proof of `t^2 ≥ 0` or `t*t ≥ 0`. * For every pair of comparisons `t1 R1 0` and `t2 R2 0`, adds a proof of `t1*t2 R 0`. This preprocessor is typically run last, after all inputs have been canonized. -/ meta def nlinarith_extras : global_preprocessor := { name := "nonlinear arithmetic extras", transform := λ ls, do s ← ls.mfoldr (λ h s', infer_type h >>= find_squares s') mk_rb_set, new_es ← s.mfold ([] : list expr) $ λ ⟨e, is_sq⟩ new_es, ((do p ← mk_app (if is_sq then ``pow_two_nonneg else ``mul_self_nonneg) [e], return $ p::new_es) <|> return new_es), new_es ← make_comp_with_zero.globalize.transform new_es, linarith_trace "nlinarith preprocessing found squares", linarith_trace s, linarith_trace_proofs "so we added proofs" new_es, with_comps ← (new_es ++ ls).mmap (λ e, do tp ← infer_type e, return $ (parse_into_comp_and_expr tp).elim (ineq.lt, e) (λ ⟨ine, _⟩, (ine, e))), products ← with_comps.mmap_upper_triangle $ λ ⟨posa, a⟩ ⟨posb, b⟩, some <$> match posa, posb with | ineq.eq, _ := mk_app ``zero_mul_eq [a, b] | _, ineq.eq := mk_app ``mul_zero_eq [a, b] | ineq.lt, ineq.lt := mk_app ``mul_pos_of_neg_of_neg [a, b] | ineq.lt, ineq.le := do a ← mk_app ``le_of_lt [a], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.lt := do b ← mk_app ``le_of_lt [b], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.le := mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] end <|> return none, products ← make_comp_with_zero.globalize.transform products.reduce_option, return $ new_es ++ ls ++ products } /-- `remove_ne_aux` case splits on any proof `h : a ≠ b` in the input, turning it into `a < b ∨ a > b`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne_aux : list expr → tactic (list branch) := λ hs, (do e ← hs.mfind (λ e : expr, do e ← infer_type e, guard $ e.is_ne.is_some), [(_, ng1), (_, ng2)] ← to_expr ``(or.elim (lt_or_gt_of_ne %%e)) >>= apply, let do_goal : expr → tactic (list branch) := λ g, do set_goals [g], h ← intro1, ls ← remove_ne_aux $ hs.remove_all [e], return $ ls.map (λ b : branch, (b.1, h::b.2)) in (++) <$> do_goal ng1 <*> do_goal ng2) <|> do g ← get_goal, return [(g, hs)] /-- `remove_ne` case splits on any proof `h : a ≠ b` in the input, turning it into `a < b ∨ a > b`, by calling `linarith.remove_ne_aux`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne : global_branching_preprocessor := { name := "remove_ne", transform := remove_ne_aux } /-- The default list of preprocessors, in the order they should typically run. -/ meta def default_preprocessors : list global_branching_preprocessor := [filter_comparisons, remove_negations, nat_to_int, strengthen_strict_int, make_comp_with_zero, cancel_denoms] /-- `preprocess pps l` takes a list `l` of proofs of propositions. It maps each preprocessor `pp ∈ pps` over this list. The preprocessors are run sequentially: each recieves the output of the previous one. Note that a preprocessor may produce multiple or no expressions from each input expression, so the size of the list may change. -/ meta def preprocess (pps : list global_branching_preprocessor) (l : list expr) : tactic (list branch) := do g ← get_goal, pps.mfoldl (λ ls pp, list.join <$> (ls.mmap $ λ b, set_goals [b.1] >> pp.process b.2)) [(g, l)] end linarith
8047a13b0a1a31fd471a83e7a286b4db218ae3b8
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/utils.lean
f453886427ec2afa487e23fb9655d1769f38afe6
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,047
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ open tactic expr list meta def get_metas : expr → list expr | (var _) := [] | (sort _) := [] | (const _ _) := [] | (mvar n t) := expr.mvar n t :: get_metas t | (local_const _ _ _ t) := get_metas t | (app a b) := get_metas a ++ get_metas b | (lam _ _ d b) := get_metas d ++ get_metas b | (pi _ _ d b) := get_metas d ++ get_metas b | (elet _ t v b) := get_metas t ++ get_metas v ++ get_metas b | (macro _ _ _) := [] meta def get_meta_type : expr → expr | (mvar _ t) := t | _ := mk_var 0 -- TODO(gabriel): think about how to handle the avalanche of implicit arguments meta def expr_size : expr → nat | (var _) := 1 | (sort _) := 1 | (const _ _) := 1 | (mvar n t) := 1 | (local_const _ _ _ _) := 1 | (app a b) := expr_size a + expr_size b | (lam _ _ d b) := 1 + expr_size b | (pi _ _ d b) := 1 + expr_size b | (elet _ t v b) := 1 + expr_size v + expr_size b | (macro _ _ _) := 1 namespace ordering def is_lt {A} [has_ordering A] (x y : A) : bool := match has_ordering.cmp x y with ordering.lt := tt | _ := ff end end ordering namespace list meta def nub {A} [has_ordering A] (l : list A) : list A := rb_map.keys (rb_map.set_of_list l) meta def nub_on {A B} [has_ordering B] (f : A → B) (l : list A) : list A := rb_map.values (rb_map.of_list (map (λx, (f x, x)) l)) def nub_on' {A B} [decidable_eq B] (f : A → B) : list A → list A | [] := [] | (x::xs) := x :: filter (λy, f x ≠ f y) (nub_on' xs) def for_all {A} (l : list A) (p : A → Prop) [decidable_pred p] : bool := list.all l (λx, to_bool (p x)) def exists_ {A} (l : list A) (p : A → Prop) [decidable_pred p] : bool := list.any l (λx, to_bool (p x)) def subset_of {A} [decidable_eq A] (xs ys : list A) := xs^.for_all (λx, x ∈ ys) def filter_maximal {A} (gt : A → A → bool) (l : list A) : list A := filter (λx, l^.for_all (λy, ¬gt y x)) l private def zip_with_index' {A} : ℕ → list A → list (A × ℕ) | _ nil := nil | i (x::xs) := (x,i) :: zip_with_index' (i+1) xs def zip_with_index {A} : list A → list (A × ℕ) := zip_with_index' 0 def partition {A} (pred : A → Prop) [decidable_pred pred] : list A → list A × list A | (x::xs) := match partition xs with (ts,fs) := if pred x then (x::ts, fs) else (ts, x::fs) end | [] := ([],[]) meta def merge_sorted {A} [has_ordering A] : list A → list A → list A | [] ys := ys | xs [] := xs | (x::xs) (y::ys) := if ordering.is_lt x y then x :: merge_sorted xs (y::ys) else y :: merge_sorted (x::xs) ys meta def sort {A} [has_ordering A] : list A → list A | (x::xs) := let (smaller, greater_eq) := partition (λy, ordering.is_lt y x) xs in merge_sorted (sort smaller) (x :: sort greater_eq) | [] := [] meta def sort_on {A B} (f : A → B) [has_ordering B] : list A → list A := @sort _ ⟨λx y, has_ordering.cmp (f x) (f y)⟩ end list meta def name_of_funsym : expr → name | (local_const uniq _ _ _) := uniq | (const n _) := n | _ := name.anonymous private meta def contained_funsyms' : expr → rb_map name expr → rb_map name expr | (var _) m := m | (sort _) m := m | (const n ls) m := rb_map.insert m n (const n ls) | (mvar _ t) m := contained_funsyms' t m | (local_const uniq pp bi t) m := rb_map.insert m uniq (local_const uniq pp bi t) | (app a b) m := contained_funsyms' a (contained_funsyms' b m) | (lam _ _ d b) m := contained_funsyms' d (contained_funsyms' b m) | (pi _ _ d b) m := contained_funsyms' d (contained_funsyms' b m) | (elet _ t v b) m := contained_funsyms' t (contained_funsyms' v (contained_funsyms' b m)) | (macro _ _ _) m := m meta def contained_funsyms (e : expr) : rb_map name expr := contained_funsyms' e (rb_map.mk name expr) private meta def contained_lconsts' : expr → rb_map name expr → rb_map name expr | (var _) m := m | (sort _) m := m | (const _ _) m := m | (mvar _ t) m := contained_lconsts' t m | (local_const uniq pp bi t) m := contained_lconsts' t (rb_map.insert m uniq (local_const uniq pp bi t)) | (app a b) m := contained_lconsts' a (contained_lconsts' b m) | (lam _ _ d b) m := contained_lconsts' d (contained_lconsts' b m) | (pi _ _ d b) m := contained_lconsts' d (contained_lconsts' b m) | (elet _ t v b) m := contained_lconsts' t (contained_lconsts' v (contained_lconsts' b m)) | (macro _ _ _) m := m meta def contained_lconsts (e : expr) : rb_map name expr := contained_lconsts' e (rb_map.mk name expr) meta def contained_lconsts_list (es : list expr) : rb_map name expr := es^.foldl (λlcs e, contained_lconsts' e lcs) (rb_map.mk name expr) namespace tactic meta def infer_univ (type : expr) : tactic level := do sort_of_type ← infer_type type >>= whnf, match sort_of_type with | sort lvl := return lvl | not_sort := do fmt ← pp not_sort, fail $ to_fmt "cannot get universe level of sort: " ++ fmt end end tactic namespace nat def min (m n : ℕ) := if m < n then m else n def max (m n : ℕ) := if m > n then m else n end nat
66952c389a21690ad21825a45c61e5e6c2eb71b1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/projective_spectrum/topology.lean
f215ce5fce05998485c720d5b01e9dcddbde107f
[ "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
18,858
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Johan Commelin -/ import ring_theory.graded_algebra.homogeneous_ideal import topology.category.Top.basic import topology.sets.opens /-! # Projective spectrum of a graded ring The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. It is naturally endowed with a topology: the Zariski topology. ## Notation - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ℕ → submodule R A` is the grading of `A`; ## Main definitions * `projective_spectrum 𝒜`: The projective spectrum of a graded ring `A`, or equivalently, the set of all homogeneous ideals of `A` that is both prime and relevant i.e. not containing irrelevant ideal. Henceforth, we call elements of projective spectrum *relevant homogeneous prime ideals*. * `projective_spectrum.zero_locus 𝒜 s`: The zero locus of a subset `s` of `A` is the subset of `projective_spectrum 𝒜` consisting of all relevant homogeneous prime ideals that contain `s`. * `projective_spectrum.vanishing_ideal t`: The vanishing ideal of a subset `t` of `projective_spectrum 𝒜` is the intersection of points in `t` (viewed as relevant homogeneous prime ideals). * `projective_spectrum.Top`: the topological space of `projective_spectrum 𝒜` endowed with the Zariski topology -/ noncomputable theory open_locale direct_sum big_operators pointwise open direct_sum set_like Top topological_space category_theory opposite variables {R A: Type*} variables [comm_semiring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) [graded_algebra 𝒜] /-- The projective spectrum of a graded commutative ring is the subtype of all homogenous ideals that are prime and do not contain the irrelevant ideal. -/ @[nolint has_nonempty_instance] def projective_spectrum := {I : homogeneous_ideal 𝒜 // I.to_ideal.is_prime ∧ ¬(homogeneous_ideal.irrelevant 𝒜 ≤ I)} namespace projective_spectrum variable {𝒜} /-- A method to view a point in the projective spectrum of a graded ring as a homogeneous ideal of that ring. -/ abbreviation as_homogeneous_ideal (x : projective_spectrum 𝒜) : homogeneous_ideal 𝒜 := x.1 lemma as_homogeneous_ideal_def (x : projective_spectrum 𝒜) : x.as_homogeneous_ideal = x.1 := rfl instance is_prime (x : projective_spectrum 𝒜) : x.as_homogeneous_ideal.to_ideal.is_prime := x.2.1 @[ext] lemma ext {x y : projective_spectrum 𝒜} : x = y ↔ x.as_homogeneous_ideal = y.as_homogeneous_ideal := subtype.ext_iff_val variable (𝒜) /-- The zero locus of a set `s` of elements of a commutative ring `A` is the set of all relevant homogeneous prime ideals of the ring that contain the set `s`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `projective_spectrum 𝒜` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set A) : set (projective_spectrum 𝒜) := {x | s ⊆ x.as_homogeneous_ideal} @[simp] lemma mem_zero_locus (x : projective_spectrum 𝒜) (s : set A) : x ∈ zero_locus 𝒜 s ↔ s ⊆ x.as_homogeneous_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set A) : zero_locus 𝒜 (ideal.span s) = zero_locus 𝒜 s := by { ext x, exact (submodule.gi _ _).gc s x.as_homogeneous_ideal.to_ideal } variable {𝒜} /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `A` can be thought of as a dependent function on the projective spectrum of `𝒜`. At a point `x` (a homogeneous prime ideal) the function (i.e., element) `f` takes values in the quotient ring `A` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `A` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (projective_spectrum 𝒜)) : homogeneous_ideal 𝒜 := ⨅ (x : projective_spectrum 𝒜) (h : x ∈ t), x.as_homogeneous_ideal lemma coe_vanishing_ideal (t : set (projective_spectrum 𝒜)) : (vanishing_ideal t : set A) = {f | ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, ← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_infi, submodule.mem_infi], apply forall_congr (λ x, _), rw [homogeneous_ideal.to_ideal_infi, submodule.mem_infi, homogeneous_ideal.mem_iff], end lemma mem_vanishing_ideal (t : set (projective_spectrum 𝒜)) (f : A) : f ∈ vanishing_ideal t ↔ ∀ x : projective_spectrum 𝒜, x ∈ t → f ∈ x.as_homogeneous_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : projective_spectrum 𝒜) : vanishing_ideal ({x} : set (projective_spectrum 𝒜)) = x.as_homogeneous_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (projective_spectrum 𝒜)) (I : ideal A) : t ⊆ zero_locus 𝒜 I ↔ I ≤ (vanishing_ideal t).to_ideal := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ variable (𝒜) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_ideal : @galois_connection (ideal A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t).to_ideal) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set A) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ s, zero_locus 𝒜 s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi A _).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose ideal_gc (gc_ideal 𝒜) lemma gc_homogeneous_ideal : @galois_connection (homogeneous_ideal 𝒜) (set (projective_spectrum 𝒜))ᵒᵈ _ _ (λ I, zero_locus 𝒜 I) (λ t, (vanishing_ideal t)) := λ I t, by simpa [show I.to_ideal ≤ (vanishing_ideal t).to_ideal ↔ I ≤ (vanishing_ideal t), from iff.rfl] using subset_zero_locus_iff_le_vanishing_ideal t I.to_ideal lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (projective_spectrum 𝒜)) (s : set A) : t ⊆ zero_locus 𝒜 s ↔ s ⊆ vanishing_ideal t := (gc_set _) s t lemma subset_vanishing_ideal_zero_locus (s : set A) : s ⊆ vanishing_ideal (zero_locus 𝒜 s) := (gc_set _).le_u_l s lemma ideal_le_vanishing_ideal_zero_locus (I : ideal A) : I ≤ (vanishing_ideal (zero_locus 𝒜 I)).to_ideal := (gc_ideal _).le_u_l I lemma homogeneous_ideal_le_vanishing_ideal_zero_locus (I : homogeneous_ideal 𝒜) : I ≤ vanishing_ideal (zero_locus 𝒜 I) := (gc_homogeneous_ideal _).le_u_l I lemma subset_zero_locus_vanishing_ideal (t : set (projective_spectrum 𝒜)) : t ⊆ zero_locus 𝒜 (vanishing_ideal t) := (gc_ideal _).l_u_le t lemma zero_locus_anti_mono {s t : set A} (h : s ⊆ t) : zero_locus 𝒜 t ⊆ zero_locus 𝒜 s := (gc_set _).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal A} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_ideal _).monotone_l h lemma zero_locus_anti_mono_homogeneous_ideal {s t : homogeneous_ideal 𝒜} (h : s ≤ t) : zero_locus 𝒜 (t : set A) ⊆ zero_locus 𝒜 (s : set A) := (gc_homogeneous_ideal _).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (projective_spectrum 𝒜)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc_ideal _).monotone_u h lemma zero_locus_bot : zero_locus 𝒜 ((⊥ : ideal A) : set A) = set.univ := (gc_ideal 𝒜).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus 𝒜 ({0} : set A) = set.univ := zero_locus_bot _ @[simp] lemma zero_locus_empty : zero_locus 𝒜 (∅ : set A) = set.univ := (gc_set 𝒜).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (projective_spectrum 𝒜)) = ⊤ := by simpa using (gc_ideal _).u_top lemma zero_locus_empty_of_one_mem {s : set A} (h : (1:A) ∈ s) : zero_locus 𝒜 s = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ x hx, (infer_instance : x.as_homogeneous_ideal.to_ideal.is_prime).ne_top $ x.as_homogeneous_ideal.to_ideal.eq_top_iff_one.mpr $ hx h @[simp] lemma zero_locus_singleton_one : zero_locus 𝒜 ({1} : set A) = ∅ := zero_locus_empty_of_one_mem 𝒜 (set.mem_singleton (1 : A)) @[simp] lemma zero_locus_univ : zero_locus 𝒜 (set.univ : set A) = ∅ := zero_locus_empty_of_one_mem _ (set.mem_univ 1) lemma zero_locus_sup_ideal (I J : ideal A) : zero_locus 𝒜 ((I ⊔ J : ideal A) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_ideal 𝒜).l_sup lemma zero_locus_sup_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I ⊔ J : homogeneous_ideal 𝒜) : set A) = zero_locus _ I ∩ zero_locus _ J := (gc_homogeneous_ideal 𝒜).l_sup lemma zero_locus_union (s s' : set A) : zero_locus 𝒜 (s ∪ s') = zero_locus _ s ∩ zero_locus _ s' := (gc_set 𝒜).l_sup lemma vanishing_ideal_union (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := by ext1; convert (gc_ideal 𝒜).u_inf lemma zero_locus_supr_ideal {γ : Sort*} (I : γ → ideal A) : zero_locus _ ((⨆ i, I i : ideal A) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_ideal 𝒜).l_supr lemma zero_locus_supr_homogeneous_ideal {γ : Sort*} (I : γ → homogeneous_ideal 𝒜) : zero_locus _ ((⨆ i, I i : homogeneous_ideal 𝒜) : set A) = (⋂ i, zero_locus 𝒜 (I i)) := (gc_homogeneous_ideal 𝒜).l_supr lemma zero_locus_Union {γ : Sort*} (s : γ → set A) : zero_locus 𝒜 (⋃ i, s i) = (⋂ i, zero_locus 𝒜 (s i)) := (gc_set 𝒜).l_supr lemma zero_locus_bUnion (s : set (set A)) : zero_locus 𝒜 (⋃ s' ∈ s, s' : set A) = ⋂ s' ∈ s, zero_locus 𝒜 s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {γ : Sort*} (t : γ → set (projective_spectrum 𝒜)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := homogeneous_ideal.to_ideal_injective $ by convert (gc_ideal 𝒜).u_infi; exact homogeneous_ideal.to_ideal_infi _ lemma zero_locus_inf (I J : ideal A) : zero_locus 𝒜 ((I ⊓ J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.2.1.inf_le lemma union_zero_locus (s s' : set A) : zero_locus 𝒜 s ∪ zero_locus 𝒜 s' = zero_locus 𝒜 ((ideal.span s) ⊓ (ideal.span s'): ideal A) := by { rw zero_locus_inf, simp } lemma zero_locus_mul_ideal (I J : ideal A) : zero_locus 𝒜 ((I * J : ideal A) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.2.1.mul_le lemma zero_locus_mul_homogeneous_ideal (I J : homogeneous_ideal 𝒜) : zero_locus 𝒜 ((I * J : homogeneous_ideal 𝒜) : set A) = zero_locus 𝒜 I ∪ zero_locus 𝒜 J := set.ext $ λ x, x.2.1.mul_le lemma zero_locus_singleton_mul (f g : A) : zero_locus 𝒜 ({f * g} : set A) = zero_locus 𝒜 {f} ∪ zero_locus 𝒜 {g} := set.ext $ λ x, by simpa using x.2.1.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_singleton_pow (f : A) (n : ℕ) (hn : 0 < n) : zero_locus 𝒜 ({f ^ n} : set A) = zero_locus 𝒜 {f} := set.ext $ λ x, by simpa using x.2.1.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (projective_spectrum 𝒜)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [← homogeneous_ideal.mem_iff, homogeneous_ideal.to_ideal_sup, mem_vanishing_ideal, submodule.mem_sup], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, erw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : A} {I : projective_spectrum 𝒜} : I ∈ (zero_locus 𝒜 {f} : set (projective_spectrum 𝒜))ᶜ ↔ f ∉ I.as_homogeneous_ideal := by rw [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (projective_spectrum 𝒜) := topological_space.of_closed (set.range (projective_spectrum.zero_locus 𝒜)) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set _ := λ i, classical.some (h i.2), have hf : ∀ i : Zs, ↑i = zero_locus 𝒜 (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union 𝒜 _⟩ end (by { rintros _ ⟨s, rfl⟩ _ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus 𝒜 s t).symm⟩ }) /-- The underlying topology of `Proj` is the projective spectrum of graded ring `A`. -/ def Top : Top := Top.of (projective_spectrum 𝒜) lemma is_open_iff (U : set (projective_spectrum 𝒜)) : is_open U ↔ ∃ s, Uᶜ = zero_locus 𝒜 s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (projective_spectrum 𝒜)) : is_closed Z ↔ ∃ s, Z = zero_locus 𝒜 s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_zero_locus (s : set A) : is_closed (zero_locus 𝒜 s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma zero_locus_vanishing_ideal_eq_closure (t : set (projective_spectrum 𝒜)) : zero_locus 𝒜 (vanishing_ideal t : set A) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus 𝒜 s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _ _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal 𝒜 t } end lemma vanishing_ideal_closure (t : set (projective_spectrum 𝒜)) : vanishing_ideal (closure t) = vanishing_ideal t := begin have := (gc_ideal 𝒜).u_l_u_eq_u t, dsimp only at this, ext1, erw zero_locus_vanishing_ideal_eq_closure 𝒜 t at this, exact this, end section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : A) : topological_space.opens (projective_spectrum 𝒜) := { val := { x | r ∉ x.as_homogeneous_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ basic_open 𝒜 f ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma mem_coe_basic_open (f : A) (x : projective_spectrum 𝒜) : x ∈ (↑(basic_open 𝒜 f): set (projective_spectrum 𝒜)) ↔ f ∉ x.as_homogeneous_ideal := iff.rfl lemma is_open_basic_open {a : A} : is_open ((basic_open 𝒜 a) : set (projective_spectrum 𝒜)) := (basic_open 𝒜 a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : A) : (basic_open 𝒜 r : set (projective_spectrum 𝒜)) = (zero_locus 𝒜 {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_iff, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open 𝒜 (1 : A) = ⊤ := topological_space.opens.ext $ by simp @[simp] lemma basic_open_zero : basic_open 𝒜 (0 : A) = ⊥ := topological_space.opens.ext $ by simp lemma basic_open_mul (f g : A) : basic_open 𝒜 (f * g) = basic_open 𝒜 f ⊓ basic_open 𝒜 g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 f := by { rw basic_open_mul 𝒜 f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : A) : basic_open 𝒜 (f * g) ≤ basic_open 𝒜 g := by { rw basic_open_mul 𝒜 f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : A) (n : ℕ) (hn : 0 < n) : basic_open 𝒜 (f ^ n) = basic_open 𝒜 f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow 𝒜 f n hn lemma basic_open_eq_union_of_projection (f : A) : basic_open 𝒜 f = ⨆ (i : ℕ), basic_open 𝒜 (graded_algebra.proj 𝒜 i f) := topological_space.opens.ext $ set.ext $ λ z, begin erw [mem_coe_basic_open, topological_space.opens.mem_Sup], split; intros hz, { rcases show ∃ i, graded_algebra.proj 𝒜 i f ∉ z.as_homogeneous_ideal, begin contrapose! hz with H, classical, rw ←direct_sum.sum_support_decompose 𝒜 f, apply ideal.sum_mem _ (λ i hi, H i) end with ⟨i, hi⟩, exact ⟨basic_open 𝒜 (graded_algebra.proj 𝒜 i f), ⟨i, rfl⟩, by rwa mem_basic_open⟩ }, { obtain ⟨_, ⟨i, rfl⟩, hz⟩ := hz, exact λ rid, hz (z.1.2 i rid) }, end lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : A), (basic_open 𝒜 r : set (projective_spectrum 𝒜)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open 𝒜 }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_iff, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open 𝒜 f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono 𝒜 (set.singleton_subset_iff.mpr hfs) } end end basic_open section order /-! ## The specialization order We endow `projective_spectrum 𝒜` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. -/ instance : partial_order (projective_spectrum 𝒜) := subtype.partial_order _ @[simp] lemma as_ideal_le_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal ≤ y.as_homogeneous_ideal ↔ x ≤ y := subtype.coe_le_coe @[simp] lemma as_ideal_lt_as_ideal (x y : projective_spectrum 𝒜) : x.as_homogeneous_ideal < y.as_homogeneous_ideal ↔ x < y := subtype.coe_lt_coe lemma le_iff_mem_closure (x y : projective_spectrum 𝒜) : x ≤ y ↔ y ∈ closure ({x} : set (projective_spectrum 𝒜)) := begin rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton], simp only [coe_subset_coe, subtype.coe_le_coe, coe_coe], end end order end projective_spectrum
af9563ed9c7da05ea34c9a9a8e6aff55733ac957
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/algebra/archimedean.lean
049100a44a619d382503376a397b3b2b1114f7ba
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
9,980
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Archimedean groups and fields. -/ import algebra.field_power import data.rat variables {α : Type*} open_locale add_monoid class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) theorem exists_nat_gt [linear_ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← add_monoid.smul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := have hy0 : 0 < y - 1 := sub_pos_of_lt hy1, -- TODO `by linarith` fails to prove hy1' have hy1' : (-1:α) ≤ y, from le_trans (neg_le_self zero_le_one) (le_of_lt hy1), let ⟨n, h⟩ := archimedean.arch x hy0 in ⟨n, calc x ≤ n • (y - 1) : h ... < 1 + n • (y - 1) : lt_one_add _ ... ≤ y ^ n : one_add_sub_mul_le_pow hy1' n⟩ /-- Every x greater than 1 is between two successive natural-number powers of another y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 < x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from nat.pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_lt_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [discrete_linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by rw [(fpow_neg y (↑N))]; exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN)⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm hM))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive x is between two successive integer powers of another y greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [discrete_linear_ordered_field α] [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, le_inv hx (fpow_pos_of_pos hyp _)]⟩ variables [linear_ordered_field α] [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.smul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [add_monoid.smul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← add_monoid.smul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0 := nat.cast_pos.1 (lt_trans (inv_pos.2 (sub_pos.2 h)) nh), have n0' := (@nat.cast_pos α _ _).2 n0, rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div_eq_inv], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases archimedean_iff_nat_lt.1 (by apply_instance) (1/ε) with n hn, existsi n, apply div_lt_of_mul_lt_of_pos, { simp, apply add_pos_of_nonneg_of_pos, apply nat.cast_nonneg, apply zero_lt_one }, { apply (div_lt_iff' hε).1, transitivity, { exact hn }, { simp [zero_lt_one] }} end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 include α @[simp] theorem rat.cast_floor (x : ℚ) : by haveI := archimedean.floor_ring α; exact ⌊(x:α)⌋ = ⌊x⌋ := begin haveI := archimedean.floor_ring α, apply le_antisymm, { rw [le_floor, ← @rat.cast_le α, rat.cast_coe_int], apply floor_le }, { rw [le_floor, ← rat.cast_coe_int, rat.cast_le], apply floor_le } end end linear_ordered_field section variables [discrete_linear_ordered_field α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round [floor_ring α] (x : α) : ℤ := ⌊x + 1 / 2⌋ lemma abs_sub_round [floor_ring α] (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end variable [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ @[simp] theorem rat.cast_round (x : ℚ) : by haveI := archimedean.floor_ring α; exact round (x:α) = round x := have ((x + (1 : ℚ) / (2 : ℚ) : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end
67625246cd70a284e092e2b5209a363df8927a45
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/eval.lean
9e677fd6dc6c5701f645a156408030388979da0f
[ "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
34,154
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.degree.definitions import algebra.geom_sum /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finset add_monoid_algebra open_locale big_operators polynomial namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : R[X]) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : R[X]} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_at_zero : p.eval₂ f 0 = f (coeff p 0) := by simp only [eval₂_eq_sum, zero_pow_eq, mul_ite, mul_zero, mul_one, sum, not_not, mem_support_iff, sum_ite_eq', ite_eq_left_iff, ring_hom.map_zero, implies_true_iff, eq_self_iff_true] {contextual := tt} @[simp] lemma eval₂_zero : (0 : R[X]).eval₂ f x = 0 := by simp [eval₂_eq_sum] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [eval₂_eq_sum] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := by { apply sum_add_index; simp [add_mul] } @[simp] lemma eval₂_one : (1 : R[X]).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : R[X]) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := begin have A : p.nat_degree < p.nat_degree.succ := nat.lt_succ_self _, have B : (s • p).nat_degree < p.nat_degree.succ := (nat_degree_smul_le _ _).trans_lt A, rw [eval₂_eq_sum, eval₂_eq_sum, sum_over_range' _ _ _ A, sum_over_range' _ _ _ B]; simp [mul_sum, mul_assoc], end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul']) /-- `eval₂_add_monoid_hom (f : R →+* S) (x : S)` is the `add_monoid_hom` from `polynomial R` to `S` obtained by evaluating the pushforward of `p` along `f` at `x`. -/ @[simps] def eval₂_add_monoid_hom : R[X] →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : R[X]).eval₂ f x = n := begin induction n with n ih, { simp only [eval₂_zero, nat.cast_zero] }, { rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] } end variables [semiring T] lemma eval₂_sum (p : T[X]) (g : ℕ → T → R[X]) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := begin let T : R[X] →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ p q, eval₂_add _ _ }, have A : ∀ y, eval₂ f x y = T y := λ y, rfl, simp only [A], rw [sum, T.map_sum, sum] end lemma eval₂_list_sum (l : list R[X]) (x : S) : eval₂ f x l.sum = (l.map (eval₂ f x)).sum := map_list_sum (eval₂_add_monoid_hom f x) l lemma eval₂_multiset_sum (s : multiset R[X]) (x : S) : eval₂ f x s.sum = (s.map (eval₂ f x)).sum := map_multiset_sum (eval₂_add_monoid_hom f x) s lemma eval₂_finset_sum (s : finset ι) (g : ι → R[X]) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := map_sum (eval₂_add_monoid_hom f x) _ _ lemma eval₂_of_finsupp {f : R →+* S} {x : S} {p : add_monoid_algebra R ℕ} : eval₂ f x (⟨p⟩ : R[X]) = lift_nc ↑f (powers_hom S x) p := by { simp only [eval₂_eq_sum, sum, to_finsupp_sum, support, coeff], refl } lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := begin rcases p, rcases q, simp only [coeff] at hf, simp only [←of_finsupp_mul, eval₂_of_finsupp], exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n) end @[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x := begin refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X), rcases em (k = 1) with (rfl|hk), { simp }, { simp [coeff_X_of_ne_one hk] } end @[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x := by rw [X_mul, eval₂_mul_X] lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a := begin rw [eval₂_mul_noncomm, eval₂_C], intro k, by_cases hk : k = 0, { simp only [hk, h, coeff_C_zero, coeff_C_ne_zero] }, { simp only [coeff_C_ne_zero hk, ring_hom.map_zero, commute.zero_left] } end lemma eval₂_list_prod_noncomm (ps : list R[X]) (hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) : eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps using list.reverse_rec_on with ps p ihp, { simp }, { simp only [list.forall_mem_append, list.forall_mem_singleton] at hf, simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : R[X] →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k), map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ section variables [semiring S] (f : R →+* S) (x : S) lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : R[X]} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end end section variables [comm_semiring S] (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := eval₂_mul_noncomm _ _ $ λ k, commute.all _ _ lemma eval₂_mul_eq_zero_of_left (q : R[X]) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : R[X]) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x : S) : R[X] →+* S := { map_one' := eval₂_one _ _, map_mul' := λ _ _, eval₂_mul _ _, ..eval₂_add_monoid_hom f x } @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_dvd : p ∣ q → eval₂ f x p ∣ eval₂ f x q := (eval₂_ring_hom f x).map_dvd lemma eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (h : p ∣ q) (h0 : eval₂ f x p = 0) : eval₂ f x q = 0 := zero_dvd_iff.mp (h0 ▸ eval₂_dvd f x h) lemma eval₂_list_prod (l : list R[X]) (x : S) : eval₂ f x l.prod = (l.map (eval₂ f x)).prod := map_list_prod (eval₂_ring_hom f x) l end end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → R[X] → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = p.sum (λ e a, a * x ^ e) := rfl lemma eval_eq_sum_range {p : R[X]} (x : R) : p.eval x = ∑ i in finset.range (p.nat_degree + 1), p.coeff i * x ^ i := by rw [eval_eq_sum, sum_over_range]; simp lemma eval_eq_sum_range' {p : R[X]} {n : ℕ} (hn : p.nat_degree < n) (x : R) : p.eval x = ∑ i in finset.range n, p.coeff i * x ^ i := by rw [eval_eq_sum, p.sum_over_range' _ _ hn]; simp @[simp] lemma eval₂_at_apply {S : Type*} [semiring S] (f : R →+* S) (r : R) : p.eval₂ f (f r) = f (p.eval r) := begin rw [eval₂_eq_sum, eval_eq_sum, sum, sum, f.map_sum], simp only [f.map_mul, f.map_pow], end @[simp] lemma eval₂_at_one {S : Type*} [semiring S] (f : R →+* S) : p.eval₂ f 1 = f (p.eval 1) := begin convert eval₂_at_apply f 1, simp, end @[simp] lemma eval₂_at_nat_cast {S : Type*} [semiring S] (f : R →+* S) (n : ℕ) : p.eval₂ f n = f (p.eval n) := begin convert eval₂_at_apply f n, simp, end @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : R[X]).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : R[X]).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : R[X]).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p : R[X]) (x : R) : (s • p).eval x = s • p.eval x := by rw [← smul_one_smul R s p, eval, eval₂_smul, ring_hom.id_apply, smul_one_mul] @[simp] lemma eval_C_mul : (C a * p).eval x = a * p.eval x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [mul_add, eval_add, ph, qh], }, { intros n b, simp only [mul_assoc, C_mul_monomial, eval_monomial], } end /-- A reformulation of the expansion of (1 + y)^d: $$(d + 1) (1 + y)^d - (d + 1)y^d = \sum_{i = 0}^d {d + 1 \choose i} \cdot i \cdot y^{i - 1}.$$ -/ lemma eval_monomial_one_add_sub [comm_ring S] (d : ℕ) (y : S) : eval (1 + y) (monomial d (d + 1 : S)) - eval y (monomial d (d + 1 : S)) = ∑ (x_1 : ℕ) in range (d + 1), ↑((d + 1).choose x_1) * (↑x_1 * y ^ (x_1 - 1)) := begin have cast_succ : (d + 1 : S) = ((d.succ : ℕ) : S), { simp only [nat.cast_succ], }, rw [cast_succ, eval_monomial, eval_monomial, add_comm, add_pow], conv_lhs { congr, congr, skip, apply_congr, skip, rw [one_pow, mul_one, mul_comm], }, rw [sum_range_succ, mul_add, nat.choose_self, nat.cast_one, one_mul, add_sub_cancel, mul_sum, sum_range_succ', nat.cast_zero, zero_mul, mul_zero, add_zero], apply sum_congr rfl (λ y hy, _), rw [←mul_assoc, ←mul_assoc, ←nat.cast_mul, nat.succ_mul_choose_eq, nat.cast_mul, nat.add_sub_cancel], end /-- `polynomial.eval` as linear map -/ @[simps] def leval {R : Type*} [semiring R] (r : R) : R[X] →ₗ[R] R := { to_fun := λ f, f.eval r, map_add' := λ f g, eval_add, map_smul' := λ c f, eval_smul c f r } @[simp] lemma eval_nat_cast_mul {n : ℕ} : ((n : R[X]) * p).eval x = n * p.eval x := by rw [←C_eq_nat_cast, eval_C_mul] @[simp] lemma eval_mul_X : (p * X).eval x = p.eval x * x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [add_mul, eval_add, ph, qh], }, { intros n a, simp only [←monomial_one_one_eq_X, monomial_mul_monomial, eval_monomial, mul_one, pow_succ', mul_assoc], } end @[simp] lemma eval_mul_X_pow {k : ℕ} : (p * X^k).eval x = p.eval x * x^k := begin induction k with k ih, { simp, }, { simp [pow_succ', ←mul_assoc, ih], } end lemma eval_sum (p : R[X]) (f : ℕ → R → R[X]) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → R[X]) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : R[X]) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma is_root.eq_zero (h : is_root p x) : eval x p = 0 := h lemma coeff_zero_eq_eval_zero (p : R[X]) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : R[X]} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp lemma is_root.dvd {R : Type*} [comm_semiring R] {p q : R[X]} {x : R} (h : p.is_root x) (hpq : p ∣ q) : q.is_root x := by rwa [is_root, eval, eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ hpq] lemma not_is_root_C (r a : R) (hr : r ≠ 0) : ¬ is_root (C r) a := by simpa using hr end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : R[X]) : R[X] := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, ← monomial_eq_C_mul_X], exact sum_monomial_eq _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := by simp [comp, (C : R →+* _).map_sum] @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma nat_cast_comp {n : ℕ} : (n : R[X]).comp p = n := by rw [←C_eq_nat_cast, C_comp] @[simp] lemma comp_zero : p.comp (0 : R[X]) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : R[X]) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : R[X]) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma monomial_comp (n : ℕ) : (monomial n a).comp p = C a * p^n := eval₂_monomial _ _ @[simp] lemma mul_X_comp : (p * X).comp r = p.comp r * r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, add_mul, add_comp] }, { intros n b, simp only [pow_succ', mul_assoc, monomial_mul_X, monomial_comp] } end @[simp] lemma X_pow_comp {k : ℕ} : (X^k).comp p = p^k := begin induction k with k ih, { simp, }, { simp [pow_succ', mul_X_comp, ih], }, end @[simp] lemma mul_X_pow_comp {k : ℕ} : (p * X^k).comp r = p.comp r * r^k := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, mul_X_comp], }, end @[simp] lemma C_mul_comp : (C a * p).comp r = C a * p.comp r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, mul_add], }, { intros n b, simp [mul_assoc], } end @[simp] lemma nat_cast_mul_comp {n : ℕ} : ((n : R[X]) * p).comp r = n * p.comp r := by rw [←C_eq_nat_cast, C_mul_comp, C_eq_nat_cast] @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : R[X]) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ @[simp] lemma pow_comp {R : Type*} [comm_semiring R] (p q : R[X]) (n : ℕ) : (p^n).comp q = (p.comp q)^n := ((monoid_hom.mk (λ r : R[X], r.comp q)) one_comp (λ r s, mul_comp r s q)).map_pow p n @[simp] lemma bit0_comp : comp (bit0 p : R[X]) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : R[X]) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] @[simp] lemma smul_comp [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p q : R[X]) : (s • p).comp q = s • p.comp q := by rw [← smul_one_smul R s p, comp, comp, eval₂_smul, ← smul_eq_C_mul, smul_assoc, one_smul] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : R[X]) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end 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 := begin rw [comp, eval₂, coeff_sum], convert finset.sum_eq_single p.nat_degree _ _, { simp only [coeff_nat_degree, coeff_C_mul, coeff_pow_mul_nat_degree] }, { assume b hbs hbp, refine coeff_eq_zero_of_nat_degree_lt ((nat_degree_mul_le).trans_lt _), rw [nat_degree_C, zero_add], refine (nat_degree_pow_le).trans_lt ((mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)).mpr _), exact lt_of_le_of_ne (le_nat_degree_of_mem_supp _ hbs) hbp }, { simp {contextual := tt} } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : R[X] → S[X] := eval₂ (C.comp f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, monomial_eq_C_mul_X], refl, end @[simp] protected lemma map_zero : (0 : R[X]).map f = 0 := eval₂_zero _ _ @[simp] protected lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] protected lemma map_one : (1 : R[X]).map f = 1 := eval₂_one _ _ @[simp] protected lemma map_mul : (p * q).map f = p.map f * q.map f := by { rw [map, eval₂_mul_noncomm], exact λ k, (commute_X _).symm } @[simp] protected lemma map_smul (r : R) : (r • p).map f = f r • p.map f := by rw [map, eval₂_smul, ring_hom.comp_apply, C_mul'] /-- `polynomial.map` as a `ring_hom`. -/ -- `map` is a ring-hom unconditionally, and theoretically the definition could be replaced, -- but this turns out not to be easy because `p.map f` does not resolve to `polynomial.map` -- if `map` is a `ring_hom` instead of a plain function; the elaborator does not try to coerce -- to a function before trying field (dot) notation (this may be technically infeasible); -- the relevant code is (both lines): https://github.com/leanprover-community/ -- lean/blob/487ac5d7e9b34800502e1ddf3c7c806c01cf9d51/src/frontends/lean/elaborator.cpp#L1876-L1913 def map_ring_hom (f : R →+* S) : R[X] →+* S[X] := { to_fun := polynomial.map f, map_add' := λ _ _, polynomial.map_add f, map_zero' := polynomial.map_zero f, map_mul' := λ _ _, polynomial.map_mul f, map_one' := polynomial.map_one f } @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl -- This is protected to not clash with the global `map_nat_cast`. @[simp] protected theorem map_nat_cast (n : ℕ) : (n : R[X]).map f = n := map_nat_cast (map_ring_hom f) n @[simp] protected lemma map_bit0 : (bit0 p).map f = bit0 (p.map f) := map_bit0 (map_ring_hom f) p @[simp] protected lemma map_bit1 : (bit1 p).map f = bit1 (p.map f) := map_bit1 (map_ring_hom f) p @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum, sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, sum, ring_hom.map_sum], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X_pow, f.map_mul], split_ifs; simp [f.map_zero], end /-- If `R` and `S` are isomorphic, then so are their polynomial rings. -/ @[simps] def map_equiv (e : R ≃+* S) : R[X] ≃+* S[X] := ring_equiv.of_hom_inv (map_ring_hom (e : R →+* S)) (map_ring_hom (e.symm : S →+* R)) (by ext; simp) (by ext; simp) lemma map_map [semiring T] (g : S →+* T) (p : R[X]) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [polynomial.map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) lemma degree_map_le (p : R[X]) : degree (p.map f) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_map_le (p : R[X]) : nat_degree (p.map f) ≤ nat_degree p := nat_degree_le_nat_degree (degree_map_le f p) variables {f} protected lemma map_eq_zero_iff (hf : function.injective f) : p.map f = 0 ↔ p = 0 := map_eq_zero_iff (map_ring_hom f) (map_injective f hf) protected lemma map_ne_zero_iff (hf : function.injective f) : p.map f ≠ 0 ↔ p ≠ 0 := (polynomial.map_eq_zero_iff hf).not lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp only [mul_one, hp.leading_coeff, f.map_one] ... = f x * (p.map f).coeff p.nat_degree : congr_arg _ (coeff_map _ _).symm ... = 0 : by simp only [hfp, mul_zero, coeff_zero], λ h, ext (λ n, by simp only [h, coeff_map, coeff_zero]) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) lemma degree_map_eq_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f _) $ have hp0 : p ≠ 0, from leading_coeff_ne_zero.mp (λ hp0, hf (trans (congr_arg _ hp0) f.map_zero)), begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma nat_degree_map_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) lemma leading_coeff_map_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_of_leading_coeff_ne_zero f hf], end variables (f) @[simp] lemma map_ring_hom_id : map_ring_hom (ring_hom.id R) = ring_hom.id R[X] := ring_hom.ext $ λ x, map_id @[simp] lemma map_ring_hom_comp [semiring T] (f : S →+* T) (g : R →+* S) : (map_ring_hom f).comp (map_ring_hom g) = map_ring_hom (f.comp g) := ring_hom.ext $ polynomial.map_map g f protected lemma map_list_prod (L : list R[X]) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (map_ring_hom f).to_monoid_hom @[simp] protected lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := (map_ring_hom f).map_pow _ _ lemma mem_map_srange {p : S[X]} : p ∈ (map_ring_hom f).srange ↔ ∀ n, p.coeff n ∈ f.srange := begin split, { rintro ⟨p, rfl⟩ n, rw [coe_map_ring_hom, coeff_map], exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, refine (map_ring_hom f).srange.sum_mem _, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [coe_map_ring_hom, polynomial.map_mul, map_C, hc, polynomial.map_pow, map_X] } end lemma mem_map_range {R S : Type*} [ring R] [ring S] (f : R →+* S) {p : S[X]} : p ∈ (map_ring_hom f).range ↔ ∀ n, p.coeff n ∈ f.range := mem_map_srange f lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := by rw [eval₂_eq_eval_map, eval₂_eq_eval_map, map_map] lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := (eval₂_eq_eval_map f).symm protected lemma map_sum {ι : Type*} (g : ι → R[X]) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := (map_ring_hom f).map_sum _ _ lemma map_comp (p q : R[X]) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp only [map_C, forall_const, C_comp, eq_self_iff_true]) (by simp only [polynomial.map_add, add_comp, forall_const, implies_true_iff, eq_self_iff_true] {contextual := tt}) (by simp only [pow_succ', ←mul_assoc, comp, forall_const, eval₂_mul_X, implies_true_iff, eq_self_iff_true, map_X, polynomial.map_mul] {contextual := tt}) @[simp] lemma eval_zero_map (f : R →+* S) (p : R[X]) : (p.map f).eval 0 = f (p.eval 0) := by simp [←coeff_zero_eq_eval_zero] @[simp] lemma eval_one_map (f : R →+* S) (p : R[X]) : (p.map f).eval 1 = f (p.eval 1) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [one_pow, mul_one, eval_monomial, map_monomial] } end @[simp] lemma eval_nat_cast_map (f : R →+* S) (p : R[X]) (n : ℕ) : (p.map f).eval n = f (p.eval n) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [map_nat_cast f, eval_monomial, map_monomial, f.map_pow, f.map_mul] } end @[simp] lemma eval_int_cast_map {R S : Type*} [ring R] [ring S] (f : R →+* S) (p : R[X]) (i : ℤ) : (p.map f).eval i = f (p.eval i) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [map_int_cast, eval_monomial, map_monomial, map_pow, map_mul] } end end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ variables [semiring S] [semiring T] (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := by rw [←eval₂_map, eval₂_at_apply, eval_map] end hom_eval₂ end semiring section comm_semiring section eval section variables [semiring R] {p q : R[X]} {x : R} [semiring S] (f : R →+* S) lemma eval₂_hom (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm end section variables [semiring R] {p q : R[X]} {x : R} [comm_semiring S] (f : R →+* S) lemma eval₂_comp {x : S} : eval₂ f x (p.comp q) = eval₂ f (eval₂ f x q) p := by rw [comp, p.as_sum_range]; simp [eval₂_finset_sum, eval₂_pow] end section variables [comm_semiring R] {p q : R[X]} {x : R} [comm_semiring S] (f : R →+* S) @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ /-- `eval r`, regarded as a ring homomorphism from `polynomial R` to `R`. -/ def eval_ring_hom : R → R[X] →+* R := eval₂_ring_hom (ring_hom.id _) @[simp] lemma coe_eval_ring_hom (r : R) : ((eval_ring_hom r) : R[X] → R) = eval r := rfl @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ @[simp] lemma eval_comp : (p.comp q).eval x = p.eval (q.eval x) := begin apply polynomial.induction_on' p, { intros r s hr hs, simp [add_comp, hr, hs], }, { intros n a, simp, } end /-- `comp p`, regarded as a ring homomorphism from `polynomial R` to itself. -/ def comp_ring_hom : R[X] → R[X] →+* R[X] := eval₂_ring_hom C @[simp] lemma coe_comp_ring_hom (q : R[X]) : (comp_ring_hom q : R[X] → R[X]) = λ p, comp p q := rfl lemma coe_comp_ring_hom_apply (p q : R[X]) : (comp_ring_hom q : R[X] → R[X]) p = comp p q := rfl lemma root_mul_left_of_is_root (p : R[X]) {q : R[X]} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : R[X]} (q : R[X]) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma eval₂_multiset_prod (s : multiset R[X]) (x : S) : eval₂ f x s.prod = (s.map (eval₂ f x)).prod := map_multiset_prod (eval₂_ring_hom f x) s lemma eval₂_finset_prod (s : finset ι) (g : ι → R[X]) (x : S) : (∏ i in s, g i).eval₂ f x = ∏ i in s, (g i).eval₂ f x := map_prod (eval₂_ring_hom f x) _ _ /-- Polynomial evaluation commutes with `list.prod` -/ lemma eval_list_prod (l : list R[X]) (x : R) : eval x l.prod = (l.map (eval x)).prod := (eval_ring_hom x).map_list_prod l /-- Polynomial evaluation commutes with `multiset.prod` -/ lemma eval_multiset_prod (s : multiset R[X]) (x : R) : eval x s.prod = (s.map (eval x)).prod := (eval_ring_hom x).map_multiset_prod s /-- Polynomial evaluation commutes with `finset.prod` -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → R[X]) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := (eval_ring_hom x).map_prod _ _ lemma list_prod_comp (l : list R[X]) (q : R[X]) : l.prod.comp q = (l.map (λ p : R[X], p.comp q)).prod := map_list_prod (comp_ring_hom q) _ lemma multiset_prod_comp (s : multiset R[X]) (q : R[X]) : s.prod.comp q = (s.map (λ p : R[X], p.comp q)).prod := map_multiset_prod (comp_ring_hom q) _ lemma prod_comp {ι : Type*} (s : finset ι) (p : ι → R[X]) (q : R[X]) : (∏ j in s, p j).comp q = ∏ j in s, (p j).comp q := map_prod (comp_ring_hom q) _ _ lemma is_root_prod {R} [comm_ring R] [is_domain R] {ι : Type*} (s : finset ι) (p : ι → R[X]) (x : R) : is_root (∏ j in s, p j) x ↔ ∃ i ∈ s, is_root (p i) x := by simp only [is_root, eval_prod, finset.prod_eq_zero_iff] lemma eval_dvd : p ∣ q → eval x p ∣ eval x q := eval₂_dvd _ _ lemma eval_eq_zero_of_dvd_of_eval_eq_zero : p ∣ q → eval x p = 0 → eval x q = 0 := eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ @[simp] lemma eval_geom_sum {R} [comm_semiring R] {n : ℕ} {x : R} : eval x (∑ i in range n, X ^ i) = ∑ i in range n, x ^ i := by simp [eval_finset_sum] end end eval section map --TODO rename to `map_dvd_map` lemma map_dvd {R S} [semiring R] [comm_semiring S] (f : R →+* S) {x y : R[X]} : x ∣ y → x.map f ∣ y.map f := eval₂_dvd _ _ lemma support_map_subset [semiring R] [semiring S] (f : R →+* S) (p : R[X]) : (map f p).support ⊆ p.support := begin intros x, contrapose!, simp { contextual := tt }, end lemma support_map_of_injective [semiring R] [semiring S] (p : R[X]) {f : R →+* S} (hf : function.injective f) : (map f p).support = p.support := by simp_rw [finset.ext_iff, mem_support_iff, coeff_map, ←map_zero f, hf.ne_iff, iff_self, forall_const] variables [comm_semiring R] [comm_semiring S] (f : R →+* S) protected lemma map_multiset_prod (m : multiset R[X]) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (map_ring_hom f).to_monoid_hom protected lemma map_prod {ι : Type*} (g : ι → R[X]) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := (map_ring_hom f).map_prod _ _ lemma is_root.map {f : R →+* S} {x : R} {p : R[X]} (h : is_root p x) : is_root (p.map f) (f x) := by rw [is_root, eval_map, eval₂_hom, h.eq_zero, f.map_zero] lemma is_root.of_map {R} [comm_ring R] {f : R →+* S} {x : R} {p : R[X]} (h : is_root (p.map f) (f x)) (hf : function.injective f) : is_root p x := by rwa [is_root, ←(injective_iff_map_eq_zero' f).mp hf, ←eval₂_hom, ←eval_map] lemma is_root_map_iff {R : Type*} [comm_ring R] {f : R →+* S} {x : R} {p : R[X]} (hf : function.injective f) : is_root (p.map f) (f x) ↔ is_root p x := ⟨λ h, h.of_map hf, λ h, h.map⟩ end map end comm_semiring section ring variables [ring R] {p q r : R[X]} lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b @[simp] protected lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := (map_ring_hom f).map_sub p q @[simp] protected lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := (map_ring_hom f).map_neg p @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := map_int_cast (map_ring_hom f) n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : R[X]).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : R[X]) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : R[X]) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ @[simp] lemma cast_int_comp (i : ℤ) : comp (i : R[X]) p = i := by cases i; simp end ring end polynomial
4821c26ae3b337b52e04a21bb416c3373c33a799
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/set/semiring.lean
118766638bb4f51a8503ff26a8069983ad0e2e96
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
4,400
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.set.pointwise /-! # Sets as a semiring under union This file defines `set_semiring α`, an alias of `set α`, which we endow with `∪` as addition and pointwise `*` as multiplication. If `α` is a (commutative) monoid, `set_semiring α` is a (commutative) semiring. -/ open function set open_locale pointwise variables {α β : Type*} /-- An alias for `set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ @[derive [inhabited, partial_order, order_bot]] def set_semiring (α : Type*) : Type* := set α /-- The identity function `set α → set_semiring α`. -/ protected def set.up : set α ≃ set_semiring α := equiv.refl _ namespace set_semiring /-- The identity function `set_semiring α → set α`. -/ protected def down : set_semiring α ≃ set α := equiv.refl _ @[simp] protected lemma down_up (s : set α) : s.up.down = s := rfl @[simp] protected lemma up_down (s : set_semiring α) : s.down.up = s := rfl -- TODO: These lemmas are not tagged `simp` because `set.le_eq_subset` simplifies the LHS lemma up_le_up {s t : set α} : s.up ≤ t.up ↔ s ⊆ t := iff.rfl lemma up_lt_up {s t : set α} : s.up < t.up ↔ s ⊂ t := iff.rfl @[simp] lemma down_subset_down {s t : set_semiring α} : s.down ⊆ t.down ↔ s ≤ t := iff.rfl @[simp] lemma down_ssubset_down {s t : set_semiring α} : s.down ⊂ t.down ↔ s < t := iff.rfl instance : add_comm_monoid (set_semiring α) := { add := λ s t, (s.down ∪ t.down).up, zero := (∅ : set α).up, add_assoc := union_assoc, zero_add := empty_union, add_zero := union_empty, add_comm := union_comm } /- Since addition on `set_semiring` is commutative (it is set union), there is no need to also have the instance `covariant_class (set_semiring α) (set_semiring α) (swap (+)) (≤)`. -/ instance covariant_class_add : covariant_class (set_semiring α) (set_semiring α) (+) (≤) := ⟨λ a b c, union_subset_union_right _⟩ section has_mul variables [has_mul α] instance : non_unital_non_assoc_semiring (set_semiring α) := { mul := λ s t, (image2 (*) s.down t.down).up, zero_mul := λ s, empty_mul, mul_zero := λ s, mul_empty, left_distrib := λ _ _ _, mul_union, right_distrib := λ _ _ _, union_mul, ..set_semiring.add_comm_monoid } instance : no_zero_divisors (set_semiring α) := ⟨λ a b ab, a.eq_empty_or_nonempty.imp_right $ λ ha, b.eq_empty_or_nonempty.resolve_right $ λ hb, nonempty.ne_empty ⟨_, mul_mem_mul ha.some_mem hb.some_mem⟩ ab⟩ instance covariant_class_mul_left : covariant_class (set_semiring α) (set_semiring α) (*) (≤) := ⟨λ a b c, mul_subset_mul_left⟩ instance covariant_class_mul_right : covariant_class (set_semiring α) (set_semiring α) (swap (*)) (≤) := ⟨λ a b c, mul_subset_mul_right⟩ end has_mul instance [mul_one_class α] : non_assoc_semiring (set_semiring α) := { one := 1, mul := (*), ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class } instance [semigroup α] : non_unital_semiring (set_semiring α) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup } instance [monoid α] : semiring (set_semiring α) := { ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring } instance [comm_semigroup α] : non_unital_comm_semiring (set_semiring α) := { ..set_semiring.non_unital_semiring, ..set.comm_semigroup } instance [comm_monoid α] : canonically_ordered_comm_semiring (set_semiring α) := { add_le_add_left := λ a b, add_le_add_left, exists_add_of_le := λ a b ab, ⟨b, (union_eq_right_iff_subset.2 ab).symm⟩, le_self_add := subset_union_left, ..set_semiring.semiring, ..set.comm_monoid, ..set_semiring.partial_order _, ..set_semiring.order_bot _, ..set_semiring.no_zero_divisors } /-- The image of a set under a multiplicative homomorphism is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom [mul_one_class α] [mul_one_class β] (f : α →* β) : set_semiring α →+* set_semiring β := { to_fun := image f, map_zero' := image_empty _, map_one' := by rw [image_one, map_one, singleton_one], map_add' := image_union _, map_mul' := λ _ _, image_mul f } end set_semiring
cc8a934c1e9cc6e5e7ee5bcd647b1255cb213407
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/def4.lean
41f238bec565cfd71de5227cc890a78a329b790a
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
422
lean
new_frontend inductive Foo : Bool → Type | Z : Foo false | O : Foo false → Foo true | E : Foo true → Foo false open Foo def toNat : {b : Bool} → Foo b → Nat | _, Z => 0 | _, O n => toNat n + 1 | _, E n => toNat n + 1 example : toNat (E (O Z)) = 2 := rfl example : toNat Z = 0 := rfl example (a : Foo false) : toNat (O a) = toNat a + 1 := rfl example (a : Foo true) : toNat (E a) = toNat a + 1 := rfl
6c9bd0df18c5dced7b02593a81266ea8703e5420
1437b3495ef9020d5413178aa33c0a625f15f15f
/category_theory/opposites.lean
95122d5bd7aaea035722ae4a74375a198a60fbea
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,047
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.types namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation def op (C : Type u₁) : Type u₁ := C notation C `ᵒᵖ`:80 := op C variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 instance opposite : category.{v₁} (Cᵒᵖ) := { hom := λ X Y : C, Y ⟶ X, comp := λ _ _ _ f g, g ≫ f, id := λ X, 𝟙 X } def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, X, map := λ X Y f, f } -- TODO this is an equivalence namespace functor section variables {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒟 variables {C D} protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, F.obj X, map := λ X Y f, F.map f, map_id' := begin /- `obviously'` says: -/ intros, erw [map_id], refl, end, map_comp' := begin /- `obviously'` says: -/ intros, erw [map_comp], refl end } @[simp] lemma op_obj (F : C ⥤ D) (X : C) : (F.op).obj X = F.obj X := rfl @[simp] lemma op_map (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : (F.op).map f = F.map f := rfl protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, F.obj X, map := λ X Y f, F.map f, map_id' := F.map_id, map_comp' := by intros; apply F.map_comp } @[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = F.obj X := rfl @[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = F.map f := rfl variables (C D) definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, F.op, map := λ F G α, { app := λ X, α.app X, naturality' := λ X Y f, eq.symm (α.naturality f) } } @[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = F.op := rfl @[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : C) : ((op_hom C D).map α).app X = α.app X := rfl definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F : Cᵒᵖ ⥤ Dᵒᵖ, F.unop, map := λ F G α, { app := λ X : C, α.app X, naturality' := λ X Y f, eq.symm (α.naturality f) } } @[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = F.unop := rfl @[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) : ((op_inv C D).map α).app X = α.app X := rfl -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, F.preimage f } instance {F : C ⥤ D} [faithful F] : faithful F.op := { injectivity' := λ X Y f g h, by simpa using injectivity F h } @[simp] lemma preimage_id (F : C ⥤ D) [fully_faithful F] (X : C) : F.preimage (𝟙 (F.obj X)) = 𝟙 X := injectivity F (by simp) end namespace category variables {C} {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒟 @[simp] lemma op_id_app (F : (C ⥤ D)ᵒᵖ) (X : C) : (𝟙 F : F ⟹ F).app X = 𝟙 (F.obj X) := rfl @[simp] lemma op_comp_app {F G H : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (β : G ⟶ H) (X : C) : ((α ≫ β) : H ⟹ F).app X = (β : H ⟹ G).app X ≫ (α : G ⟹ F).app X := rfl end category section variable (C) /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : (Cᵒᵖ × C) ⥤ (Type v₁) := { obj := λ p, @category.hom C _ p.1 p.2, map := λ X Y f, λ h, f.1 ≫ h ≫ f.2, map_id' := by intros; ext; dsimp [category_theory.opposite]; simp, map_comp' := by intros; ext; dsimp [category_theory.opposite]; simp } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (functor.hom C).obj X = @category.hom C _ X.1 X.2 := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (functor.hom C).map f = λ h, f.1 ≫ h ≫ f.2 := rfl end end functor end category_theory
6380f9ec5f6b6e4666656b4cf6f3e7e509ddf758
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/abelian/pseudoelements_auto.lean
ccc364c54ac10ef7a05d125dc96b1e823da5520c
[]
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
13,913
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.abelian.exact import Mathlib.category_theory.over import Mathlib.PostPort universes v u namespace Mathlib /-! # Pseudoelements in abelian categories A *pseudoelement* of an object `X` in an abelian category `C` is an equivalence class of arrows ending in `X`, where two arrows are considered equivalent if we can find two epimorphisms with a common domain making a commutative square with the two arrows. While the construction shows that pseudoelements are actually subobjects of `X` rather than "elements", it is possible to chase these pseudoelements through commutative diagrams in an abelian category to prove exactness properties. This is done using some "diagram-chasing metatheorems" proved in this file. In many cases, a proof in the category of abelian groups can more or less directly be converted into a proof using pseudoelements. A classic application of pseudoelements are diagram lemmas like the four lemma or the snake lemma. Pseudoelements are in some ways weaker than actual elements in a concrete category. The most important limitation is that there is no extensionality principle: If `f g : X ⟶ Y`, then `∀ x ∈ X, f x = g x` does not necessarily imply that `f = g` (however, if `f = 0` or `g = 0`, it does). A corollary of this is that we can not define arrows in abelian categories by dictating their action on pseudoelements. Thus, a usual style of proofs in abelian categories is this: First, we construct some morphism using universal properties, and then we use diagram chasing of pseudoelements to verify that is has some desirable property such as exactness. It should be noted that the Freyd-Mitchell embedding theorem gives a vastly stronger notion of pseudoelement (in particular one that gives extensionality). However, this theorem is quite difficult to prove and probably out of reach for a formal proof for the time being. ## Main results We define the type of pseudoelements of an object and, in particular, the zero pseudoelement. We prove that every morphism maps the zero pseudoelement to the zero pseudoelement (`apply_zero`) and that a zero morphism maps every pseudoelement to the zero pseudoelement (`zero_apply`) Here are the metatheorems we provide: * A morphism `f` is zero if and only if it is the zero function on pseudoelements. * A morphism `f` is an epimorphism if and only if it is surjective on pseudoelements. * A morphism `f` is a monomorphism if and only if it is injective on pseudoelements if and only if `∀ a, f a = 0 → f = 0`. * A sequence `f, g` of morphisms is exact if and only if `∀ a, g (f a) = 0` and `∀ b, g b = 0 → ∃ a, f a = b`. * If `f` is a morphism and `a, a'` are such that `f a = f a'`, then there is some pseudoelement `a''` such that `f a'' = 0` and for every `g` we have `g a' = 0 → g a = g a''`. We can think of `a''` as `a - a'`, but don't get too carried away by that: pseudoelements of an object do not form an abelian group. ## Notations We introduce coercions from an object of an abelian category to the set of its pseudoelements and from a morphism to the function it induces on pseudoelements. These coercions must be explicitly enabled via local instances: `local attribute [instance] object_to_sort hom_to_fun` ## Implementation notes It appears that sometimes the coercion from morphisms to functions does not work, i.e., writing `g a` raises a "function expected" error. This error can be fixed by writing `(g : X ⟶ Y) a`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ namespace category_theory.abelian /-- This is just composition of morphisms in `C`. Another way to express this would be `(over.map f).obj a`, but our definition has nicer definitional properties. -/ def app {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) (a : over P) : over Q := ↑(comma.hom a ≫ f) @[simp] theorem app_hom {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) (a : over P) : comma.hom (app f a) = comma.hom a ≫ f := rfl /-- Two arrows `f : X ⟶ P` and `g : Y ⟶ P are called pseudo-equal if there is some object `R` and epimorphisms `p : R ⟶ X` and `q : R ⟶ Y` such that `p ≫ f = q ≫ g`. -/ def pseudo_equal {C : Type u} [category C] (P : C) (f : over P) (g : over P) := ∃ (R : C), ∃ (p : R ⟶ comma.left f), ∃ (q : R ⟶ comma.left g), Exists (Exists (p ≫ comma.hom f = q ≫ comma.hom g)) theorem pseudo_equal_refl {C : Type u} [category C] {P : C} : reflexive (pseudo_equal P) := sorry theorem pseudo_equal_symm {C : Type u} [category C] {P : C} : symmetric (pseudo_equal P) := sorry /-- Pseudoequality is transitive: Just take the pullback. The pullback morphisms will be epimorphisms since in an abelian category, pullbacks of epimorphisms are epimorphisms. -/ theorem pseudo_equal_trans {C : Type u} [category C] [abelian C] {P : C} : transitive (pseudo_equal P) := sorry /-- The arrows with codomain `P` equipped with the equivalence relation of being pseudo-equal. -/ def pseudoelement.setoid {C : Type u} [category C] [abelian C] (P : C) : setoid (over P) := setoid.mk (pseudo_equal P) sorry /-- A `pseudoelement` of `P` is just an equivalence class of arrows ending in `P` by being pseudo-equal. -/ def pseudoelement {C : Type u} [category C] [abelian C] (P : C) := quotient sorry namespace pseudoelement /-- A coercion from an object of an abelian category to its pseudoelements. -/ def object_to_sort {C : Type u} [category C] [abelian C] : has_coe_to_sort C := has_coe_to_sort.mk (Type (max u v)) fun (P : C) => pseudoelement P /-- A coercion from an arrow with codomain `P` to its associated pseudoelement. -/ def over_to_sort {C : Type u} [category C] [abelian C] {P : C} : has_coe (over P) (pseudoelement P) := has_coe.mk (Quot.mk (pseudo_equal P)) theorem over_coe_def {C : Type u} [category C] [abelian C] {P : C} {Q : C} (a : Q ⟶ P) : ↑a = quotient.mk ↑a := rfl /-- If two elements are pseudo-equal, then their composition with a morphism is, too. -/ theorem pseudo_apply_aux {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) (a : over P) (b : over P) : a ≈ b → app f a ≈ app f b := sorry /-- A morphism `f` induces a function `pseudo_apply f` on pseudoelements. -/ def pseudo_apply {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : ↥P → ↥Q := quotient.map (fun (g : over P) => app f g) (pseudo_apply_aux f) /-- A coercion from morphisms to functions on pseudoelements -/ def hom_to_fun {C : Type u} [category C] [abelian C] {P : C} {Q : C} : has_coe_to_fun (P ⟶ Q) := has_coe_to_fun.mk (fun (x : P ⟶ Q) => ↥P → ↥Q) pseudo_apply theorem pseudo_apply_mk {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) (a : over P) : coe_fn f (quotient.mk a) = quotient.mk ↑(comma.hom a ≫ f) := rfl /-- Applying a pseudoelement to a composition of morphisms is the same as composing with each morphism. Sadly, this is not a definitional equality, but at least it is true. -/ theorem comp_apply {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) (a : ↥P) : coe_fn (f ≫ g) a = coe_fn g (coe_fn f a) := sorry /-- Composition of functions on pseudoelements is composition of morphisms. -/ theorem comp_comp {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) : ⇑g ∘ ⇑f = ⇑(f ≫ g) := funext fun (x : ↥P) => Eq.symm (comp_apply f g x) /-! In this section we prove that for every `P` there is an equivalence class that contains precisely all the zero morphisms ending in `P` and use this to define *the* zero pseudoelement. -/ /-- The arrows pseudo-equal to a zero morphism are precisely the zero morphisms -/ theorem pseudo_zero_aux {C : Type u} [category C] [abelian C] {P : C} (Q : C) (f : over P) : f ≈ ↑0 ↔ comma.hom f = 0 := sorry theorem zero_eq_zero' {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} : quotient.mk ↑0 = quotient.mk ↑0 := quotient.sound (iff.mpr (pseudo_zero_aux R ↑0) rfl) /-- The zero pseudoelement is the class of a zero morphism -/ def pseudo_zero {C : Type u} [category C] [abelian C] {P : C} : ↥P := quotient.mk ↑0 protected instance has_zero {C : Type u} [category C] [abelian C] {P : C} : HasZero ↥P := { zero := pseudo_zero } protected instance inhabited {C : Type u} [category C] [abelian C] {P : C} : Inhabited (pseudoelement P) := { default := 0 } theorem pseudo_zero_def {C : Type u} [category C] [abelian C] {P : C} : 0 = quotient.mk ↑0 := rfl @[simp] theorem zero_eq_zero {C : Type u} [category C] [abelian C] {P : C} {Q : C} : quotient.mk ↑0 = 0 := zero_eq_zero' /-- The pseudoelement induced by an arrow is zero precisely when that arrow is zero -/ theorem pseudo_zero_iff {C : Type u} [category C] [abelian C] {P : C} (a : over P) : ↑a = 0 ↔ comma.hom a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑a = 0 ↔ comma.hom a = 0)) (Eq.symm (propext (pseudo_zero_aux P a))))) quotient.eq /-- Morphisms map the zero pseudoelement to the zero pseudoelement -/ @[simp] theorem apply_zero {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : coe_fn f 0 = 0 := sorry /-- The zero morphism maps every pseudoelement to 0. -/ @[simp] theorem zero_apply {C : Type u} [category C] [abelian C] {P : C} (Q : C) (a : ↥P) : coe_fn 0 a = 0 := sorry /-- An extensionality lemma for being the zero arrow. -/ theorem zero_morphism_ext {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : (∀ (a : ↥P), coe_fn f a = 0) → f = 0 := fun (h : ∀ (a : ↥P), coe_fn f a = 0) => eq.mpr (id (Eq._oldrec (Eq.refl (f = 0)) (Eq.symm (category.id_comp f)))) (iff.mp (pseudo_zero_iff ↑(𝟙 ≫ f)) (h ↑𝟙)) theorem zero_morphism_ext' {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : (∀ (a : ↥P), coe_fn f a = 0) → 0 = f := Eq.symm ∘ zero_morphism_ext f theorem eq_zero_iff {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : f = 0 ↔ ∀ (a : ↥P), coe_fn f a = 0 := sorry /-- A monomorphism is injective on pseudoelements. -/ theorem pseudo_injective_of_mono {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) [mono f] : function.injective ⇑f := sorry /-- A morphism that is injective on pseudoelements only maps the zero element to zero. -/ theorem zero_of_map_zero {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : function.injective ⇑f → ∀ (a : ↥P), coe_fn f a = 0 → a = 0 := fun (h : function.injective ⇑f) (a : ↥P) (ha : coe_fn f a = 0) => h (eq.mp (Eq._oldrec (Eq.refl (coe_fn f a = 0)) (Eq.symm (apply_zero f))) ha) /-- A morphism that only maps the zero pseudoelement to zero is a monomorphism. -/ theorem mono_of_zero_of_map_zero {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : (∀ (a : ↥P), coe_fn f a = 0 → a = 0) → mono f := sorry /-- An epimorphism is surjective on pseudoelements. -/ theorem pseudo_surjective_of_epi {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) [epi f] : function.surjective ⇑f := sorry /-- A morphism that is surjective on pseudoelements is an epimorphism. -/ theorem epi_of_pseudo_surjective {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) : function.surjective ⇑f → epi f := sorry /-- Two morphisms in an exact sequence are exact on pseudoelements. -/ theorem pseudo_exact_of_exact {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} {f : P ⟶ Q} {g : Q ⟶ R} [exact f g] : (∀ (a : ↥P), coe_fn g (coe_fn f a) = 0) ∧ ∀ (b : ↥Q), coe_fn g b = 0 → ∃ (a : ↥P), coe_fn f a = b := sorry theorem apply_eq_zero_of_comp_eq_zero {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} (f : Q ⟶ R) (a : P ⟶ Q) : a ≫ f = 0 → coe_fn f ↑a = 0 := sorry /-- If two morphisms are exact on pseudoelements, they are exact. -/ theorem exact_of_pseudo_exact {C : Type u} [category C] [abelian C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) : ((∀ (a : ↥P), coe_fn g (coe_fn f a) = 0) ∧ ∀ (b : ↥Q), coe_fn g b = 0 → ∃ (a : ↥P), coe_fn f a = b) → exact f g := sorry /-- If two pseudoelements `x` and `y` have the same image under some morphism `f`, then we can form their "difference" `z`. This pseudoelement has the properties that `f z = 0` and for all morphisms `g`, if `g y = 0` then `g z = g x`. -/ theorem sub_of_eq_image {C : Type u} [category C] [abelian C] {P : C} {Q : C} (f : P ⟶ Q) (x : ↥P) (y : ↥P) : coe_fn f x = coe_fn f y → ∃ (z : ↥P), coe_fn f z = 0 ∧ ∀ (R : C) (g : P ⟶ R), coe_fn g y = 0 → coe_fn g z = coe_fn g x := sorry /-- If `f : P ⟶ R` and `g : Q ⟶ R` are morphisms and `p : P` and `q : Q` are pseudoelements such that `f p = g q`, then there is some `s : pullback f g` such that `fst s = p` and `snd s = q`. Remark: Borceux claims that `s` is unique. I was unable to transform his proof sketch into a pen-and-paper proof of this fact, so naturally I was not able to formalize the proof. -/ theorem pseudo_pullback {C : Type u} [category C] [abelian C] [limits.has_pullbacks C] {P : C} {Q : C} {R : C} {f : P ⟶ R} {g : Q ⟶ R} {p : ↥P} {q : ↥Q} : coe_fn f p = coe_fn g q → ∃ (s : ↥(limits.pullback f g)), coe_fn limits.pullback.fst s = p ∧ coe_fn limits.pullback.snd s = q := sorry end Mathlib
13a789b749f77abe14b838afdd1b11421bdb1ce4
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/category/Module/basic.lean
e62e57eb55189ee7f09b67f45e1c071cd1c3b220
[ "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
9,776
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.category.Group.basic import category_theory.concrete_category import category_theory.limits.shapes.kernels import category_theory.preadditive import linear_algebra.basic /-! # The category of `R`-modules `Module.{v} R` is the category of bundled `R`-modules with carrier in the universe `v`. We show that it is preadditive and show that being an isomorphism, monomorphism and epimorphism is equivalent to being a linear equivalence, an injective linear map and a surjective linear map, respectively. ## Implementation details To construct an object in the category of `R`-modules from a type `M` with an instance of the `module` typeclass, write `of R M`. There is a coercion in the other direction. Similarly, there is a coercion from morphisms in `Module R` to linear maps. Unfortunately, Lean is not smart enough to see that, given an object `M : Module R`, the expression `of R M`, where we coerce `M` to the carrier type, is definitionally equal to `M` itself. This means that to go the other direction, i.e., from linear maps/equivalences to (iso)morphisms in the category of `R`-modules, we have to take care not to inadvertently end up with an `of R M` where `M` is already an object. Hence, given `f : M →ₗ[R] N`, * if `M N : Module R`, simply use `f`; * if `M : Module R` and `N` is an unbundled `R`-module, use `↿f` or `as_hom_left f`; * if `M` is an unbundled `R`-module and `N : Module R`, use `↾f` or `as_hom_right f`; * if `M` and `N` are unbundled `R`-modules, use `↟f` or `as_hom f`. Similarly, given `f : M ≃ₗ[R] N`, use `to_Module_iso`, `to_Module_iso'_left`, `to_Module_iso'_right` or `to_Module_iso'`, respectively. The arrow notations are localized, so you may have to `open_locale Module` to use them. Note that the notation for `as_hom_left` clashes with the notation used to promote functions between types to morphisms in the category `Type`, so to avoid confusion, it is probably a good idea to avoid having the locales `Module` and `category_theory.Type` open at the same time. If you get an error when trying to apply a theorem and the `convert` tactic produces goals of the form `M = of R M`, then you probably used an incorrect variant of `as_hom` or `to_Module_iso`. -/ open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universes v u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. -/ structure Module := (carrier : Type v) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module instance : has_coe_to_sort (Module.{v} R) := { S := Type v, coe := Module.carrier } instance Module_category : category (Module.{v} R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f } instance Module_concrete_category : concrete_category.{v} (Module.{v} R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup := { forget₂ := { obj := λ M, AddCommGroup.of M, map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type v) [add_comm_group X] [module R X] : Module R := ⟨X⟩ instance : has_zero (Module R) := ⟨of R punit⟩ instance : inhabited (Module R) := ⟨0⟩ @[simp] lemma coe_of (X : Type u) [add_comm_group X] [module R X] : (of R X : Type u) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[simps] def of_self_iso (M : Module R) : Module.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } instance : subsingleton (of R punit) := by { rw coe_of R punit, apply_instance } instance : has_zero_object (Module.{v} R) := { zero := 0, unique_to := λ X, { default := (0 : punit →ₗ[R] X), uniq := λ _, linear_map.ext $ λ x, have h : x = 0, from dec_trivial, by simp only [h, linear_map.map_zero]}, unique_from := λ X, { default := (0 : X →ₗ[R] punit), uniq := λ _, linear_map.ext $ λ x, dec_trivial } } variables {R} {M N U : Module.{v} R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl lemma comp_def (f : M ⟶ N) (g : N ⟶ U) : f ≫ g = g.comp f := rfl end Module variables {R} variables {X₁ X₂ : Type v} /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom [add_comm_group X₁] [module R X₁] [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ Module.of R X₂) := id localized "notation `↟` f : 1024 := Module.as_hom f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_right [add_comm_group X₁] [module R X₁] {X₂ : Module.{v} R} : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ X₂) := id localized "notation `↾` f : 1024 := Module.as_hom_right f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_left {X₁ : Module.{v} R} [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (X₁ ⟶ Module.of R X₂) := id localized "notation `↿` f : 1024 := Module.as_hom_left f" in Module /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/ @[simps] def linear_equiv.to_Module_iso {g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso' {M N : Module.{v} R} (i : M ≃ₗ[R] N) : M ≅ N := { hom := i, inv := i.symm, hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_left {X₁ : Module.{v} R} {g₂ : add_comm_group X₂} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_right {g₁ : add_comm_group X₁} {m₁ : module R X₁} {X₂ : Module.{v} R} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } namespace category_theory.iso /-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/ @[simps] def to_linear_equiv {X Y : Module R} (i : X ≅ Y) : X ≃ₗ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_smul' := by tidy, }. end category_theory.iso /-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/ @[simps] def linear_equiv_iso_Module_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] : (X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) := { hom := λ e, e.to_Module_iso, inv := λ i, i.to_linear_equiv, } namespace Module section preadditive instance : preadditive (Module.{v} R) := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } end preadditive section epi_mono variables {M N : Module.{v} R} (f : M ⟶ N) lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := linear_map.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ ↟u ↟v).1 lemma range_eq_top_of_epi [epi f] : f.range = ⊤ := linear_map.range_eq_top_of_cancel $ λ u v, (@cancel_epi _ _ _ _ _ f _ ↟u ↟v).1 lemma mono_of_ker_eq_bot (hf : f.ker = ⊥) : mono f := concrete_category.mono_of_injective _ $ linear_map.ker_eq_bot.1 hf lemma epi_of_range_eq_top (hf : f.range = ⊤) : epi f := concrete_category.epi_of_surjective _ $ linear_map.range_eq_top.1 hf instance mono_as_hom'_subtype (U : submodule R M) : mono ↾U.subtype := mono_of_ker_eq_bot _ (submodule.ker_subtype U) instance epi_as_hom''_mkq (U : submodule R M) : epi ↿U.mkq := epi_of_range_eq_top _ $ submodule.range_mkq _ end epi_mono end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩
5c13141c702a267350149f94fb4bc0bcb0a7cb38
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/group_power.lean
6a2b57e383d93399746b2c3ec1e9824c011a1763
[ "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
29,721
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import data.int.basic import data.equiv.basic /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. ## Implementation details We adopt the convention that `0^0 = 1`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n • a = a+a+...+a` n times. -/ def add_monoid.smul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ { one := (0 : A) } a n precedence `•`:70 localized "infix ` • ` := add_monoid.smul" in add_monoid @[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : A) : 0 • a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : A) (n : ℕ) : (n+1)•a = a + n•a := rfl @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : A) : 1•a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : A) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : A) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul' (a : A) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : A) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative A) _ @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : A) = 0 := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : A) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : A) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] @[simp] theorem add_monoid.smul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n • (1 : A), add_monoid.zero_smul _, λ _ _, add_monoid.add_smul _ _ _⟩ (add_monoid.one_smul _) theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : A) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : A) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : A) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative A) _ @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative A) _ theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] theorem monoid_hom.iterate_map_pow (f : M →* M) (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := show f^[n] ((λ x, x^m) a) = (λ x, x^m) (f^[n] a), from nat.iterate₁ $ λ x, f.map_pow x m theorem add_monoid_hom.map_smul (f : A →+ B) (a : A) (n : ℕ) : f (n • a) = n • f a := f.to_multiplicative.map_pow a n theorem add_monoid_hom.iterate_map_smul (f : A →+ A) (a : A) (n m : ℕ) : f^[n] (m • a) = m • (f^[n] a) := f.to_multiplicative.iterate_map_pow a n m theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_smul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n • a) = n • f a := (add_monoid_hom.of f).map_smul a n @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n end monoid @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : A) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : A → A) := { map_add := λ _ _, add_monoid.smul_add _ _ _, map_zero := add_monoid.smul_zero _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : A) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n)•a = m•a - n•a := @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : A) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative A) _ end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `add_monoid.smul` to negative integers with the definition `(-n) • a = -(n • a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n @[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ localized "infix ` • `:70 := gsmul" in add_group localized "infix ` •ℕ `:70 := add_monoid.smul" in smul localized "infix ` •ℤ `:70 := gsmul" in smul @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n • a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : A) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) • a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : A) : (1:ℤ) • a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x theorem gsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n private lemma gpow_add_aux (a : G) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : G) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative A) _ theorem gpow_add_one (a : G) (i : ℤ) : a ^ (i + 1) = a ^ i * a := by rw [gpow_add, gpow_one] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative A) _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative A) _ theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n • a) = n • f a := f.to_multiplicative.map_gpow a n end group open_locale smul section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group @[simp] lemma with_bot.coe_smul [add_monoid A] (a : A) (n : ℕ) : ((add_monoid.smul n a : A) : with_bot A) = add_monoid.smul n a := add_monoid_hom.map_smul ⟨_, with_bot.coe_zero, with_bot.coe_add⟩ a n theorem add_monoid.smul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a variable (f : R →+* R) lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by { simp only [nat.iterate_succ', pow_succ', coe_mul, coe_pow n], refl } lemma iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := f.to_monoid_hom.iterate_map_pow a n m lemma iterate_map_smul (a) (n m : ℕ) : f^[n] (m • a) = m • (f^[n] a) := f.to_add_monoid_hom.iterate_map_smul a n m end ring_hom lemma is_semiring_hom.map_pow [semiring R] [semiring S] (f : R → S) [is_semiring_hom f] (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := is_monoid_hom.map_pow f a theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [comm_semiring R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [domain R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[field_simps] theorem pow_ne_zero [domain R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h theorem add_monoid.smul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] namespace add_monoid variable [ordered_add_comm_monoid A] theorem smul_le_smul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := let ⟨k, hk⟩ := nat.le.dest h in calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _) ... = m • a : by rw [← hk, add_smul] lemma smul_le_smul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b | 0 := by simp | (k+1) := add_le_add' hab (smul_le_smul_of_le_right _) end add_monoid namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := canonically_ordered_semiring.zero_lt_one | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) • a ≤ (1 + a) * (1 + n • a) : by simpa [succ_smul, mul_add, add_mul, add_monoid.mul_smul_left, add_comm, add_left_comm] using add_monoid.smul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n • (a * a * (2 + a)) + a * a, from add_nonneg (add_monoid.smul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) • a ≤ 1 + (n + 2) • a + (n • (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n • a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_smul, add_monoid.smul_add, add_monoid.mul_smul_assoc, (add_monoid.mul_smul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma of_add_smul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n • x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_smul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, add_monoid.zero_smul x, λ m n, add_monoid.add_smul _ _ _⟩, inv_fun := λ f, f 1, left_inv := add_monoid.one_smul, right_inv := λ f, add_monoid_hom.ext $ λ n, by simp [← f.map_smul] } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext $ λ n, by simp [← f.map_gsmul] } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h]
bbb42d13af069ec35437ded74827e9225241d4b5
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/outer_measure.lean
dbcfd1474c0af2c0f2768cdf68d2af6a00f08d4a
[ "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
19,846
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 Outer measures -- overapproximations of measures -/ import analysis.specific_limits import measure_theory.measurable_space noncomputable theory open set finset function filter encodable open_locale classical namespace measure_theory structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑'i, measure_of (s i))) namespace outer_measure instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0) {β} [encodable β] (s : β → set α) : (∑' b, m (s b)) = ∑' i, m (⋃ b ∈ decode2 β i, s b) := begin have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some, { intros n h, cases decode2 β n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 β n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑'i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := begin convert m.Union (λ b, cond b s₁ s₂), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ @[ext] lemma ext : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, by simp } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≤ (∑' (i : ℕ), m.val (f i)) : m.val.Union_nat _ ... ≤ (∑'i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩ protected lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩ protected lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ protected lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := outer_measure.Sup_le $ assume m' h', h' _ hm protected lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := outer_measure.le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, outer_measure.le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, outer_measure.Sup_le, le_Sup := assume s m, outer_measure.le_Sup, Inf := Inf, Inf_le := assume s m, outer_measure.Inf_le, le_Inf := assume s m, outer_measure.le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, outer_measure.le_Sup $ by simp, le_sup_right := assume a b, outer_measure.le_Sup $ by simp, sup_le := assume a b c ha hb, outer_measure.Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, outer_measure.Inf_le $ by simp, inf_le_right := assume a b, outer_measure.Inf_le $ by simp, le_inf := assume a b c ha hb, outer_measure.le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ λ i, le_supr (λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {β} (f : α → β) (m : outer_measure α) : outer_measure β := { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β, map} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl instance : has_scalar ennreal (outer_measure α) := ⟨λ a m, { measure_of := λs, a * m s, empty := by simp, mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := λ s, by rw ennreal.tsum_mul_left; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) : (a • m) s = a * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _, add_smul := λ a b m, ext $ λ s, add_mul _ _ _, mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _, one_smul := λ m, ext $ λ s, one_mul _, zero_smul := λ m, ext $ λ s, zero_mul _, smul_zero := λ a, ext $ λ s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := h in top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑'i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑'i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑'i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq, add_comm] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Caratheodory measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma is_caratheodory {s : set α} : caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set α} : caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀) in (is_caratheodory_le o).2 $ λ t, le_infi $ λ f, le_infi $ λ hf, begin refine le_trans (add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨆(h : s.nonempty), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s @[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 := by simp [Inf_gen, empty_not_nonempty] lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t.nonempty) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin cases t.eq_empty_or_nonempty with ht ht, { simp [ht], refine (bot_unique $ infi_le_of_le μ $ _).symm, refine infi_le_of_le h (le_refl ⊥) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (_root_.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _); cases t.eq_empty_or_nonempty with ht ht; simp [ht, Inf_gen_nonempty1], { assume μ hμ, exact (show Inf m ≤ μ, from _root_.Inf_le hμ) t }, { exact infi_le_of_le μ (infi_le _ hμ) } end end Inf_gen end outer_measure end measure_theory
94450b0aa29daf41a502bf54f18520bb1d4c405d
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/preadditive/schur.lean
2ee5e3ae131fcc0ab9bbd9e53ee156797ae2c951
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
1,979
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.simple import category_theory.preadditive /-! # Schur's lemma We prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. ## TODO If the category is enriched over finite dimensional vector spaces over an algebraically closed field, then we can further prove that `dim (X ⟶ Y) ≤ 1`. (Probably easiest to prove this for endomorphisms first: some polynomial `p` in `f : X ⟶ X` vanishes by finite dimensionality, that polynomial factors linearly, and at least one factor must be non-invertible, hence zero, so `f` is a scalar multiple of the identity. Then for any two nonzero `f g : X ⟶ Y`, observe `f ≫ g⁻¹` is a multiple of the identity.) -/ namespace category_theory open category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables [preadditive C] [has_kernels C] /-- Schur's Lemma (for a general preadditive category), that a nonzero morphism between simple objects is an isomorphism. -/ def is_iso_of_hom_simple {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f := begin haveI : mono f := preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w), exact is_iso_of_mono_of_nonzero w end /-- As a corollary of Schur's lemma, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ def is_iso_equiv_nonzero {X Y : C} [simple.{v} X] [simple.{v} Y] {f : X ⟶ Y} : is_iso.{v} f ≃ (f ≠ 0) := { to_fun := λ I, begin introI h, apply id_nonzero X, simp only [←is_iso.hom_inv_id f, h, has_zero_morphisms.zero_comp], end, inv_fun := λ w, is_iso_of_hom_simple w, left_inv := λ I, subsingleton.elim _ _, right_inv := λ w, rfl } end category_theory
689f8563d5451a72ee961936b2b7247fdfebb8e5
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/metric_space/gromov_hausdorff_realized.lean
0799e37f1c6b51038aef43c6d65ac97c78ce3324
[ "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
26,989
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.bounded_continuous_function topology.metric_space.gluing topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) set_option class.instance_max_depth 50 local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw real.dist_eq, apply abs_le_of_le_of_neg_le, { exact candidates_lipschitz_aux fA }, { have : -(f (x, y) - f (z, t)) = f (z, t) - f (x, y), by ring, rw [this, dist_comm], exact candidates_lipschitz_aux fA } end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (supr (λx:α, infi (λy:β, f (inl x, inr y)))) (supr (λy:β, infi (λx:α, f (inl x, inr y)))) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), infi (λy:β, f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc infi (λy:β, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), infi (λx:α, f (inl x, inr y) + C))) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc infi (λx:α, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : infi (λy:β, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : infi (λx:α, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, infi (λy:β, g (inl x, inr y)) + dist f g = infi ((λz, z + dist f g) ∘ (λy:β, (g (inl x, inr y)))), { assume x, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g = supr ((λz, z + dist f g) ∘ (λx:α, infi (λy:β, g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y) + dist f g)) := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, infi (λx:α, g (inl x, inr y)) + dist f g = infi ((λz, z + dist f g) ∘ (λx:α, (g (inl x, inr y)))), { assume y, refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g = supr ((λz, z + dist f g) ∘ (λy:β, infi (λx:α, g (inl x, inr y)))), { refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _, { exact continuous_id.add continuous_const }, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) ≤ supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) ≤ supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
ff06915097438fcc6614e8f30784153f89c55bad
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/succ_pred.lean
80d7312b5cede8bcd69f3c93a4a301a33d09b1e0
[ "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
1,588
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.succ_pred /-! # Successors and predecessors of naturals In this file, we show that `ℕ` is both an archimedean `succ_order` and an archimedean `pred_order`. -/ open function nat @[reducible] -- so that Lean reads `nat.succ` through `succ_order.succ` instance : succ_order ℕ := { succ := succ, ..succ_order.of_succ_le_iff succ (λ a b, iff.rfl) } @[reducible] -- so that Lean reads `nat.pred` through `pred_order.pred` instance : pred_order ℕ := { pred := pred, pred_le := pred_le, minimal_of_le_pred := λ a ha b h, begin cases a, { exact b.not_lt_zero h }, { exact nat.lt_irrefl a ha } end, le_pred_of_lt := λ a b h, begin cases b, { exact (a.not_lt_zero h).elim }, { exact le_of_succ_le_succ h } end, le_of_pred_lt := λ a b h, begin cases a, { exact b.zero_le }, { exact h } end } lemma nat.succ_iterate (a : ℕ) : ∀ n, succ^[n] a = a + n | 0 := rfl | (n + 1) := by { rw [function.iterate_succ', add_succ], exact congr_arg _ n.succ_iterate } lemma nat.pred_iterate (a : ℕ) : ∀ n, pred^[n] a = a - n | 0 := rfl | (n + 1) := by { rw [function.iterate_succ', sub_succ], exact congr_arg _ n.pred_iterate } instance : is_succ_archimedean ℕ := ⟨λ a b h, ⟨b - a, by rw [nat.succ_iterate, add_sub_cancel_of_le h]⟩⟩ instance : is_pred_archimedean ℕ := ⟨λ a b h, ⟨b - a, by rw [nat.pred_iterate, sub_sub_cancel_of_le h]⟩⟩
9bc5b8d8924cbc0c07a725c7555ec5e774f92bcf
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/run/newfrontend1.lean
5b83599338c9209597b3ebd3bf55809ae2ac44d8
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,086
lean
def x := 1 new_frontend #check x variables {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check tst #check (fun stx => if True then let e := stx; HasPure.pure e else HasPure.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 := begin assumption end theorem simple2 (x y : Nat) : x = y → x = y := begin intro h; assumption end syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := begin intro2; assumption end macro intro3 : 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 := begin intro3; assumption end theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; exact Eq.trans h3 h1 end theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans _ h1; assumption end theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans ?pre ?post; exact y; { exact h3 }; { exact h1 } end theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans ?pre ?post; case post { exact h1 }; case pre { exact h3 }; end theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 _ h3; traceState; { refine Eq.trans ?pre ?post; (exact h1) <|> (exact y; exact h3; assumption) } end 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 := begin intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption end theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro h2; intro h3; apply @Eq.trans; traceState; exact h3; assumption end macro try t:tactic : tactic => `($t <|> skip) syntax "repeat" tactic : tactic macro_rules | `(tactic| repeat $t) => `(tactic| try ($t; repeat $t)) theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; end theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; traceState; apply @Eq.trans; case main.b exact y; traceState; repeat assumption end theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros; apply @Eq.trans; case main.b exact y; repeat assumption end theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 end theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; try (clear x); -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 end macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := begin blabla end 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 [HasAdd α], -- and will fail to generate instance for [HasAdd α] #check @(fun α (s : HasAdd α) (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⟩ def altTst4 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@StateT.failure _ _ _ _, @StateT.orelse _ _ _ _⟩ #check_failure 1 + true /- universes u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option syntaxMaxDepth 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)
ceb3593ca3b118d931c371d88370b169f1ff3fcf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/group_with_zero.lean
7fe892cfd867db391c3559e0eefd65093fb68501
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,213
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.monoid import Mathlib.algebra.group.pi import Mathlib.PostPort universes u_1 u_2 u_3 l namespace Mathlib /-! # Topological group with zero In this file we define `has_continuous_inv'` to be a mixin typeclass a type with `has_inv` and `has_zero` (e.g., a `group_with_zero`) such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. Currently the only example of `has_continuous_inv'` in `mathlib` which is not a normed field is the type `nnnreal` (a.k.a. `ℝ≥0`) of nonnegative real numbers. Then we prove lemmas about continuity of `x ↦ x⁻¹` and `f / g` providing dot-style `*.inv'` and `*.div` operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. As a special case, we provide `*.div_const` operations that require only `group_with_zero` and `has_continuous_mul` instances. All lemmas about `(⁻¹)` use `inv'` in their names because lemmas without `'` are used for `topological_group`s. We also use `'` in the typeclass name `has_continuous_inv'` for the sake of consistency of notation. -/ /-! ### A group with zero with continuous multiplication If `G₀` is a group with zero with continuous `(*)`, then `(/y)` is continuous for any `y`. In this section we prove lemmas that immediately follow from this fact providing `*.div_const` dot-style operations on `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ theorem filter.tendsto.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {l : filter α} {x : G₀} {y : G₀} (hf : filter.tendsto f l (nhds x)) : filter.tendsto (fun (a : α) => f a / y) l (nhds (x / y)) := sorry theorem continuous_at.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} [topological_space α] (hf : continuous f) {y : G₀} : continuous fun (x : α) => f x / y := sorry theorem continuous_within_at.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} [topological_space α] {a : α} (hf : continuous_within_at f s a) {y : G₀} : continuous_within_at (fun (x : α) => f x / y) s a := filter.tendsto.div_const hf theorem continuous_on.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} {s : set α} [topological_space α] (hf : continuous_on f s) {y : G₀} : continuous_on (fun (x : α) => f x / y) s := sorry theorem continuous.div_const {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_mul G₀] {f : α → G₀} [topological_space α] (hf : continuous f) {y : G₀} : continuous fun (x : α) => f x / y := sorry /-- A type with `0` and `has_inv` such that `λ x, x⁻¹` is continuous at all nonzero points. Any normed (semi)field has this property. -/ class has_continuous_inv' (G₀ : Type u_3) [HasZero G₀] [has_inv G₀] [topological_space G₀] where continuous_at_inv' : ∀ {x : G₀}, x ≠ 0 → continuous_at has_inv.inv x /-! ### Continuity of `λ x, x⁻¹` at a non-zero point We define `topological_group_with_zero` to be a `group_with_zero` such that the operation `x ↦ x⁻¹` is continuous at all nonzero points. In this section we prove dot-style `*.inv'` lemmas for `filter.tendsto`, `continuous_at`, `continuous_within_at`, `continuous_on`, and `continuous`. -/ theorem tendsto_inv' {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {x : G₀} (hx : x ≠ 0) : filter.tendsto has_inv.inv (nhds x) (nhds (x⁻¹)) := continuous_at_inv' hx theorem continuous_on_inv' {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] : continuous_on has_inv.inv (singleton 0ᶜ) := fun (x : G₀) (hx : x ∈ (singleton 0ᶜ)) => continuous_at.continuous_within_at (continuous_at_inv' hx) /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ theorem filter.tendsto.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {l : filter α} {f : α → G₀} {a : G₀} (hf : filter.tendsto f l (nhds a)) (ha : a ≠ 0) : filter.tendsto (fun (x : α) => f x⁻¹) l (nhds (a⁻¹)) := filter.tendsto.comp (tendsto_inv' ha) hf theorem continuous_within_at.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {s : set α} {a : α} [topological_space α] (hf : continuous_within_at f s a) (ha : f a ≠ 0) : continuous_within_at (fun (x : α) => f x⁻¹) s a := filter.tendsto.inv' hf ha theorem continuous_at.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {a : α} [topological_space α] (hf : continuous_at f a) (ha : f a ≠ 0) : continuous_at (fun (x : α) => f x⁻¹) a := filter.tendsto.inv' hf ha theorem continuous.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} [topological_space α] (hf : continuous f) (h0 : ∀ (x : α), f x ≠ 0) : continuous fun (x : α) => f x⁻¹ := iff.mpr continuous_iff_continuous_at fun (x : α) => filter.tendsto.inv' (continuous.tendsto hf x) (h0 x) theorem continuous_on.inv' {α : Type u_1} {G₀ : Type u_2} [HasZero G₀] [has_inv G₀] [topological_space G₀] [has_continuous_inv' G₀] {f : α → G₀} {s : set α} [topological_space α] (hf : continuous_on f s) (h0 : ∀ (x : α), x ∈ s → f x ≠ 0) : continuous_on (fun (x : α) => f x⁻¹) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.inv' (hf x hx) (h0 x hx) /-! ### Continuity of division If `G₀` is a `group_with_zero` with `x ↦ x⁻¹` continuous at all nonzero points and `(*)`, then division `(/)` is continuous at any point where the denominator is continuous. -/ theorem filter.tendsto.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} {l : filter α} {a : G₀} {b : G₀} (hf : filter.tendsto f l (nhds a)) (hg : filter.tendsto g l (nhds b)) (hy : b ≠ 0) : filter.tendsto (f / g) l (nhds (a / b)) := sorry theorem continuous_within_at.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {s : set α} {a : α} (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h₀ : g a ≠ 0) : continuous_within_at (f / g) s a := filter.tendsto.div hf hg h₀ theorem continuous_on.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) (h₀ : ∀ (x : α), x ∈ s → g x ≠ 0) : continuous_on (f / g) s := fun (x : α) (hx : x ∈ s) => continuous_within_at.div (hf x hx) (hg x hx) (h₀ x hx) /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ theorem continuous_at.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] {a : α} (hf : continuous_at f a) (hg : continuous_at g a) (h₀ : g a ≠ 0) : continuous_at (f / g) a := filter.tendsto.div hf hg h₀ theorem continuous.div {α : Type u_1} {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] {f : α → G₀} {g : α → G₀} [topological_space α] (hf : continuous f) (hg : continuous g) (h₀ : ∀ (x : α), g x ≠ 0) : continuous (f / g) := eq.mpr (id ((fun (f f_1 : α → G₀) (e_3 : f = f_1) => congr_arg continuous e_3) (f / g) (f * (g⁻¹)) (div_eq_mul_inv f g))) (eq.mp (Eq.refl (continuous fun (x : α) => f x * (g x⁻¹))) (continuous.mul hf (continuous.inv' hg h₀))) theorem continuous_on_div {G₀ : Type u_2} [group_with_zero G₀] [topological_space G₀] [has_continuous_inv' G₀] [has_continuous_mul G₀] : continuous_on (fun (p : G₀ × G₀) => prod.fst p / prod.snd p) (set_of fun (p : G₀ × G₀) => prod.snd p ≠ 0) := continuous_on.div continuous_on_fst continuous_on_snd fun (_x : G₀ × G₀) => id
388e010f11bcf819accd69b3a2975695c8ca2c86
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Ring/colimits.lean
1d3bf64ea8c69610b351622624e934d28ab75d31
[ "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
13,306
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Ring.basic import category_theory.limits.has_limits import category_theory.concrete_category.elementwise /-! # The category of commutative rings has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `comm_ring` and `ring_hom`. -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. /- `#print comm_ring` says: structure comm_ring : Type u → Type u fields: comm_ring.zero : Π (α : Type u) [c : comm_ring α], α comm_ring.one : Π (α : Type u) [c : comm_ring α], α comm_ring.neg : Π {α : Type u} [c : comm_ring α], α → α comm_ring.add : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.mul : Π {α : Type u} [c : comm_ring α], α → α → α comm_ring.zero_add : ∀ {α : Type u} [c : comm_ring α] (a : α), 0 + a = a comm_ring.add_zero : ∀ {α : Type u} [c : comm_ring α] (a : α), a + 0 = a comm_ring.one_mul : ∀ {α : Type u} [c : comm_ring α] (a : α), 1 * a = a comm_ring.mul_one : ∀ {α : Type u} [c : comm_ring α] (a : α), a * 1 = a comm_ring.add_left_neg : ∀ {α : Type u} [c : comm_ring α] (a : α), -a + a = 0 comm_ring.add_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a + b = b + a comm_ring.mul_comm : ∀ {α : Type u} [c : comm_ring α] (a b : α), a * b = b * a comm_ring.add_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a + b + c_1 = a + (b + c_1) comm_ring.mul_assoc : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) comm_ring.left_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), a * (b + c_1) = a * b + a * c_1 comm_ring.right_distrib : ∀ {α : Type u} [c : comm_ring α] (a b c_1 : α), (a + b) * c_1 = a * c_1 + b * c_1 -/ namespace CommRing.colimits /-! We build the colimit of a diagram in `CommRing` by constructing the free commutative ring on the disjoint union of all the commutative rings in the diagram, then taking the quotient by the commutative ring laws within each commutative ring, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ CommRing.{v}) /-- An inductive type representing all commutative ring expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | one : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the commutative ring laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | one : Π (j), relation (of j 1) one | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | mul_comm : Π (x y), relation (mul x y) (mul y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | left_distrib : Π (x y z), relation (mul x (add y z)) (add (mul x y) (mul x z)) | right_distrib : Π (x y z), relation (mul (add x y) z) (add (mul x z) (mul y z)) /-- The setoid corresponding to commutative expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `CommRing`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : add_group (colimit_type F) := { zero := begin exact quot.mk _ zero end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end } instance : add_group_with_one (colimit_type F) := { one := begin exact quot.mk _ one end, .. colimit_type.add_group F } instance : comm_ring (colimit_type F) := { one := begin exact quot.mk _ one end, mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, mul_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.mul_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, left_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.left_distrib, refl, refl, refl, end, right_distrib := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.right_distrib, refl, refl, refl, end, .. colimit_type.add_group_with_one F } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled commutative ring giving the colimit of a diagram. -/ def colimit : CommRing := CommRing.of (colimit_type F) /-- The function from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The ring homomorphism from a given commutative ring in the diagram to the colimit commutative ring. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := by apply quot.sound; apply relation.one, map_mul' := by intros; apply quot.sound; apply relation.mul, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit commutative ring. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free commutative ring on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | one := 1 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit commutative ring to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- one { simp, }, -- neg { simp, }, -- add { simp, }, -- mul { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- mul_comm { rw mul_comm, }, -- add_assoc { rw add_assoc, }, -- mul_assoc { rw mul_assoc, }, -- left_distrib { rw left_distrib, }, -- right_distrib { rw right_distrib, } } end /-- The ring homomorphism from the colimit commutative ring to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp, }, { simp, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_CommRing : has_colimits CommRing := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end CommRing.colimits
908a740d07639537d41a07f31099d6091860bb81
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/ring_exp.lean
96ff42de956bd40bb8f712ed578315121b2352a7
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
56,174
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Tim Baanen. Solve equations in commutative (semi)rings with exponents. -/ import tactic.norm_num import control.traversable.basic /-! # `ring_exp` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`, something that the `ring` tactic cannot do, but `ring_exp` can. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ex` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The normalised version and normalisation proofs are also stored in the `ex` type. The outline of the file: - Define an inductive family of types `ex`, parametrised over `ex_type`, which can represent expressions with `+`, `*`, `^` and rational numerals. The parametrisation over `ex_type` ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ex` type, thus allowing us to map expressions to `ex` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `ex_type`) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - In the tactic, a normalized expression `ps : ex` lives in the meta-world, but the normalization proofs live in the real world. Thus, we cannot directly say `ps.orig = ps.pretty` anywhere, but we have to carefully construct the proof when we compute `ps`. This was a major source of bugs in development! - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. This is accomplished by the `in_exponent` function and is relatively painless since we work in a `reader` monad. - The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`. ## Caveats and future work Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring_exp` solves the goal, but `a / a := 1 by ring_exp` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ -- The base ring `α` will have a universe level `u`. -- We do not introduce `α` as a variable yet, -- in order to make it explicit or implicit as required. universes u namespace tactic.ring_exp open nat /-- The `atom` structure is used to represent atomic expressions: those which `ring_exp` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring_exp_eq` tactic does not normalize the subexpressions in atoms, but `ring_exp` does if `ring_exp_eq` was not sufficient. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ meta structure atom : Type := (value : expr) (index : ℕ) namespace atom /-- The `eq` operation on `atom`s works modulo definitional equality, ignoring their `value`s. The invariants on `atom` ensure indices are unique per value. Thus, `eq` indicates equality as long as the `atom`s come from the same context. -/ meta def eq (a b : atom) : bool := a.index = b.index /-- We order `atom`s on the order of appearance in the main expression. -/ meta def lt (a b : atom) : bool := a.index < b.index meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩ end atom section expression /-! ### `expression` section In this section, we define the `ex` type and its basic operations. First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`. For understanding the code, it's easier to check out `ex` itself first, then refer back to the supporting types. The arithmetic operations on `ex` need additional definitions, so they are defined in a later section. -/ /-- Coefficients in the expression are stored in a wrapper structure, allowing for easier modification of the data structures. The modifications might be caching of the result of `expr.of_rat`, or using a different meta representation of numerals. -/ @[derive decidable_eq, derive inhabited] structure coeff : Type := (value : ℚ) /-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/ @[derive decidable_eq, derive inhabited] inductive ex_type : Type | base : ex_type | sum : ex_type | prod : ex_type | exp : ex_type open ex_type /-- Each `ex` stores information for its normalization proof. The `orig` expression is the expression that was passed to `eval`. The `pretty` expression is the normalised form that the `ex` represents. (I didn't call this something like `norm`, because there are already too many things called `norm` in mathematics!) The field `proof` contains an optional proof term of type `%%orig = %%pretty`. The value `none` for the proof indicates that everything reduces to reflexivity. (Which saves space in quite a lot of cases.) -/ meta structure ex_info : Type := (orig : expr) (pretty : expr) (proof : option expr) /-- The `ex` type is an abstract representation of an expression with `+`, `*` and `^`. Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively. The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented by (something along the lines of) `sum 1 (sum 2 zero)`. The `coeff` constructor is the base case for `ex prod`, and is used for numerals. The code maintains the invariant that the coefficient is never `0`. The `var` constructor is the base case for `ex exp`, and is used for atoms. The `sum_b` constructor allows for addition in the base of an exponentiation; it serves a similar purpose as the parentheses in `(a + b)^c`. The code maintains the invariant that the argument to `sum_b` is not `zero` or `sum _ zero`. All of the constructors contain an `ex_info` field, used to carry around (arguments to) proof terms. While the `ex_type` parameter enforces some simplification invariants, the following ones must be manually maintained at the risk of insufficient power: - the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`) - the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`) - normalisation proofs of subexpressions must be `refl ps.pretty` - if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted according to the `lt` relation defined further down; similarly for `prod` and `coeff` (to ensure `a + b = b + a`). The first two invariants could be encoded in a subtype of `ex`, but aren't (yet) to spare some implementation burden. The other invariants cannot be encoded because we need the `tactic` monad to check them. (For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.) -/ meta inductive ex : ex_type → Type | zero (info : ex_info) : ex sum | sum (info : ex_info) : ex prod → ex sum → ex sum | coeff (info : ex_info) : coeff → ex prod | prod (info : ex_info) : ex exp → ex prod → ex prod | var (info : ex_info) : atom → ex base | sum_b (info : ex_info) : ex sum → ex base | exp (info : ex_info) : ex base → ex prod → ex exp /-- Return the proof information associated to the `ex`. -/ meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info | sum (ex.zero i) := i | sum (ex.sum i _ _) := i | prod (ex.coeff i _) := i | prod (ex.prod i _ _) := i | base (ex.var i _) := i | base (ex.sum_b i _) := i | exp (ex.exp i _ _) := i /-- Return the original, non-normalized version of this `ex`. Note that arguments to another `ex` are always "pre-normalized": their `orig` and `pretty` are equal, and their `proof` is reflexivity. -/ meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig /-- Return the normalized version of this `ex`. -/ meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty /-- Return the normalisation proof of the given expression. If the proof is `refl`, we give `none` instead, which helps to control the size of proof terms. To get an actual term, use `ex.proof_term`, or use `mk_proof` with the correct set of arguments. -/ meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof /-- Update the `orig` and `proof` fields of the `ex_info`. Intended for use in `ex.set_info`. -/ meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info := {orig := o.get_or_else i.pretty, proof := pf, .. i} /-- Update the `ex_info` of the given expression. We use this to combine intermediate normalisation proofs. Since `pretty` only depends on the subexpressions, which do not change, we do not set `pretty`. -/ meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et | sum (ex.zero i) o pf := ex.zero (i.set o pf) | sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps | prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x | prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps | base (ex.var i x) o pf := ex.var (i.set o pf) x | base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps | exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩ /-- Convert an `ex` to a `string`. -/ meta def ex.repr : Π {et : ex_type}, ex et → string | sum (ex.zero _) := "0" | sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps | prod (ex.coeff _ x) := repr x | prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps | base (ex.var _ x) := repr x | base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")" | exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩ /-- Equality test for expressions. Since equivalence of `atom`s is not the same as equality, we cannot make a true `(=)` operator for `ex` either. -/ meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool | sum (ex.zero _) (ex.zero _) := tt | sum (ex.zero _) (ex.sum _ _ _) := ff | sum (ex.sum _ _ _) (ex.zero _) := ff | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs | prod (ex.coeff _ x) (ex.coeff _ y) := x = y | prod (ex.coeff _ _) (ex.prod _ _ _) := ff | prod (ex.prod _ _ _) (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs | base (ex.var _ x) (ex.var _ y) := x.eq y | base (ex.var _ _) (ex.sum_b _ _) := ff | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs /-- The ordering on expressions. As for `ex.eq`, this is a linear order only in one context. -/ meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool | sum _ (ex.zero _) := ff | sum (ex.zero _) _ := tt | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs) | prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1 | prod (ex.coeff _ _) _ := tt | prod _ (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs) | base (ex.var _ x) (ex.var _ y) := x.lt y | base (ex.var _ _) (ex.sum_b _ _) := tt | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs) end expression section operations /-! ### `operations` section This section defines the operations (on `ex`) that use tactics. They live in the `ring_exp_m` monad, which adds a cache and a list of encountered atoms to the `tactic` monad. Throughout this section, we will be constructing proof terms. The lemmas used in the construction are all defined over a commutative semiring α. -/ variables {α : Type u} [comm_semiring α] open tactic open ex_type /-- Stores the information needed in the `eval` function and its dependencies, so they can (re)construct expressions. The `eval_info` structure stores this information for one type, and the `context` combines the two types, one for bases and one for exponents. -/ meta structure eval_info := (α : expr) (univ : level) -- Cache the instances for optimization and consistency (csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr) -- Optional instances (only required for (-) and (/) respectively) (ring_instance : option expr) (dr_instance : option expr) -- Cache common constants. (zero : expr) (one : expr) /-- The `context` contains the full set of information needed for the `eval` function. This structure has two copies of `eval_info`: one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`). When evaluating an exponent, we put `info_e` in `info_b`. -/ meta structure context := (info_b : eval_info) (info_e : eval_info) (transp : transparency) /-- The `ring_exp_m` monad is used instead of `tactic` to store the context. -/ @[derive [monad, alternative]] meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α /-- Access the instance cache. -/ meta def get_context : ring_exp_m context := reader_t.read /-- Lift an operation in the `tactic` monad to the `ring_exp_m` monad. This operation will not access the cache. -/ meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m) /-- Change the context of the given computation, so that expressions are evaluated in the exponent ring, instead of the base ring. -/ meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do ctx ← get_context, reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩ /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class f (ctx.info_b.csr_instance) args /-- Specialized version of `mk_app ``has_add.add`. Should be faster because it can use the cached instances. -/ meta def mk_add (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_add.add ctx.info_b.ha_instance args /-- Specialized version of `mk_app ``has_mul.mul`. Should be faster because it can use the cached instances. -/ meta def mk_mul (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_mul.mul ctx.info_b.hm_instance args /-- Specialized version of `mk_app ``has_pow.pow`. Should be faster because it can use the cached instances. -/ meta def mk_pow (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt ``has_pow.pow [ctx.info_b.univ, ctx.info_e.univ] ctx.info_b.α ctx.info_e.α ctx.info_b.hp_instance).mk_app args /-- Construct a normalization proof term or return the cached one. -/ meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr := match ps.proof with | none := lift $ tactic.mk_eq_refl ps.pretty | (some p) := pure p end /-- Construct a normalization proof term or return the cached one. -/ meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term /-- If all `ex_info` have trivial proofs, return a trivial proof. Otherwise, construct all proof terms. Useful in applications where trivial proofs combine to another trivial proof, most importantly to pass to `mk_proof_or_refl`. -/ meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr)) | [] := pure none | (x :: xs) := do xs_pfs ← none_or_proof_term xs, match (x.proof, xs_pfs) with | (none, none) := pure none | (some x_pf, none) := do xs_pfs ← traverse ex_info.proof_term xs, pure (some (x_pf :: xs_pfs)) | (_, some xs_pfs) := do x_pf ← x.proof_term, pure (some (x_pf :: xs_pfs)) end /-- Use the proof terms as arguments to the given lemma. If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.` -/ meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs' ← traverse ex_info.proof_term hs, mk_app_csr lem (args ++ hs') /-- Use the proof terms as arguments to the given lemma. Often, we construct a proof term using congruence where reflexivity suffices. To solve this, the following function tries to get away with reflexivity. -/ meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs_full ← none_or_proof_term hs, match hs_full with | none := lift $ mk_eq_refl term | (some hs') := mk_app_csr lem (args ++ hs') end /-- A shortcut for adding the original terms of two expressions. -/ meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_add [ps.orig, qs.orig] /-- A shortcut for multiplying the original terms of two expressions. -/ meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_mul [ps.orig, qs.orig] /-- A shortcut for exponentiating the original terms of two expressions. -/ meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_pow [ps.orig, qs.orig] /-- Congruence lemma for constructing `ex.sum`. -/ lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc /-- Congruence lemma for constructing `ex.prod`. -/ lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc /-- Congruence lemma for constructing `ex.exp`. -/ lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc /-- Constructs `ex.zero` with the correct arguments. -/ meta def ex_zero : ring_exp_m (ex sum) := do ctx ← get_context, pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩ /-- Constructs `ex.sum` with the correct arguments. -/ meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do pps_o ← add_orig p ps, pps_p ← mk_add [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``sum_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.coeff` with the correct arguments. There are more efficient constructors for specific numerals: if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`. -/ meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do ctx ← get_context, x_p ← lift $ expr.of_rat ctx.info_b.α x, pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩) /-- Constructs `ex.coeff 1` with the correct arguments. This is a special case for optimization purposes. -/ meta def ex_one : ring_exp_m (ex prod) := do ctx ← get_context, pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩ /-- Constructs `ex.prod` with the correct arguments. -/ meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do pps_o ← mul_orig p ps, pps_p ← mk_mul [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``prod_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.var` with the correct arguments. -/ meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p) /-- Constructs `ex.sum_b` with the correct arguments. -/ meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) := pure (ex.sum_b ps.info (ps.set_info none none)) /-- Constructs `ex.exp` with the correct arguments. -/ meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do ctx ← get_context, pps_o ← pow_orig p ps, pps_p ← mk_pow [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``exp_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp /-- Conversion from `ex base` to `ex exp`. -/ meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do o ← in_exponent $ ex_one, ps ← ex_exp p o, pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp /-- Conversion from `ex exp` to `ex prod`. -/ meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do o ← ex_one, ps ← ex_prod p o, pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp /-- Conversion from `ex prod` to `ex sum`. -/ meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do z ← ex_zero, ps ← ex_sum p z, pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp /-- A more efficient conversion from `atom` to `ex sum`. The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`, except we need to calculate less intermediate steps. -/ meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do p' ← ex_var p, o ← in_exponent $ ex_one, p' ← ex_exp p' o, o ← ex_one, p' ← ex_prod p' o, z ← ex_zero, p' ← ex_sum p' z, pf ← mk_proof ``atom_to_sum_pf [p.1] [], pure $ p'.set_info p.1 pf /-- Compute the sum of two coefficients. Note that the result might not be a valid expression: if `p = -q`, then the result should be `ex.zero : ex sum` instead. The caller must detect when this happens! The returned value is of the form `ex.coeff _ (p + q)`, with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`. -/ meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq_o ← mk_add [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.derive' pq_o, pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩ lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p /-- Compute the product of two coefficients. The returned value is of the form `ex.coeff _ (p * q)`, with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`. -/ meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := match p.1, q.1 with -- Special case to speed up multiplication with 1. | ⟨1, 1, _, _⟩, _ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p], pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩ | _, ⟨1, 1, _, _⟩ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p], pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩ | _, _ := do ctx ← get_context, pq' ← mk_mul [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.derive' pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ end /-- Represents the way in which two products are equal except coefficient. This type is used in the function `add_overlap`. In order to deal with equations of the form `a * 2 + a = 3 * a`, the `add` function will add up overlapping products, turning `a * 2 + a` into `a * 3`. We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this, and the `overlap` type carries the information on how it overlaps. The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`; the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a` (the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`); the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`. We distinguish those two cases because in the second, the whole product reduces to `0`. A potential extension to the tactic would also do this for the base of exponents, e.g. to show `2^n * 2^n = 4^n`. -/ meta inductive overlap : Type | none : overlap | nonzero : ex prod → overlap | zero : ex sum → overlap lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * pq : by rw pq_pf lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * 0 : by rw pq_pf ... = 0 : mul_zero _ /-- Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients). For other arguments, return `overlap.none`. -/ meta def add_overlap : ex prod → ex prod → ring_exp_m overlap | (ex.coeff x_i x) (ex.coeff y_i y) := do xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y | lift $ fail "internal error: add_coeff should return ex.coeff", if xy_c.1 = 0 then do z ← ex_zero, pure $ overlap.zero (z.set_info xy.orig xy.proof) else pure $ overlap.nonzero xy | (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none | (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none | pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q then do pq_ol ← add_overlap ps qs, pqs_o ← add_orig pps qqs, match pq_ol with | overlap.none := pure overlap.none | (overlap.nonzero pq) := do pqs ← ex_prod p pq, pf ← mk_proof ``add_overlap_pf [ps.pretty, qs.pretty, pq.pretty, p.pretty] [pq.info], pure $ overlap.nonzero (pqs.set_info pqs_o pf) | (overlap.zero pq) := do z ← ex_zero, pf ← mk_proof ``add_overlap_pf_zero [ps.pretty, qs.pretty, p.pretty] [pq.info], pure $ overlap.zero (z.set_info pqs_o pf) end else pure overlap.none section addition lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc ps + qs = 0 + qs' : by rw [ps_pf, qs_pf] ... = qs' : zero_add _ lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc ps + qs = ps' + 0 : by rw [ps_pf, qs_pf] ... = ps' : add_zero _ lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} : pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} : pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs := λ pps_pf qqs_pf pq_pf pqs_pf, calc pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf] ... = (p + q) + (ps + qs) : by cc ... = 0 + pqs : by rw [pq_pf, pqs_pf] ... = pqs : zero_add _ lemma add_pf_sum_lt {pps p ps qqs pqs : α} : pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc lemma add_pf_sum_gt {pps qqs q qs pqs : α} : qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc /-- Add two expressions. * `0 + qs = 0` * `ps + 0 = 0` * `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`) * `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`) * `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`) -/ meta def add : ex sum → ex sum → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ qs.set_info pqs_o pf | ps qs@(ex.zero qs_i) := do pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ ps.set_info pqs_o pf | pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do ol ← add_overlap p q, ppqqs_o ← add_orig pps qqs, match ol with | (overlap.nonzero pq) := do pqs ← add ps qs, pqqs ← ex_sum pq pqs, qqs_pf ← qqs.proof_term, pf ← mk_proof ``add_pf_sum_overlap [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf | (overlap.zero pq) := do pqs ← add ps qs, pf ← mk_proof ``add_pf_sum_overlap_zero [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqs.set_info ppqqs_o pf | overlap.none := if p.lt q then do pqs ← add ps qqs, ppqs ← ex_sum p pqs, pf ← mk_proof ``add_pf_sum_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← add pps qs, pqqs ← ex_sum q pqs, pf ← mk_proof ``add_pf_sum_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end end addition section multiplication lemma mul_pf_c_c {ps ps' qs qs' pq : α} : ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc lemma mul_pf_c_prod {ps qqs q qs pqs : α} : qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc lemma mul_pf_prod_c {pps p ps qs pqs : α} : pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} : pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs → p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs := λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} : pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} : qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc /-- Multiply two expressions. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (q * qs) = q * (qs * x)` (for `x` coefficient) * `(p * ps) * y = p * (ps * y)` (for `y` coefficient) * `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)` (if `p_e` and `q_e` are identical except coefficient) * `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`) * `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`) -/ meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do pq ← mul_coeff ps.pretty qs.pretty x y, pq_o ← mul_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c [ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do pqs ← mul_pp ps qs, pqqs ← ex_prod q pqs, pqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_c_prod [ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info pqqs_o pf | pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do pqs ← mul_pp ps qs, ppqs ← ex_prod p pqs, ppqs_o ← mul_orig pps qs, pf ← mk_proof ``mul_pf_prod_c [pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqs_o pf | pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do ppqqs_o ← mul_orig pps qqs, pq_ol ← in_exponent $ add_overlap p_e q_e, match pq_ol, p_b.eq q_b with | (overlap.nonzero pq_e), tt := do psqs ← mul_pp ps qs, pq ← ex_exp p_b pq_e, ppsqqs ← ex_prod pq psqs, pf ← mk_proof ``mul_pp_pf_overlap [pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty] [pps.info, qqs.info, ppsqqs.info], pure $ ppsqqs.set_info ppqqs_o pf | _, _ := if p.lt q then do pqs ← mul_pp ps qqs, ppqs ← ex_prod p pqs, pf ← mk_proof ``mul_pp_pf_prod_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← mul_pp pps qs, pqqs ← ex_prod q pqs, pf ← mk_proof ``mul_pp_pf_prod_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 := λ ps_pf, by rw [ps_pf, zero_mul] lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps → p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc pps * qs = (p + ps) * qs : by rw [pps_pf] ... = p * qs + ps * qs : add_mul _ _ _ ... = ppsqs : ppsqs_pf /-- Multiply two expressions. * `0 * qs = 0` * `(p + ps) * qs = (p * qs) + (ps * qs)` -/ meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info], pure $ z.set_info z_o pf | pps@(ex.sum pps_i p ps) qs := do pqs ← mul_pp p qs >>= prod_to_sum, psqs ← mul_p ps qs, ppsqs ← add pqs psqs, pps_pf ← pps.proof_term, ppsqs_o ← mul_orig pps qs, ppsqs_pf ← ppsqs.proof_term, pf ← mk_proof ``mul_p_pf_sum [pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty] [pps.info, ppsqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 := λ qs_pf, by rw [qs_pf, mul_zero] lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs → ps * qqs = psqqs := λ qs_pf psqqs_pf, calc ps * qqs = ps * (q + qs) : by rw [qs_pf] ... = ps * q + ps * qs : mul_add _ _ _ ... = psqqs : psqqs_pf /-- Multiply two expressions. * `ps * 0 = 0` * `ps * (q + qs) = (ps * q) + (ps * qs)` -/ meta def mul : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info], pure $ z.set_info z_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← mul_p ps q, psqs ← mul ps qs, psqqs ← add psq psqs, psqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_sum [ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end multiplication section exponentiation lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} : pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs := λ pps_pf psqs_pf, calc pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf] ... = p ^ (ps * qs) : symm (pow_mul _ _ _) ... = p ^ psqs : by rw [psqs_pf] /-- Compute the exponentiation of two coefficients. The returned value is of the form `ex.coeff _ (p ^ q)`, with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`. -/ meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq' ← mk_pow [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.derive' pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ /-- Exponentiate two expressions. * `(p ^ ps) ^ qs = p ^ (ps * qs)` -/ meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp) | pps@(ex.exp pps_i p ps) qs := do psqs ← in_exponent $ mul_pp ps qs, ppsqs ← ex_exp p psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_e_pf_exp [pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty] [pps.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 := λ ps_pf, by rw [ps_pf, one_pow] lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 := by simp; cc lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps → p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs := λ pps_pf pqs_pf psqs_pf, calc pps ^ qs = (p * ps) ^ qs : by rw [pps_pf] ... = p ^ qs * ps ^ qs : mul_pow _ _ _ ... = pqs * psqs : by rw [pqs_pf, psqs_pf] /-- Exponentiate two expressions. * `1 ^ qs = 1` * `x ^ qs = x ^ qs` (for `x` coefficient) * `(p * ps) ^ qs = p ^ qs + ps ^ qs` -/ meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info], pure $ o.set_info o_o pf | ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do pq ← pow_coeff ps.pretty qs.pretty x y, pq_o ← pow_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c [ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff ps_i x) qs := do ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b, pqs ← ex_exp ps'' qs, pqs_o ← pow_orig ps qs, pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c [ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pqs.info], pqs' ← exp_to_prod pqs, pure $ pqs'.set_info pqs_o pf | pps@(ex.prod pps_i p ps) qs := do pqs ← pow_e p qs, psqs ← pow_pp ps qs, ppsqs ← ex_prod pqs psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_pp_pf_prod [pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig] [pps.info, pqs.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' := λ ps_pf qs_pf, calc ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf] ... = ps' : pow_one _ lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 := λ ps_pf qs_pf, calc ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf] ... = 0 : zero_pow (succ_pos qs') lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} : qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs := λ qs_pf pqqs_pf, calc ps ^ qs = ps ^ succ qs' : by rw [qs_pf] ... = ps * ps ^ qs' : pow_succ _ _ ... = pqqs : by rw [pqqs_pf] lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} : pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs := λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf] lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc /-- Exponentiate two expressions. * `ps ^ 1 = ps` * `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`) * `(p + 0) ^ qs = p ^ qs` * `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`) * `ps ^ qs = ps ^ qs` (otherwise) -/ meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum) | ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do ps_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pure $ ps.set_info ps_o pf | ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do ctx ← get_context, z ← ex_zero, qs_pred ← lift $ expr.of_nat ctx.info_e.α y, pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info], z_o ← pow_orig ps qs, pure $ z.set_info z_o pf | pps@(ex.sum pps_i p (ex.zero _)) qqs := do pqs ← pow_pp p qqs, pqs_o ← pow_orig pps qqs, pf ← mk_proof ``pow_p_pf_singleton [pps.orig, p.pretty, pqs.pretty, qqs.orig] [pps.info, pqs.info], prod_to_sum $ pqs.set_info pqs_o pf | ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩, pqs ← pow_p ps qs', pqqs ← mul ps pqs, pqqs_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_succ [ps.orig, pqqs.pretty, qs.orig, qs'.pretty] [qs.info, pqqs.info], pure $ pqqs.set_info pqqs_o pf | pps qqs := do -- fallback: treat them as atoms pps' ← ex_sum_b pps, psqs ← ex_exp pps' qqs, psqs_o ← pow_orig pps qqs, pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons [pps.orig, pps.pretty, qqs.orig, qqs.pretty] [pps.info, qqs.info], exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc ps ^ qs = ps ^ 0 : by rw [qs_pf] ... = 1 : pow_zero _ lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs → ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf] ... = ps ^ q * ps ^ qs : pow_add _ _ _ ... = psqqs : psqqs_pf /-- Exponentiate two expressions. * `ps ^ 0 = 1` * `ps ^ (q + qs) = ps ^ q * ps ^ qs` -/ meta def pow : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info], prod_to_sum $ o.set_info o_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← pow_p ps q, psqs ← pow ps qs, psqqs ← mul psq psqs, psqqs_o ← pow_orig ps qqs, pf ← mk_proof ``pow_pf_sum [ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end exponentiation lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp /-- Give a simpler, more human-readable representation of the normalized expression. Normalized expressions might have the form `a^1 * 1 + 0`, since the dummy operations reduce special cases in pattern-matching. Humans prefer to read `a` instead. This tactic gets rid of the dummy additions, multiplications and exponentiations. -/ meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr) | sum pps@(ex.sum pps_i p (ex.zero _)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf] | sum (ex.sum pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_add [p_p, ps_p] <*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf] | prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := prod.mk pps.pretty <$> pps.proof_term | (some ringi) := do (p_p, p_pf) ← p.simple, prod.mk <$> lift (mk_app ``has_neg.neg [p_p]) <*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf] end | prod (ex.prod pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_mul [p_p, ps_p] <*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | base (ex.sum_b pps_i ps) := ps.simple | exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf] | exp (ex.exp pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← in_exponent $ ps.simple, prod.mk <$> mk_pow [p_p, ps_p] <*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | et ps := prod.mk ps.pretty <$> ps.proof_term /-- Performs a lookup of the atom `a` in the list of known atoms, or allocates a new one. If `a` is not definitionally equal to any of the list's entries, a new atom is appended to the list and returned. The index of this atom is kept track of in the second inductive argument. This function is mostly useful in `resolve_atom`, which updates the state with the new list of atoms. -/ meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom) | [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm]) | bas@(b :: as) n := do ctx ← get_context, (lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do (atm, as') ← resolve_atom_aux as (succ n), pure (atm, b :: as') /-- Convert the expression to an atom: either look up a definitionally equal atom, or allocate it as a new atom. You probably want to use `eval_base` if `eval` doesn't work instead of directly calling `resolve_atom`, since `eval_base` can also handle numerals. -/ meta def resolve_atom (a : expr) : ring_exp_m atom := do atoms ← reader_t.lift $ state_t.get, (atm, atoms') ← resolve_atom_aux a atoms 0, reader_t.lift $ state_t.put atoms', pure atm /-- Treat the expression atomically: as a coefficient or atom. Handles cases where `eval` cannot treat the expression as a known operation because it is just a number or single variable. -/ meta def eval_base (ps : expr) : ring_exp_m (ex sum) := match ps.to_rat with | some ⟨0, 1, _, _⟩ := ex_zero | some x := ex_coeff x >>= prod_to_sum | none := do a ← resolve_atom ps, atom_to_sum a end lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp /-- Negate an expression by multiplying with `-1`. Only works if there is a `ring` instance; otherwise it will `fail`. -/ meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := lift $ fail "internal error: negate called in semiring" | (some ring_instance) := do minus_one ← ex_coeff (-1) >>= prod_to_sum, ps' ← mul minus_one ps, ps_pf ← ps'.proof_term, pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf], ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig], pure $ ps'.set_info ps'_o pf end lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} : ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' := by cc /-- Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom. Only works if there is a `division_ring` instance; otherwise it will `fail`. -/ meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only supported in a division ring" | (some dri) := pure dri end, (ps_simple, ps_simple_pf) ← ps.simple, e ← lift $ mk_app ``has_inv.inv [ps_simple], (e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)), e'' ← eval_base e', ps_pf ← ps.proof_term, e''_pf ← e''.proof_term, pf ← mk_app_class ``inverse_pf dri [ ps.orig, ps.pretty, ps_simple, e', e''.pretty, ps_pf, ps_simple_pf, e_pf, e''_pf], e''_o ← lift $ mk_app ``has_inv.inv [ps.orig], pure $ e''.set_info e''_o pf lemma sub_pf {α} [ring α] {ps qs psqs : α} : ps + -qs = psqs → ps - qs = psqs := id lemma div_pf {α} [division_ring α] {ps qs psqs : α} : ps * qs⁻¹ = psqs → ps / qs = psqs := id end operations section wiring /-! ### `wiring` section This section deals with going from `expr` to `ex` and back. The main attraction is `eval`, which uses `add`, `mul`, etc. to calculate an `ex` from a given `expr`. Other functions use `ex`es to produce `expr`s together with a proof, or produce the context to run `ring_exp_m` from an `expr`. -/ open tactic open ex_type /-- Compute a normalized form (of type `ex`) from an expression (of type `expr`). This is the main driver of the `ring_exp` tactic, calling out to `add`, `mul`, `pow`, etc. to parse the `expr`. -/ meta def eval : expr → ring_exp_m (ex sum) | e@`(%%ps + %%qs) := do ps' ← eval ps, qs' ← eval qs, add ps' qs' | e@`(%%ps - %%qs) := (do ctx ← get_context, ri ← match ctx.info_b.ring_instance with | none := lift $ fail "subtraction is not directly supported in a semiring" | (some ri) := pure ri end, ps' ← eval ps, qs' ← eval qs >>= negate, psqs ← add ps' qs', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(- %%ps) := do ps' ← eval ps, negate ps' <|> eval_base e | e@`(%%ps * %%qs) := do ps' ← eval ps, qs' ← eval qs, mul ps' qs' | e@`(has_inv.inv %%ps) := do ps' ← eval ps, inverse ps' <|> eval_base e | e@`(%%ps / %%qs) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only directly supported in a division ring" | (some dri) := pure dri end, ps' ← eval ps, qs' ← eval qs, (do qs'' ← inverse qs', psqs ← mul ps' qs'', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do ps' ← eval ps, qs' ← in_exponent $ eval qs, psqs ← pow ps' qs', psqs_pf ← psqs.proof_term, (do has_pow_pf ← match hp_instance with | `(monoid.has_pow) := lift $ mk_eq_refl e | _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow" end, pf ← lift $ mk_eq_trans has_pow_pf psqs_pf, pure $ psqs.set_info e pf) <|> eval_base e | ps := eval_base ps /-- Run `eval` on the expression and return the result together with normalization proof. See also `eval_simple` if you want something that behaves like `norm_num`. -/ meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do e' ← eval e, prod.mk e' <$> e'.proof_term /-- Run `eval` on the expression and simplify the result. Returns a simplified normalized expression, together with an equality proof. See also `eval_with_proof` if you just want to check the equality of two expressions. -/ meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do (complicated, complicated_pf) ← eval_with_proof e, (simple, simple_pf) ← complicated.simple, prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf) /-- Compute the `eval_info` for a given type `α`. -/ meta def make_eval_info (α : expr) : tactic eval_info := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance, ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none), dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none), ha_instance ← mk_app ``has_add [α] >>= mk_instance, hm_instance ← mk_app ``has_mul [α] >>= mk_instance, hp_instance ← mk_mapp ``monoid.has_pow [some α, none], z ← mk_mapp ``has_zero.zero [α, none], o ← mk_mapp ``has_one.one [α, none], pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩ /-- Use `e` to build the context for running `mx`. -/ meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do info_b ← infer_type e >>= make_eval_info, info_e ← mk_const ``nat >>= make_eval_info, (λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) []) /-- Repeatedly apply `eval_simple` on (sub)expressions. -/ meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do (_, e', pf') ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (e'', pf) ← run_ring_exp transp e $ eval_simple e, guard (¬ e'' =ₐ e), return ((), e'', some pf, ff)) (λ _ _ _ _ _, failed) `eq e, pure (e', pf') end wiring end tactic.ring_exp namespace tactic.interactive open interactive interactive.types lean.parser tactic tactic.ring_exp local postfix `?`:9001 := optional /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. This version of `ring_exp` fails if the target is not an equality. The variant `ring_exp_eq!` will use a more aggressive reducibility setting to determine equality of atoms. -/ meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do `(eq %%ps %%qs) ← target >>= whnf, let transp := if red.is_some then semireducible else reducible, ((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $ prod.mk <$> eval_with_proof ps <*> eval_with_proof qs, if ps'.eq qs' then do qs_pf_inv ← mk_eq_symm qs_pf, pf ← mk_eq_trans ps_pf qs_pf_inv, tactic.interactive.exact ``(%%pf) else fail "ring_exp failed to prove equality" /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. This tactic extends `ring`: it should solve every goal that `ring` can solve. Additionally, it knows how to evaluate expressions with complicated exponents (where `ring` only understands constant exponents). The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine equality of atoms. For example: ```lean example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp example (x y : ℕ) : x + id y = y + id x := by ring_exp! ``` -/ meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring_exp_eq red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp) ns loc.include_goal | fail "ring_exp failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "ring_exp", category := doc_category.tactic, decl_names := [`tactic.interactive.ring_exp], tags := ["arithmetic", "simplification", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive open tactic tactic.interactive (ring_exp_eq) open tactic.ring_exp (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`. -/ meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring_exp_eq red) <|> replace_lhs (normalize transp) <|> fail "ring_exp failed to simplify" end conv.interactive
a1a035336d137b8bbb4f07054fe156ab9ade821f
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/order.lean
99f70d9317ac0dc69c21ffaa1260a601beab7872
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
420
lean
import order.basic namespace preorder variables {α : Type*} {β : Type*} --def comap [preorder β] (f : α → β) : preorder α := --{ le := λ x y, f x ≤ f y, -- le_refl := λ x, le_refl (f x), -- le_trans := λ x y z, le_trans (f x) (f y) (f z)} /-- version of preorder.lift which doesn't use type class inference -/ def lift' : preorder β → (α → β) → preorder α := @preorder.lift _ _ end preorder
44075f4647132f425ed565d527e21bce7adc7b84
4727251e0cd73359b15b664c3170e5d754078599
/src/order/category/DistribLattice.lean
7b7220477b2b933ccc785dc44ee775b33e352952
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,429
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.category.Lattice /-! # The category of distributive lattices This file defines `DistribLattice`, the category of distributive lattices. Note that [`DistLat`](https://ncatlab.org/nlab/show/DistLat) in the literature doesn't always correspond to `DistribLattice` as we don't require bottom or top elements. Instead, this `DistLat` corresponds to `BoundedDistribLattice`. -/ universes u open category_theory /-- The category of distributive lattices. -/ def DistribLattice := bundled distrib_lattice namespace DistribLattice instance : has_coe_to_sort DistribLattice Type* := bundled.has_coe_to_sort instance (X : DistribLattice) : distrib_lattice X := X.str /-- Construct a bundled `DistribLattice` from a `distrib_lattice` underlying type and typeclass. -/ def of (α : Type*) [distrib_lattice α] : DistribLattice := bundled.of α @[simp] lemma coe_of (α : Type*) [distrib_lattice α] : ↥(of α) = α := rfl instance : inhabited DistribLattice := ⟨of punit⟩ instance : bundled_hom.parent_projection @distrib_lattice.to_lattice := ⟨⟩ attribute [derive [large_category, concrete_category]] DistribLattice instance has_forget_to_Lattice : has_forget₂ DistribLattice Lattice := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between distributive lattices from an order isomorphism between them. -/ @[simps] def iso.mk {α β : DistribLattice.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : DistribLattice ⥤ DistribLattice := { obj := λ X, of Xᵒᵈ, map := λ X Y, lattice_hom.dual } /-- The equivalence between `DistribLattice` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : DistribLattice ≌ DistribLattice := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end DistribLattice lemma DistribLattice_dual_comp_forget_to_Lattice : DistribLattice.dual ⋙ forget₂ DistribLattice Lattice = forget₂ DistribLattice Lattice ⋙ Lattice.dual := rfl
4c2555400905bf395a8b71615f32f5713dfbeca9
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/polynomial/chebyshev.lean
5adc60a4038bf694bd8118ca4be6ec121dd12502
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,910
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 lemma T_two : T R 2 = 2 * X ^ 2 - 1 := by simp only [T, sub_left_inj, sq, mul_assoc] @[simp] lemma T_add_two (n : ℕ) : T R (n + 2) = 2 * X * T R (n + 1) - T R n := by rw T 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 variables {R S} 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 variables (R S) /-- `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 lemma U_two : U R 2 = 4 * X ^ 2 - 1 := by { simp only [U], ring, } @[simp] lemma U_add_two (n : ℕ) : U R (n + 2) = 2 * X * U R (n + 1) - U R n := by rw U 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_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, 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 (h₁, 2 * T R (m + k + 2)) (H₁, 2 * X) (H₂, -1) (h₂, -1) (h₃, -1), 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
1deaea8f4643c5dfe369bb4650d7a4e371aa042f
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/order.hlean
a4208e38c33914d571814df673c365460772c809
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,340
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Various types of orders. We develop weak orders "≤" and strict orders "<" separately. We also consider structures with both, where the two are related by x < y ↔ (x ≤ y × x ≠ y) (order_pair) x ≤ y ↔ (x < y ⊎ x = y) (strong_order_pair) These might not hold constructively in some applications, but we can define additional structures with both < and ≤ as needed. Ported from the standard library -/ --import logic.eq logic.connectives open core prod namespace algebra variable {A : Type} /- overloaded symbols -/ structure has_le.{l} [class] (A : Type.{l}) : Type.{l+1} := (le : A → A → Type.{l}) structure has_lt [class] (A : Type) := (lt : A → A → Type₀) infixl <= := has_le.le infixl ≤ := has_le.le infixl < := has_lt.lt definition has_le.ge [reducible] {A : Type} [s : has_le A] (a b : A) := b ≤ a notation a ≥ b := has_le.ge a b notation a >= b := has_le.ge a b definition has_lt.gt [reducible] {A : Type} [s : has_lt A] (a b : A) := b < a notation a > b := has_lt.gt a b /- weak orders -/ structure weak_order [class] (A : Type) extends has_le A := (le_refl : Πa, le a a) (le_trans : Πa b c, le a b → le b c → le a c) (le_antisymm : Πa b, le a b → le b a → a = b) section variable [s : weak_order A] include s definition le.refl (a : A) : a ≤ a := !weak_order.le_refl definition le.trans [trans] {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans definition ge.trans [trans] {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1 definition le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm end structure linear_weak_order [class] (A : Type) extends weak_order A : Type := (le_total : Πa b, le a b ⊎ le b a) definition le.total [s : linear_weak_order A] (a b : A) : a ≤ b ⊎ b ≤ a := !linear_weak_order.le_total /- strict orders -/ structure strict_order [class] (A : Type) extends has_lt A := (lt_irrefl : Πa, ¬ lt a a) (lt_trans : Πa b c, lt a b → lt b c → lt a c) section variable [s : strict_order A] include s definition lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl definition lt.trans [trans] {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans definition gt.trans [trans] {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1 definition ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b := assume eq_ab : a = b, show empty, from lt.irrefl b (eq_ab ▸ lt_ab) definition ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b := ne.symm (ne_of_lt gt_ab) definition lt.asymm {a b : A} (H : a < b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt.trans H H1) end /- well-founded orders -/ -- TODO: do these duplicate what Leo has done? if so, eliminate structure wf_strict_order [class] (A : Type) extends strict_order A := (wf_rec : ΠP : A → Type, (Πx, (Πy, lt y x → P y) → P x) → Πx, P x) definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type} (x : A) (H : Πx, (Πy, wf_strict_order.lt y x → P y) → P x) : P x := wf_strict_order.wf_rec P H x definition wf.ind_on := @wf.rec_on /- structures with a weak and a strict order -/ structure order_pair [class] (A : Type) extends weak_order A, has_lt A := (lt_iff_le_and_ne : Πa b, lt a b ↔ (le a b × a ≠ b)) section variable [s : order_pair A] variables {a b c : A} include s definition lt_iff_le_and_ne : a < b ↔ (a ≤ b × a ≠ b) := !order_pair.lt_iff_le_and_ne definition le_of_lt (H : a < b) : a ≤ b := pr1 (iff.mp lt_iff_le_and_ne H) definition lt_of_le_of_ne (H1 : a ≤ b) (H2 : a ≠ b) : a < b := iff.mp (iff.symm lt_iff_le_and_ne) (pair H1 H2) private definition lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a := assume H : a < a, have H1 : a ≠ a, from pr2 (iff.mp !lt_iff_le_and_ne H), H1 rfl private definition lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c := have le_ab : a ≤ b, from le_of_lt lt_ab, have le_bc : b ≤ c, from le_of_lt lt_bc, have le_ac : a ≤ c, from le.trans le_ab le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm le_ab le_ba, have ne_ab : a ≠ b, from pr2 (iff.mp lt_iff_le_and_ne lt_ab), ne_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac definition order_pair.to_strict_order [instance] [reducible] : strict_order A := ⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄ definition lt_of_lt_of_le [trans] : a < b → b ≤ c → a < c := assume lt_ab : a < b, assume le_bc : b ≤ c, have le_ac : a ≤ c, from le.trans (le_of_lt lt_ab) le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm (le_of_lt lt_ab) le_ba, show empty, from ne_of_lt lt_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac definition lt_of_le_of_lt [trans] : a ≤ b → b < c → a < c := assume le_ab : a ≤ b, assume lt_bc : b < c, have le_ac : a ≤ c, from le.trans le_ab (le_of_lt lt_bc), have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_cb : c ≤ b, from eq_ac ▸ le_ab, have eq_bc : b = c, from le.antisymm (le_of_lt lt_bc) le_cb, show empty, from ne_of_lt lt_bc eq_bc, show a < c, from lt_of_le_of_ne le_ac ne_ac definition gt_of_gt_of_ge [trans] (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1 definition gt_of_ge_of_gt [trans] (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1 definition not_le_of_lt (H : a < b) : ¬ b ≤ a := assume H1 : b ≤ a, lt.irrefl _ (lt_of_lt_of_le H H1) definition not_lt_of_le (H : a ≤ b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt_of_le_of_lt H H1) end structure strong_order_pair [class] (A : Type) extends order_pair A := (le_iff_lt_or_eq : Πa b, le a b ↔ lt a b ⊎ a = b) definition le_iff_lt_or_eq [s : strong_order_pair A] {a b : A} : a ≤ b ↔ a < b ⊎ a = b := !strong_order_pair.le_iff_lt_or_eq definition lt_or_eq_of_le [s : strong_order_pair A] {a b : A} (le_ab : a ≤ b) : a < b ⊎ a = b := iff.mp le_iff_lt_or_eq le_ab -- We can also construct a strong order pair by defining a strict order, and then defining -- x ≤ y ↔ x < y ⊎ x = y structure strict_order_with_le [class] (A : Type) extends strict_order A, has_le A := (le_iff_lt_or_eq : Πa b, le a b ↔ lt a b ⊎ a = b) private definition le_refl (s : strict_order_with_le A) (a : A) : a ≤ a := iff.mp (iff.symm !strict_order_with_le.le_iff_lt_or_eq) (sum.inr rfl) private definition le_trans (s : strict_order_with_le A) (a b c : A) (le_ab : a ≤ b) (le_bc : b ≤ c) : a ≤ c := sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_bc) (assume lt_bc : b < c, iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (sum.inl (lt.trans lt_ab lt_bc))) (assume eq_bc : b = c, eq_bc ▸ le_ab)) (assume eq_ab : a = b, eq_ab⁻¹ ▸ le_bc) private definition le_antisymm (s : strict_order_with_le A) (a b : A) (le_ab : a ≤ b) (le_ba : b ≤ a) : a = b := sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, sum.rec_on (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ba) (assume lt_ba : b < a, absurd (lt.trans lt_ab lt_ba) (lt.irrefl a)) (assume eq_ba : b = a, eq_ba⁻¹)) (assume eq_ab : a = b, eq_ab) private definition lt_iff_le_ne (s : strict_order_with_le A) (a b : A) : a < b ↔ a ≤ b × a ≠ b := iff.intro (assume lt_ab : a < b, have le_ab : a ≤ b, from iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (sum.inl lt_ab), show a ≤ b × a ≠ b, from pair le_ab (ne_of_lt lt_ab)) (assume H : a ≤ b × a ≠ b, have H1 : a < b ⊎ a = b, from iff.mp !strict_order_with_le.le_iff_lt_or_eq (pr1 H), show a < b, from sum_resolve_left H1 (pr2 H)) definition strict_order_with_le.to_order_pair [instance] [reducible] [s : strict_order_with_le A] : strong_order_pair A := ⦃ strong_order_pair, s, le_refl := le_refl s, le_trans := le_trans s, le_antisymm := le_antisymm s, lt_iff_le_and_ne := lt_iff_le_ne s ⦄ /- linear orders -/ structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A, linear_weak_order A section variable [s : linear_strong_order_pair A] variables (a b c : A) include s definition lt.trichotomy : a < b ⊎ a = b ⊎ b < a := sum.rec_on (le.total a b) (assume H : a ≤ b, sum.rec_on (iff.mp !le_iff_lt_or_eq H) (assume H1, sum.inl H1) (assume H1, sum.inr (sum.inl H1))) (assume H : b ≤ a, sum.rec_on (iff.mp !le_iff_lt_or_eq H) (assume H1, sum.inr (sum.inr H1)) (assume H1, sum.inr (sum.inl (H1⁻¹)))) definition lt.by_cases {a b : A} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := sum.rec_on !lt.trichotomy (assume H, H1 H) (assume H, sum.rec_on H (assume H', H2 H') (assume H', H3 H')) definition linear_strong_order_pair.to_linear_order_pair [instance] [reducible] : linear_order_pair A := ⦃ linear_order_pair, s ⦄ definition le_of_not_lt {a b : A} (H : ¬ a < b) : b ≤ a := lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H') definition lt_of_not_le {a b : A} (H : ¬ a ≤ b) : b < a := lt.by_cases (assume H', absurd (le_of_lt H') H) (assume H', absurd (H' ▸ !le.refl) H) (assume H', H') definition lt_or_ge : a < b ⊎ a ≥ b := lt.by_cases (assume H1 : a < b, sum.inl H1) (assume H1 : a = b, sum.inr (H1 ▸ le.refl a)) (assume H1 : a > b, sum.inr (le_of_lt H1)) definition le_or_gt : a ≤ b ⊎ a > b := !sum.swap (lt_or_ge b a) definition lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ⊎ a > b := lt.by_cases (assume H1, sum.inl H1) (assume H1, absurd H1 H) (assume H1, sum.inr H1) end structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A := (decidable_lt : decidable_rel lt) section variable [s : decidable_linear_order A] variables {a b c d : A} include s open decidable definition decidable_lt [instance] : decidable (a < b) := @decidable_linear_order.decidable_lt _ _ _ _ definition decidable_le [instance] : decidable (a ≤ b) := by_cases (assume H : a < b, inl (le_of_lt H)) (assume H : ¬ a < b, have H1 : b ≤ a, from le_of_not_lt H, by_cases (assume H2 : b < a, inr (not_le_of_lt H2)) (assume H2 : ¬ b < a, inl (le_of_not_lt H2))) definition decidable_eq [instance] : decidable (a = b) := by_cases (assume H : a ≤ b, by_cases (assume H1 : b ≤ a, inl (le.antisymm H H1)) (assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a)))) (assume H : ¬ a ≤ b, (inr (assume H1 : a = b, H (H1 ▸ !le.refl)))) -- testing equality first may result in more definitional equalities definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B := if a = b then t_eq else (if a < b then t_lt else t_gt) definition lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) : lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H definition lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) : lt.cases a b t_lt t_eq t_gt = t_lt := if_neg (ne_of_lt H) ⬝ if_pos H definition lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) : lt.cases a b t_lt t_eq t_gt = t_gt := if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H) end end algebra /- For reference, these are all the transitivity rules defined in this file: calc_trans le.trans calc_trans lt.trans calc_trans lt_of_lt_of_le calc_trans lt_of_le_of_lt calc_trans ge.trans calc_trans gt.trans calc_trans gt_of_gt_of_ge calc_trans gt_of_ge_of_gt -/
b1d9b0e3546006ba6aa4612044ee563bba1d2a3c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/affine_isometry.lean
3ff1ec859ab4feeb0933ef965ef1ab32ddb15fab
[ "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
22,056
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed_space.add_torsor import analysis.normed_space.linear_isometry import linear_algebra.affine_space.affine_subspace /-! # Affine isometries In this file we define `affine_isometry 𝕜 P P₂` to be an affine isometric embedding of normed add-torsors `P` into `P₂` over normed `𝕜`-spaces and `affine_isometry_equiv` to be an affine isometric equivalence between `P` and `P₂`. We also prove basic lemmas and provide convenience constructors. The choice of these lemmas and constructors is closely modelled on those for the `linear_isometry` and `affine_map` theories. Since many elementary properties don't require `∥x∥ = 0 → x = 0` we initially set up the theory for `semi_normed_add_torsor` and specialize to `normed_add_torsor` only when needed. ## Notation We introduce the notation `P →ᵃⁱ[𝕜] P₂` for `affine_isometry 𝕜 P P₂`, and `P ≃ᵃⁱ[𝕜] P₂` for `affine_isometry_equiv 𝕜 P P₂`. In contrast with the notation `→ₗᵢ` for linear isometries, `≃ᵢ` for isometric equivalences, etc., the "i" here is a superscript. This is for aesthetic reasons to match the superscript "a" (note that in mathlib `→ᵃ` is an affine map, since `→ₐ` has been taken by algebra-homomorphisms.) -/ open function set variables (𝕜 : Type*) {V V₁ V₂ V₃ V₄ : Type*} {P₁ : Type*} (P P₂ : Type*) {P₃ P₄ : Type*} [normed_field 𝕜] [semi_normed_group V] [normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃] [semi_normed_group V₄] [semi_normed_space 𝕜 V] [normed_space 𝕜 V₁] [semi_normed_space 𝕜 V₂] [semi_normed_space 𝕜 V₃] [semi_normed_space 𝕜 V₄] [pseudo_metric_space P] [metric_space P₁] [pseudo_metric_space P₂] [pseudo_metric_space P₃] [pseudo_metric_space P₄] [semi_normed_add_torsor V P] [normed_add_torsor V₁ P₁] [semi_normed_add_torsor V₂ P₂] [semi_normed_add_torsor V₃ P₃] [semi_normed_add_torsor V₄ P₄] include V V₂ /-- An `𝕜`-affine isometric embedding of one normed add-torsor over a normed `𝕜`-space into another. -/ structure affine_isometry extends P →ᵃ[𝕜] P₂ := (norm_map : ∀ x : V, ∥linear x∥ = ∥x∥) omit V V₂ variables {𝕜 P P₂} -- `→ᵃᵢ` would be more consistent with the linear isometry notation, but it is uglier notation P ` →ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry 𝕜 P P₂ namespace affine_isometry variables (f : P →ᵃⁱ[𝕜] P₂) /-- The underlying linear map of an affine isometry is in fact a linear isometry. -/ protected def linear_isometry : V →ₗᵢ[𝕜] V₂ := { norm_map' := f.norm_map, .. f.linear } @[simp] lemma linear_eq_linear_isometry : f.linear = f.linear_isometry.to_linear_map := by { ext, refl } include V V₂ instance : has_coe_to_fun (P →ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩ omit V V₂ @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl include V V₂ lemma to_affine_map_injective : injective (to_affine_map : (P →ᵃⁱ[𝕜] P₂) → (P →ᵃ[𝕜] P₂)) | ⟨f, _⟩ ⟨g, _⟩ rfl := rfl lemma coe_fn_injective : @injective (P →ᵃⁱ[𝕜] P₂) (P → P₂) coe_fn := affine_map.coe_fn_injective.comp to_affine_map_injective @[ext] lemma ext {f g : P →ᵃⁱ[𝕜] P₂} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h omit V V₂ end affine_isometry namespace linear_isometry variables (f : V →ₗᵢ[𝕜] V₂) /-- Reinterpret a linear isometry as an affine isometry. -/ def to_affine_isometry : V →ᵃⁱ[𝕜] V₂ := { norm_map := f.norm_map, .. f.to_linear_map.to_affine_map } @[simp] lemma coe_to_affine_isometry : ⇑(f.to_affine_isometry : V →ᵃⁱ[𝕜] V₂) = f := rfl @[simp] lemma to_affine_isometry_linear_isometry : f.to_affine_isometry.linear_isometry = f := by { ext, refl } -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_to_affine_map : f.to_affine_isometry.to_affine_map = f.to_linear_map.to_affine_map := rfl end linear_isometry namespace affine_isometry /-- We use `f₁` when we need the domain to be a `normed_space`. -/ variables (f : P →ᵃⁱ[𝕜] P₂) (f₁ : P₁ →ᵃⁱ[𝕜] P₂) @[simp] lemma map_vadd (p : P) (v : V) : f (v +ᵥ p) = f.linear_isometry v +ᵥ f p := f.to_affine_map.map_vadd p v @[simp] lemma map_vsub (p1 p2 : P) : f.linear_isometry (p1 -ᵥ p2) = f p1 -ᵥ f p2 := f.to_affine_map.linear_map_vsub p1 p2 @[simp] lemma dist_map (x y : P) : dist (f x) (f y) = dist x y := by rw [dist_eq_norm_vsub V₂, dist_eq_norm_vsub V, ← map_vsub, f.linear_isometry.norm_map] @[simp] lemma nndist_map (x y : P) : nndist (f x) (f y) = nndist x y := by simp [nndist_dist] @[simp] lemma edist_map (x y : P) : edist (f x) (f y) = edist x y := by simp [edist_dist] protected lemma isometry : isometry f := f.edist_map protected lemma injective : injective f₁ := f₁.isometry.injective @[simp] lemma map_eq_iff {x y : P₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff lemma map_ne {x y : P₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz @[continuity] protected lemma continuous : continuous f := f.isometry.continuous lemma ediam_image (s : set P) : emetric.diam (f '' s) = emetric.diam s := f.isometry.ediam_image s lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set P) := f.isometry.ediam_range lemma diam_image (s : set P) : metric.diam (f '' s) = metric.diam s := f.isometry.diam_image s lemma diam_range : metric.diam (range f) = metric.diam (univ : set P) := f.isometry.diam_range @[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → P} : continuous (f ∘ g) ↔ continuous g := f.isometry.comp_continuous_iff include V /-- The identity affine isometry. -/ def id : P →ᵃⁱ[𝕜] P := ⟨affine_map.id 𝕜 P, λ x, rfl⟩ @[simp] lemma coe_id : ⇑(id : P →ᵃⁱ[𝕜] P) = _root_.id := rfl @[simp] lemma id_apply (x : P) : (affine_isometry.id : P →ᵃⁱ[𝕜] P) x = x := rfl @[simp] lemma id_to_affine_map : (id.to_affine_map : P →ᵃ[𝕜] P) = affine_map.id 𝕜 P := rfl instance : inhabited (P →ᵃⁱ[𝕜] P) := ⟨id⟩ include V₂ V₃ /-- Composition of affine isometries. -/ def comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) : P →ᵃⁱ[𝕜] P₃ := ⟨g.to_affine_map.comp f.to_affine_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩ @[simp] lemma coe_comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) : ⇑(g.comp f) = g ∘ f := rfl omit V V₂ V₃ @[simp] lemma id_comp : (id : P₂ →ᵃⁱ[𝕜] P₂).comp f = f := ext $ λ x, rfl @[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl include V V₂ V₃ V₄ lemma comp_assoc (f : P₃ →ᵃⁱ[𝕜] P₄) (g : P₂ →ᵃⁱ[𝕜] P₃) (h : P →ᵃⁱ[𝕜] P₂) : (f.comp g).comp h = f.comp (g.comp h) := rfl omit V₂ V₃ V₄ instance : monoid (P →ᵃⁱ[𝕜] P) := { one := id, mul := comp, mul_assoc := comp_assoc, one_mul := id_comp, mul_one := comp_id } @[simp] lemma coe_one : ⇑(1 : P →ᵃⁱ[𝕜] P) = _root_.id := rfl @[simp] lemma coe_mul (f g : P →ᵃⁱ[𝕜] P) : ⇑(f * g) = f ∘ g := rfl end affine_isometry -- remark: by analogy with the `linear_isometry` file from which this is adapted, there should -- follow here a section defining an "inclusion" affine isometry from `p : affine_subspace 𝕜 P` -- into `P`; we omit this for now variables (𝕜 P P₂) include V V₂ /-- A affine isometric equivalence between two normed vector spaces. -/ structure affine_isometry_equiv extends P ≃ᵃ[𝕜] P₂ := (norm_map : ∀ x, ∥linear x∥ = ∥x∥) variables {𝕜 P P₂} omit V V₂ -- `≃ᵃᵢ` would be more consistent with the linear isometry equiv notation, but it is uglier notation P ` ≃ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry_equiv 𝕜 P P₂ namespace affine_isometry_equiv variables (e : P ≃ᵃⁱ[𝕜] P₂) /-- The underlying linear equiv of an affine isometry equiv is in fact a linear isometry equiv. -/ protected def linear_isometry_equiv : V ≃ₗᵢ[𝕜] V₂ := { norm_map' := e.norm_map, .. e.linear } @[simp] lemma linear_eq_linear_isometry : e.linear = e.linear_isometry_equiv.to_linear_equiv := by { ext, refl } include V V₂ instance : has_coe_to_fun (P ≃ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩ @[simp] lemma coe_mk (e : P ≃ᵃ[𝕜] P₂) (he : ∀ x, ∥e.linear x∥ = ∥x∥) : ⇑(mk e he) = e := rfl @[simp] lemma coe_to_affine_equiv (e : P ≃ᵃⁱ[𝕜] P₂) : ⇑e.to_affine_equiv = e := rfl lemma to_affine_equiv_injective : injective (to_affine_equiv : (P ≃ᵃⁱ[𝕜] P₂) → (P ≃ᵃ[𝕜] P₂)) | ⟨e, _⟩ ⟨_, _⟩ rfl := rfl @[ext] lemma ext {e e' : P ≃ᵃⁱ[𝕜] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_equiv_injective $ affine_equiv.ext h omit V V₂ /-- Reinterpret a `affine_isometry_equiv` as a `affine_isometry`. -/ def to_affine_isometry : P →ᵃⁱ[𝕜] P₂ := ⟨e.1.to_affine_map, e.2⟩ @[simp] lemma coe_to_affine_isometry : ⇑e.to_affine_isometry = e := rfl /-- Construct an affine isometry equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear isometry equivalence `e' : V₁ ≃ᵢₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃⁱ[𝕜] P₂ := { norm_map := e'.norm_map, .. affine_equiv.mk' e e'.to_linear_equiv p h } @[simp] lemma coe_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_isometry_equiv_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) : (mk' e e' p h).linear_isometry_equiv = e' := by { ext, refl } end affine_isometry_equiv namespace linear_isometry_equiv variables (e : V ≃ₗᵢ[𝕜] V₂) /-- Reinterpret a linear isometry equiv as an affine isometry equiv. -/ def to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂ := { norm_map := e.norm_map, .. e.to_linear_equiv.to_affine_equiv } @[simp] lemma coe_to_affine_isometry_equiv : ⇑(e.to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂) = e := rfl @[simp] lemma to_affine_isometry_equiv_linear_isometry_equiv : e.to_affine_isometry_equiv.linear_isometry_equiv = e := by { ext, refl } -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_equiv_to_affine_equiv : e.to_affine_isometry_equiv.to_affine_equiv = e.to_linear_equiv.to_affine_equiv := rfl -- somewhat arbitrary choice of simp direction @[simp] lemma to_affine_isometry_equiv_to_affine_isometry : e.to_affine_isometry_equiv.to_affine_isometry = e.to_linear_isometry.to_affine_isometry := rfl end linear_isometry_equiv namespace affine_isometry_equiv variables (e : P ≃ᵃⁱ[𝕜] P₂) protected lemma isometry : isometry e := e.to_affine_isometry.isometry /-- Reinterpret a `affine_isometry_equiv` as an `isometric`. -/ def to_isometric : P ≃ᵢ P₂ := ⟨e.to_affine_equiv.to_equiv, e.isometry⟩ @[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl include V V₂ lemma range_eq_univ (e : P ≃ᵃⁱ[𝕜] P₂) : set.range e = set.univ := by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, } omit V V₂ /-- Reinterpret a `affine_isometry_equiv` as an `homeomorph`. -/ def to_homeomorph : P ≃ₜ P₂ := e.to_isometric.to_homeomorph @[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl protected lemma continuous : continuous e := e.isometry.continuous protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on protected lemma continuous_within_at {s x} : continuous_within_at e s x := e.continuous.continuous_within_at variables (𝕜 P) include V /-- Identity map as a `affine_isometry_equiv`. -/ def refl : P ≃ᵃⁱ[𝕜] P := ⟨affine_equiv.refl 𝕜 P, λ x, rfl⟩ variables {𝕜 P} instance : inhabited (P ≃ᵃⁱ[𝕜] P) := ⟨refl 𝕜 P⟩ @[simp] lemma coe_refl : ⇑(refl 𝕜 P) = id := rfl @[simp] lemma to_affine_equiv_refl : (refl 𝕜 P).to_affine_equiv = affine_equiv.refl 𝕜 P := rfl @[simp] lemma to_isometric_refl : (refl 𝕜 P).to_isometric = isometric.refl P := rfl @[simp] lemma to_homeomorph_refl : (refl 𝕜 P).to_homeomorph = homeomorph.refl P := rfl omit V /-- The inverse `affine_isometry_equiv`. -/ def symm : P₂ ≃ᵃⁱ[𝕜] P := { norm_map := e.linear_isometry_equiv.symm.norm_map, .. e.to_affine_equiv.symm } @[simp] lemma apply_symm_apply (x : P₂) : e (e.symm x) = x := e.to_affine_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (x : P) : e.symm (e x) = x := e.to_affine_equiv.symm_apply_apply x @[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl @[simp] lemma to_affine_equiv_symm : e.to_affine_equiv.symm = e.symm.to_affine_equiv := rfl @[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl @[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl include V₃ /-- Composition of `affine_isometry_equiv`s as a `affine_isometry_equiv`. -/ def trans (e' : P₂ ≃ᵃⁱ[𝕜] P₃) : P ≃ᵃⁱ[𝕜] P₃ := ⟨e.to_affine_equiv.trans e'.to_affine_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩ include V V₂ @[simp] lemma coe_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl omit V V₂ V₃ @[simp] lemma trans_refl : e.trans (refl 𝕜 P₂) = e := ext $ λ x, rfl @[simp] lemma refl_trans : (refl 𝕜 P).trans e = e := ext $ λ x, rfl @[simp] lemma trans_symm : e.trans e.symm = refl 𝕜 P := ext e.symm_apply_apply @[simp] lemma symm_trans : e.symm.trans e = refl 𝕜 P₂ := ext e.apply_symm_apply include V V₂ V₃ @[simp] lemma coe_symm_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) : ⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm := rfl include V₄ lemma trans_assoc (ePP₂ : P ≃ᵃⁱ[𝕜] P₂) (eP₂G : P₂ ≃ᵃⁱ[𝕜] P₃) (eGG' : P₃ ≃ᵃⁱ[𝕜] P₄) : ePP₂.trans (eP₂G.trans eGG') = (ePP₂.trans eP₂G).trans eGG' := rfl omit V₂ V₃ V₄ /-- The group of affine isometries of a `normed_add_torsor`, `P`. -/ instance : group (P ≃ᵃⁱ[𝕜] P) := { mul := λ e₁ e₂, e₂.trans e₁, one := refl _ _, inv := symm, one_mul := trans_refl, mul_one := refl_trans, mul_assoc := λ _ _ _, trans_assoc _ _ _, mul_left_inv := trans_symm } @[simp] lemma coe_one : ⇑(1 : P ≃ᵃⁱ[𝕜] P) = id := rfl @[simp] lemma coe_mul (e e' : P ≃ᵃⁱ[𝕜] P) : ⇑(e * e') = e ∘ e' := rfl @[simp] lemma coe_inv (e : P ≃ᵃⁱ[𝕜] P) : ⇑(e⁻¹) = e.symm := rfl omit V @[simp] lemma map_vadd (p : P) (v : V) : e (v +ᵥ p) = e.linear_isometry_equiv v +ᵥ e p := e.to_affine_isometry.map_vadd p v @[simp] lemma map_vsub (p1 p2 : P) : e.linear_isometry_equiv (p1 -ᵥ p2) = e p1 -ᵥ e p2 := e.to_affine_isometry.map_vsub p1 p2 @[simp] lemma dist_map (x y : P) : dist (e x) (e y) = dist x y := e.to_affine_isometry.dist_map x y @[simp] lemma edist_map (x y : P) : edist (e x) (e y) = edist x y := e.to_affine_isometry.edist_map x y protected lemma bijective : bijective e := e.1.bijective protected lemma injective : injective e := e.1.injective protected lemma surjective : surjective e := e.1.surjective @[simp] lemma map_eq_iff {x y : P} : e x = e y ↔ x = y := e.injective.eq_iff lemma map_ne {x y : P} (h : x ≠ y) : e x ≠ e y := e.injective.ne h protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz @[simp] lemma ediam_image (s : set P) : emetric.diam (e '' s) = emetric.diam s := e.isometry.ediam_image s @[simp] lemma diam_image (s : set P) : metric.diam (e '' s) = metric.diam s := e.isometry.diam_image s variables {α : Type*} [topological_space α] @[simp] lemma comp_continuous_on_iff {f : α → P} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.isometry.comp_continuous_on_iff @[simp] lemma comp_continuous_iff {f : α → P} : continuous (e ∘ f) ↔ continuous f := e.isometry.comp_continuous_iff section constructions variables (𝕜) /-- The map `v ↦ v +ᵥ p` as an affine isometric equivalence between `V` and `P`. -/ def vadd_const (p : P) : V ≃ᵃⁱ[𝕜] P := { norm_map := λ x, rfl, .. affine_equiv.vadd_const 𝕜 p } variables {𝕜} include V @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const 𝕜 p) = λ v, v +ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const 𝕜 p).symm = λ p', p' -ᵥ p := rfl @[simp] lemma vadd_const_to_affine_equiv (p : P) : (vadd_const 𝕜 p).to_affine_equiv = affine_equiv.vadd_const 𝕜 p := rfl omit V variables (𝕜) /-- `p' ↦ p -ᵥ p'` as an affine isometric equivalence. -/ def const_vsub (p : P) : P ≃ᵃⁱ[𝕜] V := { norm_map := norm_neg, .. affine_equiv.const_vsub 𝕜 p } variables {𝕜} include V @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub 𝕜 p) = (-ᵥ) p := rfl @[simp] lemma symm_const_vsub (p : P) : (const_vsub 𝕜 p).symm = (linear_isometry_equiv.neg 𝕜).to_affine_isometry_equiv.trans (vadd_const 𝕜 p) := by { ext, refl } omit V variables (𝕜 P) /-- Translation by `v` (that is, the map `p ↦ v +ᵥ p`) as an affine isometric automorphism of `P`. -/ def const_vadd (v : V) : P ≃ᵃⁱ[𝕜] P := { norm_map := λ x, rfl, .. affine_equiv.const_vadd 𝕜 P v } variables {𝕜 P} @[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd 𝕜 P v : P ≃ᵃⁱ[𝕜] P) = (+ᵥ) v := rfl @[simp] lemma const_vadd_zero : const_vadd 𝕜 P (0:V) = refl 𝕜 P := ext $ zero_vadd V include 𝕜 V /-- The map `g` from `V` to `V₂` corresponding to a map `f` from `P` to `P₂`, at a base point `p`, is an isometry if `f` is one. -/ lemma vadd_vsub {f : P → P₂} (hf : isometry f) {p : P} {g : V → V₂} (hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g := begin convert (vadd_const 𝕜 (f p)).symm.isometry.comp (hf.comp (vadd_const 𝕜 p).isometry), exact funext hg end omit 𝕜 variables (𝕜) /-- Point reflection in `x` as an affine isometric automorphism. -/ def point_reflection (x : P) : P ≃ᵃⁱ[𝕜] P := (const_vsub 𝕜 x).trans (vadd_const 𝕜 x) variables {𝕜} lemma point_reflection_apply (x y : P) : (point_reflection 𝕜 x) y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_to_affine_equiv (x : P) : (point_reflection 𝕜 x).to_affine_equiv = affine_equiv.point_reflection 𝕜 x := rfl @[simp] lemma point_reflection_self (x : P) : point_reflection 𝕜 x x = x := affine_equiv.point_reflection_self 𝕜 x lemma point_reflection_involutive (x : P) : function.involutive (point_reflection 𝕜 x) := equiv.point_reflection_involutive x @[simp] lemma point_reflection_symm (x : P) : (point_reflection 𝕜 x).symm = point_reflection 𝕜 x := to_affine_equiv_injective $ affine_equiv.point_reflection_symm 𝕜 x @[simp] lemma dist_point_reflection_fixed (x y : P) : dist (point_reflection 𝕜 x y) x = dist y x := by rw [← (point_reflection 𝕜 x).dist_map y x, point_reflection_self] lemma dist_point_reflection_self' (x y : P) : dist (point_reflection 𝕜 x y) y = ∥bit0 (x -ᵥ y)∥ := by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0] lemma dist_point_reflection_self (x y : P) : dist (point_reflection 𝕜 x y) y = ∥(2:𝕜)∥ * dist x y := by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V] lemma point_reflection_fixed_iff [invertible (2:𝕜)] {x y : P} : point_reflection 𝕜 x y = y ↔ y = x := affine_equiv.point_reflection_fixed_iff_of_module 𝕜 variables [semi_normed_space ℝ V] lemma dist_point_reflection_self_real (x y : P) : dist (point_reflection ℝ x y) y = 2 * dist x y := by { rw [dist_point_reflection_self, real.norm_two] } @[simp] lemma point_reflection_midpoint_left (x y : P) : point_reflection ℝ (midpoint ℝ x y) x = y := affine_equiv.point_reflection_midpoint_left x y @[simp] lemma point_reflection_midpoint_right (x y : P) : point_reflection ℝ (midpoint ℝ x y) y = x := affine_equiv.point_reflection_midpoint_right x y end constructions end affine_isometry_equiv include V V₂ /-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/ lemma affine_map.continuous_linear_iff {f : P →ᵃ[𝕜] P₂} : continuous f.linear ↔ continuous f := begin inhabit P, have : (f.linear : V → V₂) = (affine_isometry_equiv.vadd_const 𝕜 $ f $ default P).to_homeomorph.symm ∘ f ∘ (affine_isometry_equiv.vadd_const 𝕜 $ default P).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'], end /-- If `f` is an affine map, then its linear part is an open map iff `f` is an open map. -/ lemma affine_map.is_open_map_linear_iff {f : P →ᵃ[𝕜] P₂} : is_open_map f.linear ↔ is_open_map f := begin inhabit P, have : (f.linear : V → V₂) = (affine_isometry_equiv.vadd_const 𝕜 $ f $ default P).to_homeomorph.symm ∘ f ∘ (affine_isometry_equiv.vadd_const 𝕜 $ default P).to_homeomorph, { ext v, simp }, rw this, simp only [homeomorph.comp_is_open_map_iff, homeomorph.comp_is_open_map_iff'], end
c252eb81a71e7d9992c4196155f8c100725a9586
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed/group/infinite_sum.lean
e6a9535f972f4177653ae87c2b0145b238a7871a
[ "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
8,506
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Heather Macbeth, Johannes Hölzl, Yury Kudryashov -/ import analysis.normed.group.basic import topology.instances.nnreal /-! # Infinite sums in (semi)normed groups In a complete (semi)normed group, - `summable_iff_vanishing_norm`: a series `∑' i, f i` is summable if and only if for any `ε > 0`, there exists a finite set `s` such that the sum `∑ i in t, f i` over any finite set `t` disjoint with `s` has norm less than `ε`; - `summable_of_norm_bounded`, `summable_of_norm_bounded_eventually`: if `∥f i∥` is bounded above by a summable series `∑' i, g i`, then `∑' i, f i` is summable as well; the same is true if the inequality hold only off some finite set. - `tsum_of_norm_bounded`, `has_sum.norm_le_of_bounded`: if `∥f i∥ ≤ g i`, where `∑' i, g i` is a summable series, then `∥∑' i, f i∥ ≤ ∑' i, g i`. ## Tags infinite series, absolute convergence, normed group -/ open_locale classical big_operators topological_space nnreal open finset filter metric variables {ι α E F : Type*} [semi_normed_group E] [semi_normed_group F] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → E} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff], { simp only [ball_zero_eq, set.mem_set_of_eq] }, { rintros s t hst ⟨s', hs'⟩, exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ } end lemma summable_iff_vanishing_norm [complete_space E] {f : ι → E} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded_eventually {f : ι → E} {g : ι → ℝ} (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : cauchy_seq (λ s, ∑ i in s, f i) := begin refine cauchy_seq_finset_iff_vanishing_norm.2 (λ ε hε, _), rcases summable_iff_vanishing_norm.1 hg ε hε with ⟨s, hs⟩, refine ⟨s ∪ h.to_finset, λ t ht, _⟩, have : ∀ i ∈ t, ∥f i∥ ≤ g i, { intros i hi, simp only [disjoint_left, mem_union, not_or_distrib, h.mem_to_finset, set.mem_compl_iff, not_not] at ht, exact (ht hi).2 }, calc ∥∑ i in t, f i∥ ≤ ∑ i in t, g i : norm_sum_le_of_le _ this ... ≤ ∥∑ i in t, g i∥ : le_abs_self _ ... < ε : hs _ (ht.mono_right le_sup_left), end lemma cauchy_seq_finset_of_norm_bounded {f : ι → E} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_of_norm_bounded_eventually hg $ eventually_of_forall h /-- A version of the **direct comparison test** for conditionally convergent series. See `cauchy_seq_finset_of_norm_bounded` for the same statement about absolutely convergent ones. -/ lemma cauchy_seq_range_of_norm_bounded {f : ℕ → E} (g : ℕ → ℝ) (hg : cauchy_seq (λ n, ∑ i in range n, g i)) (hf : ∀ i, ∥f i∥ ≤ g i) : cauchy_seq (λ n, ∑ i in range n, f i) := begin refine metric.cauchy_seq_iff'.2 (λ ε hε, _), refine (metric.cauchy_seq_iff'.1 hg ε hε).imp (λ N hg n hn, _), specialize hg n hn, rw [dist_eq_norm, ←sum_Ico_eq_sub _ hn] at ⊢ hg, calc ∥∑ k in Ico N n, f k∥ ≤ ∑ k in _, ∥f k∥ : norm_sum_le _ _ ... ≤ ∑ k in _, g k : sum_le_sum (λ x _, hf x) ... ≤ ∥∑ k in _, g k∥ : le_abs_self _ ... < ε : hg end lemma cauchy_seq_finset_of_summable_norm {f : ι → E} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_rfl) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → E} (hf : summable (λa, ∥f a∥)) {s : α → finset ι} {p : filter α} [ne_bot p] (hs : tendsto s p at_top) {a : E} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → E} {a : E} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space E] {f : ι → E} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma has_sum.norm_le_of_bounded {f : ι → E} {g : ι → ℝ} {a : E} {b : ℝ} (hf : has_sum f a) (hg : has_sum g b) (h : ∀ i, ∥f i∥ ≤ g i) : ∥a∥ ≤ b := le_of_tendsto_of_tendsto' hf.norm hg $ λ s, norm_sum_le_of_le _ $ λ i hi, h i /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → E} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀ i, ∥f i∥ ≤ g i) : ∥∑' i : ι, f i∥ ≤ a := begin by_cases hf : summable f, { exact hf.has_sum.norm_le_of_bounded hg h }, { rw [tsum_eq_zero_of_not_summable hf, norm_zero], exact ge_of_tendsto' hg (λ s, sum_nonneg $ λ i hi, (norm_nonneg _).trans (h i)) } end /-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → E} (hf : summable (λi, ∥f i∥)) : ∥∑' i, f i∥ ≤ ∑' i, ∥f i∥ := tsum_of_norm_bounded hf.has_sum $ λ i, le_rfl /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥₊ ≤ g i`, then `∥∑' i, f i∥₊ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_nnnorm_bounded {f : ι → E} {g : ι → ℝ≥0} {a : ℝ≥0} (hg : has_sum g a) (h : ∀ i, ∥f i∥₊ ≤ g i) : ∥∑' i : ι, f i∥₊ ≤ a := begin simp only [← nnreal.coe_le_coe, ← nnreal.has_sum_coe, coe_nnnorm] at *, exact tsum_of_norm_bounded hg h end /-- If `∑' i, ∥f i∥₊` is summable, then `∥∑' i, f i∥₊ ≤ ∑' i, ∥f i∥₊`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma nnnorm_tsum_le {f : ι → E} (hf : summable (λi, ∥f i∥₊)) : ∥∑' i, f i∥₊ ≤ ∑' i, ∥f i∥₊ := tsum_of_nnnorm_bounded hf.has_sum (λ i, le_rfl) variable [complete_space E] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → E} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := summable_iff_cauchy_seq_finset.2 $ cauchy_seq_finset_of_norm_bounded_eventually hg h lemma summable_of_nnnorm_bounded {f : ι → E} (g : ι → ℝ≥0) (hg : summable g) (h : ∀i, ∥f i∥₊ ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → E} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_rfl) lemma summable_of_summable_nnnorm {f : ι → E} (hf : summable (λ a, ∥f a∥₊)) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_rfl)
ac5e129a740d26f23f94a58b2a24d500bfea8c82
47181b4ef986292573c77e09fcb116584d37ea8a
/src/ostrowski/polynomial.lean
86030a9228b43abbc7c73b667d6f3eb33fc330cc
[ "MIT" ]
permissive
RaitoBezarius/berkovich-spaces
87662a2bdb0ac0beed26e3338b221e3f12107b78
0a49f75a599bcb20333ec86b301f84411f04f7cf
refs/heads/main
1,690,520,666,912
1,629,328,012,000
1,629,328,012,000
332,238,095
4
0
MIT
1,629,312,085,000
1,611,414,506,000
Lean
UTF-8
Lean
false
false
8,979
lean
import data.real.basic import data.polynomial.basic import data.polynomial.induction import data.real.cau_seq import abvs_equiv import valuations.basic import valuations.abv_pid import valuations.bounded import for_mathlib.degree open is_absolute_value open_locale classical noncomputable theory def degree_norm {R} [field R] (c: ℝ) (one_lt_c: 1 < c): polynomial R → ℝ := λ p, if p = 0 then 0 else c ^ p.nat_degree instance degree_norm.is_absolute_value {R} [field R] (c: ℝ) (one_lt_c: 1 < c): is_absolute_value (@degree_norm R _ c one_lt_c) := begin have c_pos := (lt_trans zero_lt_one one_lt_c), exact { abv_nonneg := λ p, if h: p = 0 then by simp [degree_norm, h, int.zero_nonneg] else by simp [degree_norm, h, pow_nonneg (le_of_lt c_pos) p.nat_degree], abv_eq_zero := λ p, if h: p = 0 then by simp [degree_norm, h] else by { simp [degree_norm, h], exact (ne.symm $ ne_of_lt $ pow_pos c_pos _), }, abv_add := λ p q, if hp: p = 0 then by { simp [degree_norm, hp], } else if hq: q = 0 then by { simp [degree_norm, hq], } else if hpq: p + q = 0 then by { simp [degree_norm, hpq, hp, hq], exact (λ p₁: (Π (n: ℕ), 0 ≤ c ^ n), add_nonneg (p₁ p.nat_degree) (p₁ q.nat_degree)) (pow_nonneg $ le_of_lt c_pos), } else by { simp [degree_norm, hpq, hp, hq], cases le_max_iff.1 (polynomial.degree_add_le p q) with h₀ h₀; have h := polynomial.nat_degree_le_nat_degree h₀; apply le_trans (pow_le_pow (le_of_lt one_lt_c) h); linarith [pow_nonneg (le_of_lt c_pos) p.nat_degree, pow_nonneg (le_of_lt c_pos) q.nat_degree], }, abv_mul := λ p q, if hp: p = 0 then by { simp [degree_norm, hp], } else if hq: q = 0 then by { simp [degree_norm, hq], } else by { simp [degree_norm, hp, hq], have hpq: p * q ≠ 0, { by_contra hpq, push_neg at hpq, cases eq_zero_or_eq_zero_of_mul_eq_zero hpq, exact hp h, exact hq h, }, have := (@polynomial.degree_mul _ _ _ p q), rw polynomial.degree_eq_nat_degree hp at this, rw polynomial.degree_eq_nat_degree hq at this, rw polynomial.degree_eq_nat_degree hpq at this, norm_cast at this, rw this, rw pow_add, }, }, end def sample_degree_norm {R} [field R]: polynomial R → ℝ := degree_norm 2 one_lt_two instance sample_degree_norm.is_absolute_value {R} [hR: field R]: is_absolute_value (@sample_degree_norm R hR) := degree_norm.is_absolute_value 2 one_lt_two lemma polynomial_abv_nonarchimedian {R} [field R] [normalization_monoid R] (abv: polynomial R → ℝ) [is_absolute_value abv] (trivial_on_base: ∀ x: R, x ≠ 0 → abv (polynomial.C x) = 1): ∀ a b: polynomial R, abv (a + b) ≤ max (abv a) (abv b) := begin have bounded_on_base: ∀ a: R, abv (polynomial.C a) ≤ 1, from λ p, if hp: p = 0 then by simp [hp, abv_zero abv, zero_le_one] else (le_of_eq $ trivial_on_base p hp), rw ← nonarchimedian_iff_integers_bounded, use [1, zero_lt_one], intro n, rw show (n: polynomial R) = (polynomial.C (n: R)), by simp, exact bounded_on_base n, end theorem polynomial_abv_is_degree {R} [field R] [normalization_monoid R] (abv: polynomial R → ℝ) [is_absolute_value abv] (one_lt_abvx: 1 < abv polynomial.X) (trivial_on_base: ∀ x: R, x ≠ 0 → abv (polynomial.C x) = 1): abvs_equiv abv sample_degree_norm := begin have nonarchimedian := polynomial_abv_nonarchimedian abv trivial_on_base, have abv_sum_of_abv_ne: ∀ p q: polynomial R, abv p < abv q → abv (p + q) = abv q, { intros a b hab, apply le_antisymm, calc abv (a + b) ≤ max (abv a) (abv b) : nonarchimedian _ _ ... = abv b : max_eq_right (le_of_lt hab), have h₀: abv b ≤ max (abv a) (abv (a + b)), { calc abv b = abv (-a + (a + b)) : by ring_nf ... ≤ max (abv (-a)) (abv (a + b)) : nonarchimedian _ _ ... = max (abv a) (abv (a + b)) : by rw abv_neg abv }, have h₁: max (abv a) (abv (a + b)) = abv (a + b) := (max_choice (abv a) (abv (a + b))) .resolve_left (ne_of_lt (lt_of_lt_of_le hab h₀)).symm, rwa h₁ at h₀, }, suffices: abvs_equiv abv (degree_norm (abv polynomial.X) one_lt_abvx), { apply abvs_equiv_transitive abv (degree_norm (abv polynomial.X) one_lt_abvx) sample_degree_norm this, set α := real.log 2 / real.log (abv polynomial.X) with α_def, have α_pos: 0 < α, from div_pos (real.log_pos one_lt_two) (real.log_pos one_lt_abvx), use [α, α_pos], unfold sample_degree_norm, unfold degree_norm, ext p, by_cases hp: p = 0, simp [hp, abv_zero abv, real.zero_rpow (ne_of_lt α_pos).symm], suffices: ((abv polynomial.X) ^ (p.nat_degree: ℝ)) ^ α = 2 ^ (p.nat_degree: ℝ), { simp [hp], rw ← real.rpow_nat_cast _ p.nat_degree, rw ← real.rpow_nat_cast _ p.nat_degree, exact this, }, rw ← real.rpow_mul (le_of_lt $ lt_trans zero_lt_one one_lt_abvx), apply log_inj_pos (real.rpow_pos_of_pos (lt_trans zero_lt_one one_lt_abvx) _) (real.rpow_pos_of_pos zero_lt_two _), rw real.log_rpow (lt_trans zero_lt_one one_lt_abvx), rw real.log_rpow zero_lt_two, rw α_def, calc (p.nat_degree: ℝ) * (real.log 2 / real.log (abv polynomial.X)) * real.log (abv polynomial.X) = (p.nat_degree: ℝ) * real.log 2 * (real.log (abv polynomial.X) / real.log (abv polynomial.X)) : by ring ... = (p.nat_degree: ℝ) * real.log 2 : by rw [div_self (real.log_ne_zero_of_ne_one _ (lt_trans zero_lt_one one_lt_abvx) (ne_of_lt one_lt_abvx).symm), mul_one], }, use [1, zero_lt_one], simp [degree_norm], ext p, refine p.rec_on_horner _ _ _, { simp [abv_zero abv], }, { intros q c hq_coeff hc_ne_zero hq_eq_abv, by_cases hq_zero: q = 0, { simp [hq_zero, trivial_on_base c hc_ne_zero, if_neg hc_ne_zero], }, have zero_lt_deg_q: 0 < q.degree, { -- TODO: avoid naturals and just use with_bot ℕ, it's simpler. apply polynomial.nat_degree_pos_iff_degree_pos.1, apply nat.succ_le_of_lt, apply nat.lt_of_le_and_ne, exact polynomial.zero_le_nat_degree hq_zero, by_contra, push_neg at h, rw [polynomial.eq_C_of_nat_degree_eq_zero h.symm, hq_coeff] at hq_zero, simp at hq_zero, exact hq_zero, }, { rw [if_neg hq_zero] at hq_eq_abv, rw [add_comm q _, abv_sum_of_abv_ne, hq_eq_abv, add_comm _ q, polynomial.nat_degree_add_C], have hq_add_const_ne_zero: q + polynomial.C c ≠ 0, { apply mt polynomial.degree_eq_bot.2, rw [polynomial.degree_add_C zero_lt_deg_q], exact (mt polynomial.degree_eq_bot.1) hq_zero, }, rw [if_neg hq_add_const_ne_zero], { intro h_deg_q, rw [polynomial.eq_C_of_nat_degree_eq_zero h_deg_q, hq_coeff], simp [hc_ne_zero], }, { rw [trivial_on_base c hc_ne_zero, hq_eq_abv], refine one_lt_pow one_lt_abvx _, exact (nat.succ_le_of_lt (polynomial.nat_degree_pos_iff_degree_pos.2 zero_lt_deg_q)), }, }, }, { intros q hq_ne_zero habv_q, rw [if_neg hq_ne_zero] at habv_q, rw [if_neg (mul_ne_zero hq_ne_zero polynomial.X_ne_zero), polynomial.nat_degree_mul hq_ne_zero polynomial.X_ne_zero, abv_mul abv, habv_q, ← pow_succ'], simp, }, end theorem polynomial_abv_is_padic {R} [field R] [normalization_monoid R] (abv: polynomial R → ℝ) [is_absolute_value abv] (nontrivial: abv ≠ (λ x, if x = 0 then 0 else 1)) (abvx_le_one: abv polynomial.X ≤ 1) (trivial_on_base: ∀ x: R, x ≠ 0 → abv (polynomial.C x) = 1): ∃ (p: polynomial R) [p_prime: fact (prime p)], abvs_equiv abv (@sample_padic_abv _ _ _ _ p p_prime) := begin apply abv_bounded_padic abv, { have nonarchimedian := polynomial_abv_nonarchimedian abv trivial_on_base, have bounded_on_base: ∀ a: R, abv (polynomial.C a) ≤ 1, from λ p, if hp: p = 0 then by simp [hp, abv_zero abv, zero_le_one] else (le_of_eq $ trivial_on_base p hp), intro p, apply polynomial.induction_on p, from bounded_on_base, from λ p q hp hq, by { calc abv (p + q) ≤ max (abv p) (abv q) : nonarchimedian p q ... ≤ 1 : max_le_iff.2 ⟨ hp, hq ⟩, }, from λ n a h, by { rw pow_succ, rw mul_comm (polynomial.X) _, rw ← mul_assoc, rw abv_mul abv, convert mul_le_mul h abvx_le_one (abv_nonneg abv polynomial.X) zero_le_one, rw mul_one, }, }, { by_contra h, push_neg at h, apply nontrivial, ext, exact if hx: x = 0 then by { simp [hx, abv_zero abv], } else by { simp [hx, h x hx], }, }, end
e5748a05b991fb691cc593a974d2d5c1aad74dcc
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/tauto.lean
228ac65d5f60f92e6034df5c09ab06dcafc6b69b
[ "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
8,337
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import logic.basic tactic.solve_by_elim namespace tactic open expr open tactic.interactive ( casesm constructor_matching ) /-- find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and replace them using de Morgan's law. -/ meta def distrib_not : tactic unit := do hs ← local_context, hs.for_each $ λ h, all_goals $ iterate_at_most 3 $ do h ← get_local h.local_pp_name, e ← infer_type h, match e with | `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h) | `(¬ (_ ∧ _)) := replace h.local_pp_name ``(not_and_distrib'.mp %%h) <|> replace h.local_pp_name ``(not_and_distrib.mp %%h) | `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h) | `(¬ ¬ _) := replace h.local_pp_name ``(of_not_not %%h) | `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(not_imp.mp %%h) | `(¬ (_ ↔ _)) := replace h.local_pp_name ``(not_iff.mp %%h) | `(_ ↔ _) := replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp %%h) <|> replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp (%%h).symm) <|> () <$ tactic.cases h | `(_ → _) := replace h.local_pp_name ``(not_or_of_imp %%h) | _ := failed end meta def tauto_state := ref $ expr_map (option (expr × expr)) meta def modify_ref {α : Type} (r : ref α) (f : α → α) := read_ref r >>= write_ref r ∘ f meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) := do m ← read_ref r, p ← mk_mapp `rfl [none,e], write_ref r $ m.insert e none, return (e,p) meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) := do env ← get_env, let rel := e.get_app_fn.const_name, some symm ← pure $ environment.symm_for env rel | add_refl r e, (do e' ← mk_meta_var `(Prop), iff_t ← to_expr ``(%%e = %%e'), (_,p) ← solve_aux iff_t (applyc `iff.to_eq ; () <$ split ; applyc symm), e' ← instantiate_mvars e', m ← read_ref r, write_ref r $ (m.insert e (e',p)).insert e' none, return (e',p) ) <|> add_refl r e meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit := modify_ref r $ λ m, m.insert x (y,p) meta def root (r : tauto_state) : expr → tactic (expr × expr) | e := do m ← read_ref r, let record_e : tactic (expr × expr) := match e with | v@(expr.mvar _ _ _) := (do (e,p) ← get_assignment v >>= root, add_edge r v e p, return (e,p)) <|> add_refl r e | _ := add_refl r e end, some e' ← pure $ m.find e | record_e, match e' with | (some (e',p')) := do (e'',p'') ← root e', p'' ← mk_app `eq.trans [p',p''], add_edge r e e'' p'', pure (e'',p'') | none := prod.mk e <$> mk_mapp `rfl [none,some e] end meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b := do m ← read_ref r, (a',pa) ← root r a, (b',pb) ← root r b, (unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|> do p ← match (a', b') with | (`(¬ %%a₀), `(¬ %%b₀)) := do p ← symm_eq a₀ b₀, p' ← mk_app `congr_arg [`(not),p], add_edge r a' b' p', return p' | (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) := (do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁), add_edge r a' b' p', return p') <|> do p₀ ← symm_eq a₀ b₁, p₁ ← symm_eq a₁ b₀, p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁) (iff.to_eq iff.comm ) ), add_edge r a' b' p', return p' | (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) := if ¬ a₁.has_var ∧ ¬ b₁.has_var then do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← mk_app `congr_arg [`(implies),p₀,p₁], add_edge r a' b' p', return p' else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a] | (_, _) := (do guard $ a'.get_app_fn.is_constant ∧ a'.get_app_fn.const_name = b'.get_app_fn.const_name, (a'',pa') ← add_symm_proof r a', guard $ a'' =ₐ b', pure pa' ) end, p' ← mk_eq_trans pa p, add_edge r a' b' p', mk_eq_symm pb >>= mk_eq_trans p' meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr) | e [] := failed | e (H :: Hs) := do t ← infer_type H, t' ← infer_type e, (prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf, (do a ← match_not t, (H2,p) ← find_eq_type r a Hs, H2 ← to_expr ``( (%%p).mpr %%H2 ), tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], tactic.exact pr) <|> contra_p_not_p Rs Hs meta def contradiction_with (r : tauto_state) : tactic unit := contradiction <|> do tactic.try intro1, ctx ← local_context, contra_p_not_p r ctx ctx meta def contradiction_symm := using_new_ref (native.rb_map.mk _ _) contradiction_with meta def assumption_with (r : tauto_state) : tactic unit := do { ctx ← local_context, t ← target, (H,p) ← find_eq_type r t ctx, mk_eq_mpr p H >>= tactic.exact } <|> fail "assumption tactic failed" meta def assumption_symm := using_new_ref (native.rb_map.mk _ _) assumption_with meta def tautology (c : bool := ff) : tactic unit := do when c classical, using_new_ref (expr_map.mk _) $ λ r, do try (contradiction_with r); try (assumption_with r); repeat (do gs ← get_goals, repeat (() <$ tactic.intro1); distrib_not; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)]; try (contradiction_with r); try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _)); try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _)); repeat (() <$ tactic.intro1); constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)]; try (assumption_with r), gs' ← get_goals, guard (gs ≠ gs') ) ; repeat (reflexivity <|> solve_by_elim <|> constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)] ) ; done open interactive lean.parser namespace interactive local postfix `?`:9001 := optional /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some /-- Shorter name for the tactic `tautology`. -/ meta def tauto (c : parse $ (tk "!")?) := tautology c end interactive end tactic
c9c3c916c65190cddb925bae362c0383fa86ee9f
abd85493667895c57a7507870867b28124b3998f
/src/topology/metric_space/emetric_space.lean
2fc74cc22641dc9c3ee508e79b75fc0f6c13c330
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
40,959
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ @[nolint ge_or_gt] -- see Note [nolint_ge] class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff] /-- Expressing uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.coe_ext.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h @[nolint ge_or_gt] -- see Note [nolint_ge] theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist @[nolint ge_or_gt] -- see Note [nolint_ge] theorem nhds_eq : 𝓝 x = (⨅ε>0, principal (ball x ε)) := nhds_basis_eball.eq_binfi @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply S_countable.bUnion, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
bc990594cdf35a1b5763a3ece9e26d63e1c14aad
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/meta/derive.lean
a53ff6313b32d0ba99f8dba9e1794b10e9573313
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
4,085
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Attribute that can automatically derive typeclass instances. -/ prelude import init.meta.attribute import init.meta.interactive_base import init.meta.mk_has_reflect_instance import init.meta.mk_has_sizeof_instance import init.meta.mk_inhabited_instance open lean open interactive.types open tactic /-- A handler that may or may not be able to implement the typeclass `cls` for `decl`. It should return `tt` if it was able to derive `cls` and `ff` if it does not know how to derive `cls`, in which case lower-priority handlers will be tried next. -/ meta def derive_handler := Π (cls : pexpr) (decl : name), tactic bool @[user_attribute] meta def derive_handler_attr : user_attribute := { name := `derive_handler, descr := "register a definition of type `derive_handler` for use in the [derive] attribute" } private meta def try_handlers (p : pexpr) (n : name) : list derive_handler → tactic unit | [] := fail format!"failed to find a derive handler for '{p}'" | (h::hs) := do success ← h p n, when (¬success) $ try_handlers hs @[user_attribute] meta def derive_attr : user_attribute unit (list pexpr) := { name := `derive, descr := "automatically derive typeclass instances", parser := pexpr_list_or_texpr, after_set := some (λ n _ _, do ps ← derive_attr.get_param n, handlers ← attribute.get_instances `derive_handler, handlers ← handlers.mmap (λ n, eval_expr derive_handler (expr.const n [])), ps.mmap' (λ p, try_handlers p n handlers)) } /-- Given a tactic `tac` that can solve an application of `cls` in the right context, `instance_derive_handler` uses it to build an instance declaration of `cls n`. -/ meta def instance_derive_handler (cls : name) (tac : tactic unit) (univ_poly := tt) (modify_target : name → list expr → expr → tactic expr := λ _ _, pure) : derive_handler := λ p n, if p.is_constant_of cls then do decl ← get_decl n, cls_decl ← get_decl cls, env ← get_env, guard (env.is_inductive n) <|> fail format!"failed to derive '{cls}', '{n}' is not an inductive type", let ls := decl.univ_params.map $ λ n, if univ_poly then level.param n else level.zero, -- incrementally build up target expression `Π (hp : p) [cls hp] ..., cls (n.{ls} hp ...)` -- where `p ...` are the inductive parameter types of `n` let tgt : expr := expr.const n ls, ⟨params, _⟩ ← mk_local_pis (decl.type.instantiate_univ_params (decl.univ_params.zip ls)), let tgt := tgt.mk_app params, tgt ← mk_app cls [tgt], tgt ← modify_target n params tgt, tgt ← params.enum.mfoldr (λ ⟨i, param⟩ tgt, do -- add typeclass hypothesis for each inductive parameter tgt ← do { guard $ i < env.inductive_num_params n, param_cls ← mk_app cls [param], -- TODO(sullrich): omit some typeclass parameters based on usage of `param`? pure $ expr.pi `a binder_info.inst_implicit param_cls tgt } <|> pure tgt, pure $ tgt.bind_pi param ) tgt, (_, val) ← tactic.solve_aux tgt (intros >> tac), val ← instantiate_mvars val, let trusted := decl.is_trusted ∧ cls_decl.is_trusted, add_decl (declaration.defn (n ++ cls) (if univ_poly then decl.univ_params else []) tgt val reducibility_hints.abbrev trusted), set_basic_attribute `instance (n ++ cls) tt, pure true else pure false @[derive_handler] meta def has_reflect_derive_handler := instance_derive_handler ``has_reflect mk_has_reflect_instance ff (λ n params tgt, -- add additional `reflected` assumption for each parameter params.mfoldr (λ param tgt, do param_cls ← mk_app `reflected [param], pure $ expr.pi `a binder_info.inst_implicit param_cls tgt ) tgt) @[derive_handler] meta def has_sizeof_derive_handler := instance_derive_handler ``has_sizeof mk_has_sizeof_instance attribute [derive has_reflect] bool prod sum option interactive.loc pos
eb496eb56484edbd15bfdb4a3af08b2739e4a5c9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/measure_theory/ae_eq_fun.lean
28a75fade317cd1335c06a0f4ae4aa235e6a332d
[ "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
21,463
lean
/- Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Zhouhang Zhou -/ import measure_theory.integration import order.filter.germ /-! # Almost everywhere equal functions Two measurable functions are treated as identical if they are almost everywhere equal. We form the set of equivalence classes under the relation of being almost everywhere equal, which is sometimes known as the `L⁰` space. See `l1_space.lean` for `L¹` space. ## Notation * `α →ₘ[μ] β` is the type of `L⁰` space, where `α` and `β` are measurable spaces and `μ` is a measure on `α`. `f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used to denote an `L⁰` function. `ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing. ## Main statements * The linear structure of `L⁰` : Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e., `[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring. See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`, `add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun` * The order structure of `L⁰` : `≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain. And `α →ₘ β` inherits the preorder and partial order of `β`. TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a linear order, since otherwise `f ⊔ g` may not be a measurable function. * Emetric on `L⁰` : If `β` is an `emetric_space`, then `L⁰` can be made into an `emetric_space`, where `edist [f] [g]` is defined to be `∫⁻ a, edist (f a) (g a)`. The integral used here is `lintegral : (α → ennreal) → ennreal`, which is defined in the file `integration.lean`. See `edist_mk_mk` and `edist_to_fun`. ## Implementation notes * `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`. For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`, characterizing, say, `(f op g).to_fun`. * `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`, use `ae_eq_fun.mk` * `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ` * `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`. For example, `[f + g]` is `comp₂ (+)` ## Tags function space, almost everywhere equal, `L⁰`, ae_eq_fun -/ noncomputable theory open_locale classical namespace measure_theory open set filter topological_space function variables {α β γ δ : Type*} [measurable_space α] section measurable_space variables [measurable_space β] variable (β) /-- The equivalence relation of being almost everywhere equal -/ def measure.ae_eq_setoid (μ : measure α) : setoid { f : α → β // measurable f } := ⟨λf g, (f : α → β) =ᵐ[μ] g, λ f, ae_eq_refl f, λ f g, ae_eq_symm, λ f g h, ae_eq_trans⟩ variable (α) /-- The space of equivalence classes of measurable functions, where two measurable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def ae_eq_fun (μ : measure α) : Type* := quotient (μ.ae_eq_setoid β) variables {α β} notation α ` →ₘ[`:25 μ `] ` β := ae_eq_fun α β μ end measurable_space namespace ae_eq_fun variables [measurable_space β] [measurable_space γ] [measurable_space δ] {μ : measure α} /-- Construct the equivalence class `[f]` of a measurable function `f`, based on the equivalence relation of being almost everywhere equal. -/ def mk (f : α → β) (hf : measurable f) : α →ₘ[μ] β := quotient.mk' ⟨f, hf⟩ /-- A representative of an `ae_eq_fun` [f] -/ instance : has_coe_to_fun (α →ₘ[μ] β) := ⟨_, λf, ((quotient.out' f : {f : α → β // measurable f}) : α → β)⟩ protected lemma measurable (f : α →ₘ[μ] β) : measurable f := (quotient.out' f).2 @[simp] lemma quot_mk_eq_mk (f : α → β) (hf) : (quot.mk (@setoid.r _ $ μ.ae_eq_setoid β) ⟨f, hf⟩ : α →ₘ[μ] β) = mk f hf := rfl @[simp] lemma quotient_out'_eq_coe_fn (f : α →ₘ[μ] β) : quotient.out' f = ⟨f, f.measurable⟩ := subtype.eq rfl @[simp] lemma mk_eq_mk {f g : α → β} {hf hg} : (mk f hf : α →ₘ[μ] β) = mk g hg ↔ f =ᵐ[μ] g := quotient.eq' @[simp] lemma mk_coe_fn (f : α →ₘ[μ] β) : mk f f.measurable = f := by simpa using quotient.out_eq' f @[ext] lemma ext {f g : α →ₘ[μ] β} (h : f =ᵐ[μ] g) : f = g := by rwa [← f.mk_coe_fn, ← g.mk_coe_fn, mk_eq_mk] lemma coe_fn_mk (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β) =ᵐ[μ] f := @quotient.mk_out' _ (μ.ae_eq_setoid β) (⟨f, hf⟩ : {f // measurable f}) @[elab_as_eliminator] lemma induction_on (f : α →ₘ[μ] β) {p : (α →ₘ[μ] β) → Prop} (H : ∀ f hf, p (mk f hf)) : p f := quotient.induction_on' f $ subtype.forall.2 H @[elab_as_eliminator] lemma induction_on₂ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'} (f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → Prop} (H : ∀ f hf f' hf', p (mk f hf) (mk f' hf')) : p f f' := induction_on f $ λ f hf, induction_on f' $ H f hf @[elab_as_eliminator] lemma induction_on₃ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'} {α'' β'' : Type*} [measurable_space α''] [measurable_space β''] {μ'' : measure α''} (f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') (f'' : α'' →ₘ[μ''] β'') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → (α'' →ₘ[μ''] β'') → Prop} (H : ∀ f hf f' hf' f'' hf'', p (mk f hf) (mk f' hf') (mk f'' hf'')) : p f f' f'' := induction_on f $ λ f hf, induction_on₂ f' f'' $ H f hf /-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`, return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function `[g ∘ f] : α →ₘ γ`. -/ def comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : α →ₘ[μ] γ := quotient.lift_on' f (λ f, mk (g ∘ (f : α → β)) (hg.comp f.2)) $ λ f f' H, mk_eq_mk.2 $ H.fun_comp g @[simp] lemma comp_mk (g : β → γ) (hg : measurable g) (f : α → β) (hf) : comp g hg (mk f hf : α →ₘ[μ] β) = mk (g ∘ f) (hg.comp hf) := rfl lemma comp_eq_mk (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : comp g hg f = mk (g ∘ f) (hg.comp f.measurable) := by rw [← comp_mk g hg f f.measurable, mk_coe_fn] lemma coe_fn_comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : comp g hg f =ᵐ[μ] g ∘ f := by { rw [comp_eq_mk], apply coe_fn_mk } /-- The class of `x ↦ (f x, g x)`. -/ def pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : α →ₘ[μ] β × γ := quotient.lift_on₂' f g (λ f g, mk (λ x, (f.1 x, g.1 x)) (f.2.prod_mk g.2)) $ λ f g f' g' Hf Hg, mk_eq_mk.2 $ Hf.prod_mk Hg @[simp] lemma pair_mk_mk (f : α → β) (hf) (g : α → γ) (hg) : (mk f hf : α →ₘ[μ] β).pair (mk g hg) = mk (λ x, (f x, g x)) (hf.prod_mk hg) := rfl lemma pair_eq_mk (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : f.pair g = mk (λ x, (f x, g x)) (f.measurable.prod_mk g.measurable) := by simp only [← pair_mk_mk, mk_coe_fn] lemma coe_fn_pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : f.pair g =ᵐ[μ] (λ x, (f x, g x)) := by { rw pair_eq_mk, apply coe_fn_mk } /-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions `[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function `λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function `[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/ def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : α →ₘ[μ] δ := comp _ hg (f₁.pair f₂) @[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) : comp₂ g hg (mk f₁ hf₁ : α →ₘ[μ] β) (mk f₂ hf₂) = mk (λa, g (f₁ a) (f₂ a)) (hg.comp (hf₁.prod_mk hf₂)) := rfl lemma comp₂_eq_pair {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ = comp _ hg (f₁.pair f₂) := rfl lemma comp₂_eq_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ = mk (λ a, g (f₁ a) (f₂ a)) (hg.comp (f₁.measurable.prod_mk f₂.measurable)) := by rw [comp₂_eq_pair, pair_eq_mk, comp_mk]; refl lemma coe_fn_comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ =ᵐ[μ] λ a, g (f₁ a) (f₂ a) := by { rw comp₂_eq_mk, apply coe_fn_mk } /-- Interpret `f : α →ₘ[μ] β` as a germ at `μ.ae` forgetting that `f` is measurable. -/ def to_germ (f : α →ₘ[μ] β) : germ μ.ae β := quotient.lift_on' f (λ f, ((f : α → β) : germ μ.ae β)) $ λ f g H, germ.coe_eq.2 H @[simp] lemma mk_to_germ (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β).to_germ = f := rfl lemma to_germ_eq (f : α →ₘ[μ] β) : f.to_germ = (f : α → β) := by rw [← mk_to_germ, mk_coe_fn] lemma to_germ_injective : injective (to_germ : (α →ₘ[μ] β) → germ μ.ae β) := λ f g H, ext $ germ.coe_eq.1 $ by rwa [← to_germ_eq, ← to_germ_eq] lemma comp_to_germ (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : (comp g hg f).to_germ = f.to_germ.map g := induction_on f $ λ f hf, by simp lemma comp₂_to_germ (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : (comp₂ g hg f₁ f₂).to_germ = f₁.to_germ.map₂ g f₂.to_germ := induction_on₂ f₁ f₂ $ λ f₁ hf₁ f₂ hf₂, by simp /-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a` for almost all `a` -/ def lift_pred (p : β → Prop) (f : α →ₘ[μ] β) : Prop := f.to_germ.lift_pred p /-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of `(f a, g a)` for almost all `a` -/ def lift_rel (r : β → γ → Prop) (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : Prop := f.to_germ.lift_rel r g.to_germ lemma lift_rel_mk_mk {r : β → γ → Prop} {f : α → β} {g : α → γ} {hf hg} : lift_rel r (mk f hf : α →ₘ[μ] β) (mk g hg) ↔ ∀ᵐ a ∂μ, r (f a) (g a) := iff.rfl lemma lift_rel_iff_coe_fn {r : β → γ → Prop} {f : α →ₘ[μ] β} {g : α →ₘ[μ] γ} : lift_rel r f g ↔ ∀ᵐ a ∂μ, r (f a) (g a) := by rw [← lift_rel_mk_mk, mk_coe_fn, mk_coe_fn] section order instance [preorder β] : preorder (α →ₘ[μ] β) := preorder.lift to_germ @[simp] lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) : (mk f hf : α →ₘ[μ] β) ≤ mk g hg ↔ f ≤ᵐ[μ] g := iff.rfl @[simp, norm_cast] lemma coe_fn_le [preorder β] {f g : α →ₘ[μ] β} : (f : α → β) ≤ᵐ[μ] g ↔ f ≤ g := lift_rel_iff_coe_fn.symm instance [partial_order β] : partial_order (α →ₘ[μ] β) := partial_order.lift to_germ to_germ_injective /- TODO: Prove `L⁰` space is a lattice if β is linear order. What if β is only a lattice? -/ -- instance [linear_order β] : semilattice_sup (α →ₘ β) := -- { sup := comp₂ (⊔) (_), -- .. ae_eq_fun.partial_order } end order variable (α) /-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of being almost everywhere equal -/ def const (b : β) : α →ₘ[μ] β := mk (λa:α, b) measurable_const lemma coe_fn_const (b : β) : (const α b : α →ₘ[μ] β) =ᵐ[μ] function.const α b := coe_fn_mk _ _ variable {α} instance [inhabited β] : inhabited (α →ₘ[μ] β) := ⟨const α (default β)⟩ @[to_additive] instance [has_one β] : has_one (α →ₘ[μ] β) := ⟨const α 1⟩ @[to_additive] lemma one_def [has_one β] : (1 : α →ₘ[μ] β) = mk (λa:α, 1) measurable_const := rfl @[to_additive] lemma coe_fn_one [has_one β] : ⇑(1 : α →ₘ[μ] β) =ᵐ[μ] 1 := coe_fn_const _ _ @[simp, to_additive] lemma one_to_germ [has_one β] : (1 : α →ₘ[μ] β).to_germ = 1 := rfl section monoid variables [topological_space γ] [second_countable_topology γ] [borel_space γ] [monoid γ] [has_continuous_mul γ] @[to_additive] instance : has_mul (α →ₘ[μ] γ) := ⟨comp₂ (*) measurable_mul⟩ @[simp, to_additive] lemma mk_mul_mk (f g : α → γ) (hf hg) : (mk f hf : α →ₘ[μ] γ) * (mk g hg) = mk (f * g) (hf.mul hg) := rfl @[to_additive] lemma coe_fn_mul (f g : α →ₘ[μ] γ) : ⇑(f * g) =ᵐ[μ] f * g := coe_fn_comp₂ _ _ _ _ @[simp, to_additive] lemma mul_to_germ (f g : α →ₘ[μ] γ) : (f * g).to_germ = f.to_germ * g.to_germ := comp₂_to_germ _ _ _ _ @[to_additive] instance : monoid (α →ₘ[μ] γ) := to_germ_injective.monoid to_germ one_to_germ mul_to_germ end monoid @[to_additive] instance comm_monoid [topological_space γ] [second_countable_topology γ] [borel_space γ] [comm_monoid γ] [has_continuous_mul γ] : comm_monoid (α →ₘ[μ] γ) := to_germ_injective.comm_monoid to_germ one_to_germ mul_to_germ section group variables [topological_space γ] [borel_space γ] [group γ] [topological_group γ] @[to_additive] instance : has_inv (α →ₘ[μ] γ) := ⟨comp has_inv.inv measurable_inv⟩ @[simp, to_additive] lemma inv_mk (f : α → γ) (hf) : (mk f hf : α →ₘ[μ] γ)⁻¹ = mk f⁻¹ hf.inv := rfl @[to_additive] lemma coe_fn_inv (f : α →ₘ[μ] γ) : ⇑(f⁻¹) =ᵐ[μ] f⁻¹ := coe_fn_comp _ _ _ @[to_additive] lemma inv_to_germ (f : α →ₘ[μ] γ) : (f⁻¹).to_germ = f.to_germ⁻¹ := comp_to_germ _ _ _ variables [second_countable_topology γ] @[to_additive] instance : group (α →ₘ[μ] γ) := to_germ_injective.group _ one_to_germ mul_to_germ inv_to_germ end group section add_group variables [topological_space γ] [borel_space γ] [add_group γ] [topological_add_group γ] [second_countable_topology γ] @[simp] lemma mk_sub (f g : α → γ) (hf hg) : mk (f - g) (measurable.sub hf hg) = (mk f hf : α →ₘ[μ] γ) - (mk g hg) := rfl lemma coe_fn_sub (f g : α →ₘ[μ] γ) : ⇑(f - g) =ᵐ[μ] f - g := (coe_fn_add f (-g)).trans $ (coe_fn_neg g).mono $ λ x hx, congr_arg ((+) (f x)) hx end add_group @[to_additive] instance [topological_space γ] [borel_space γ] [comm_group γ] [topological_group γ] [second_countable_topology γ] : comm_group (α →ₘ[μ] γ) := { .. ae_eq_fun.group, .. ae_eq_fun.comm_monoid } section semimodule variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] variables [topological_space γ] [borel_space γ] [add_comm_monoid γ] [semimodule 𝕜 γ] [topological_semimodule 𝕜 γ] instance : has_scalar 𝕜 (α →ₘ[μ] γ) := ⟨λ c f, comp ((•) c) (measurable_id.const_smul c) f⟩ @[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) : c • (mk f hf : α →ₘ[μ] γ) = mk (c • f) (hf.const_smul _) := rfl lemma coe_fn_smul (c : 𝕜) (f : α →ₘ[μ] γ) : ⇑(c • f) =ᵐ[μ] c • f := coe_fn_comp _ _ _ lemma smul_to_germ (c : 𝕜) (f : α →ₘ[μ] γ) : (c • f).to_germ = c • f.to_germ := comp_to_germ _ _ _ variables [second_countable_topology γ] [has_continuous_add γ] instance : semimodule 𝕜 (α →ₘ[μ] γ) := to_germ_injective.semimodule 𝕜 ⟨@to_germ α γ _ _ μ, zero_to_germ, add_to_germ⟩ smul_to_germ end semimodule /- TODO : Prove that `L⁰` is a complete space if the codomain is complete. -/ open ennreal /-- For `f : α → ennreal`, define `∫ [f]` to be `∫ f` -/ def lintegral (f : α →ₘ[μ] ennreal) : ennreal := quotient.lift_on' f (λf, ∫⁻ a, (f : α → ennreal) a ∂μ) (assume f g, lintegral_congr_ae) @[simp] lemma lintegral_mk (f : α → ennreal) (hf) : (mk f hf : α →ₘ[μ] ennreal).lintegral = ∫⁻ a, f a ∂μ := rfl lemma lintegral_coe_fn (f : α →ₘ[μ] ennreal) : ∫⁻ a, f a ∂μ = f.lintegral := by rw [← lintegral_mk, mk_coe_fn] @[simp] lemma lintegral_zero : lintegral (0 : α →ₘ[μ] ennreal) = 0 := lintegral_zero @[simp] lemma lintegral_eq_zero_iff {f : α →ₘ[μ] ennreal} : lintegral f = 0 ↔ f = 0 := induction_on f $ λ f hf, (lintegral_eq_zero_iff hf).trans mk_eq_mk.symm lemma lintegral_add (f g : α →ₘ[μ] ennreal) : lintegral (f + g) = lintegral f + lintegral g := induction_on₂ f g $ λ f hf g hg, by simp [lintegral_add hf hg] lemma lintegral_mono {f g : α →ₘ[μ] ennreal} : f ≤ g → lintegral f ≤ lintegral g := induction_on₂ f g $ λ f hf g hg hfg, lintegral_mono_ae hfg section variables [emetric_space γ] [second_countable_topology γ] [opens_measurable_space γ] /-- `comp_edist [f] [g] a` will return `edist (f a) (g a) -/ protected def edist (f g : α →ₘ[μ] γ) : α →ₘ[μ] ennreal := comp₂ edist measurable_edist f g protected lemma edist_comm (f g : α →ₘ[μ] γ) : f.edist g = g.edist f := induction_on₂ f g $ λ f hf g hg, mk_eq_mk.2 $ eventually_of_forall $ λ x, edist_comm (f x) (g x) lemma coe_fn_edist (f g : α →ₘ[μ] γ) : ⇑(f.edist g) =ᵐ[μ] λ a, edist (f a) (g a) := coe_fn_comp₂ _ _ _ _ protected lemma edist_self (f : α →ₘ[μ] γ) : f.edist f = 0 := induction_on f $ λ f hf, mk_eq_mk.2 $ eventually_of_forall $ λ x, edist_self (f x) /-- Almost everywhere equal functions form an `emetric_space`, with the emetric defined as `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →ₘ[μ] γ) := { edist := λf g, lintegral (f.edist g), edist_self := assume f, lintegral_eq_zero_iff.2 f.edist_self, edist_comm := λ f g, congr_arg lintegral $ f.edist_comm g, edist_triangle := λ f g h, induction_on₃ f g h $ λ f hf g hg h hh, calc ∫⁻ a, edist (f a) (h a) ∂μ ≤ ∫⁻ a, edist (f a) (g a) + edist (g a) (h a) ∂μ : measure_theory.lintegral_mono (λ a, edist_triangle (f a) (g a) (h a)) ... = ∫⁻ a, edist (f a) (g a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ : measure_theory.lintegral_add (hf.edist hg) (hg.edist hh), eq_of_edist_eq_zero := λ f g, induction_on₂ f g $ λ f hf g hg H, mk_eq_mk.2 $ ((measure_theory.lintegral_eq_zero_iff (hf.edist hg)).1 H).mono $ λ x, eq_of_edist_eq_zero } lemma edist_mk_mk {f g : α → γ} (hf hg) : edist (mk f hf : α →ₘ[μ] γ) (mk g hg) = ∫⁻ x, edist (f x) (g x) ∂μ := rfl lemma edist_eq_coe (f g : α →ₘ[μ] γ) : edist f g = ∫⁻ x, edist (f x) (g x) ∂μ := by rw [← edist_mk_mk, mk_coe_fn, mk_coe_fn] lemma edist_zero_eq_coe [has_zero γ] (f : α →ₘ[μ] γ) : edist f 0 = ∫⁻ x, edist (f x) 0 ∂μ := by rw [← edist_mk_mk, mk_coe_fn, zero_def] end section metric variables [metric_space γ] [second_countable_topology γ] [opens_measurable_space γ] lemma edist_mk_mk' {f g : α → γ} (hf hg) : edist (mk f hf : α →ₘ[μ] γ) (mk g hg) = ∫⁻ x, nndist (f x) (g x) ∂μ := by simp only [edist_mk_mk, edist_nndist] lemma edist_eq_coe' (f g : α →ₘ[μ] γ) : edist f g = ∫⁻ x, nndist (f x) (g x) ∂μ := by simp only [edist_eq_coe, edist_nndist] end metric lemma edist_add_right [normed_group γ] [second_countable_topology γ] [borel_space γ] (f g h : α →ₘ[μ] γ) : edist (f + h) (g + h) = edist f g := induction_on₃ f g h $ λ f hf g hg h hh, by simp [edist_mk_mk, edist_dist, dist_add_right] section normed_space variables {𝕜 : Type*} [normed_field 𝕜] variables [normed_group γ] [second_countable_topology γ] [normed_space 𝕜 γ] [borel_space γ] lemma edist_smul (c : 𝕜) (f : α →ₘ[μ] γ) : edist (c • f) 0 = (ennreal.of_real ∥c∥) * edist f 0 := induction_on f $ λ f hf, by simp [edist_mk_mk, zero_def, smul_mk, edist_dist, norm_smul, ennreal.of_real_mul, lintegral_const_mul'] end normed_space section pos_part variables [topological_space γ] [linear_order γ] [order_closed_topology γ] [second_countable_topology γ] [has_zero γ] [opens_measurable_space γ] /-- Positive part of an `ae_eq_fun`. -/ def pos_part (f : α →ₘ[μ] γ) : α →ₘ[μ] γ := comp (λ x, max x 0) (measurable_id.max measurable_const) f @[simp] lemma pos_part_mk (f : α → γ) (hf) : pos_part (mk f hf : α →ₘ[μ] γ) = mk (λ x, max (f x) 0) (hf.max measurable_const) := rfl lemma coe_fn_pos_part (f : α →ₘ[μ] γ) : ⇑(pos_part f) =ᵐ[μ] (λ a, max (f a) 0) := coe_fn_comp _ _ _ end pos_part end ae_eq_fun end measure_theory
48190f64807f426a77fdc9eec53fbb4bf611f664
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/analytic/basic.lean
8468532438eea5769f5b4e9fb9a8463a74d87c48
[ "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
49,449
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import analysis.specific_limits /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (p : formal_multilinear_series 𝕜 E F) (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (p : formal_multilinear_series 𝕜 E F) (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), nnnorm (p n) * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, nat.sub_add_cancel hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc abs (∥p n∥ * r ^ n) = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, replace h₀ : 0 < r := pos_iff_ne_zero.2 h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := (lt_div_iff ha.1).2 (by simpa only [mul_one] using mul_lt_mul_of_pos_left ha.2 h₀), norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, nnnorm (p n) * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < nnnorm x) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_of_lt_radius (p : formal_multilinear_series 𝕜 E F) (h : ↑r < p.radius) : summable (λ n, ∥p n∥ * r^n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) end lemma summable_of_nnnorm_lt_radius (p : formal_multilinear_series 𝕜 E F) [complete_space F] {x : E} (h : ↑(nnnorm x) < p.radius) : summable (λ n, p n (λ i, x)) := begin refine summable_of_norm_bounded (λ n, ∥p n∥ * (nnnorm x)^n) (p.summable_norm_of_lt_radius h) _, intros n, calc ∥(p n) (λ (i : fin n), x)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥x∥) : continuous_multilinear_map.le_op_norm _ _ ... = ∥p n∥ * (nnnorm x)^n : by simp end lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow' _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_sets_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_0_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2] }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_0_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)), rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, begin rw zero_add, replace hy : (nnnorm y : ℝ≥0∞) < p.radius, by { convert hy, exact (edist_eq_coe_nnnorm _).symm }, exact (p.summable_of_nnnorm_lt_radius hy).has_sum end } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := begin have A := h.has_sum hy, have B := (p.has_fpower_series_on_ball h.radius_pos).has_sum (lt_of_lt_of_le hy h.r_le), simpa using A.unique B end /-- The sum of a converging power series is continuous in its disk of convergence. -/ lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r : ℝ≥0} /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Here, we don't use the bracket notation `⟨n, s, hs⟩` in place of the argument `i` in the lambda, as this leads to a bad definition with auxiliary `_match` statements, but we will try to use pattern matching in lambdas as much as possible in the proofs below to increase readability. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, ∑' i : Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}, (p i.1).restr i.2 i.2.2 x /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, first version. -/ -- Note here and below it is necessary to use `@` and provide implicit arguments using `_`, -- so that it is possible to use pattern matching in the lambda. -- Overall this seems a good trade-off in readability. lemma change_origin_summable_aux1 (h : (nnnorm x + r : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ ((λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card) : (Σ (n : ℕ), finset (fin n)) → ℝ) := begin obtain ⟨a, ha, C, hC, hp : ∀ n, ∥p n∥ * (∥x∥ + ↑r) ^ n ≤ C * a ^ n⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, set B : (Σ n, finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have H : ∀ n s, 0 ≤ B ⟨n, s⟩ := λ n s, by apply_rules [mul_nonneg, pow_nonneg, norm_nonneg, r.2], rw summable_sigma_of_nonneg (λ ⟨n, s⟩, H n s), have : ∀ n, has_sum (λ s, B ⟨n, s⟩) (∥p n∥ * (∥x∥ + r) ^ n), { simpa only [← fin.sum_pow_mul_eq_add_pow, finset.mul_sum, ← mul_assoc, add_comm _ ↑r, mul_right_comm] using λ n, has_sum_fintype (λ s, B ⟨n, s⟩) }, refine ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact summable_of_nonneg_of_le (λ n, (this n).nonneg (H n)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, second version. -/ lemma change_origin_summable_aux2 (h : (nnnorm x + r : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ ((λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * ↑r ^ k) : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * r ^ s.card, have SBnorm : summable Bnorm := p.change_origin_summable_aux1 h, let Anorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥(p n).restr s rfl x∥ * r ^ s.card, have SAnorm : summable Anorm, { refine summable_of_norm_bounded _ SBnorm (λ i, _), rcases i with ⟨n, s⟩, suffices H : ∥(p n).restr s rfl x∥ * (r : ℝ) ^ s.card ≤ (∥p n∥ * ∥x∥ ^ (n - finset.card s) * r ^ s.card), { have : ∥(r: ℝ)∥ = r, by rw [real.norm_eq_abs, abs_of_nonneg (nnreal.coe_nonneg _)], simpa [Anorm, Bnorm, this] using H }, exact mul_le_mul_of_nonneg_right ((p n).norm_restr s rfl x) (pow_nonneg (nnreal.coe_nonneg _) _) }, let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, rw ← e.summable_iff, convert SAnorm, ext ⟨n, s⟩, refl end /-- An auxiliary definition for `change_origin_radius`. -/ def change_origin_summable_aux_j (k : ℕ) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := λ ⟨n, s, hs⟩, ⟨k, n, s, hs⟩ lemma change_origin_summable_aux_j_injective (k : ℕ) : function.injective (change_origin_summable_aux_j k) := begin rintros ⟨_, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩⟩ a, simp only [change_origin_summable_aux_j, true_and, eq_self_iff_true, heq_iff_eq, sigma.mk.inj_iff] at a, rcases a with ⟨rfl, a⟩, simpa using a, end /-- Auxiliary lemma controlling the summability of the sequence appearing in the definition of `p.change_origin`, third version. -/ lemma change_origin_summable_aux3 (k : ℕ) (h : (nnnorm x : ℝ≥0∞) < p.radius) : @summable ℝ _ _ _ (λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) := begin obtain ⟨r, rpos, hr⟩ : ∃ (r : ℝ≥0), 0 < r ∧ ((nnnorm x + r) : ℝ≥0∞) < p.radius := ennreal.lt_iff_exists_add_pos_lt.mp h, have S : @summable ℝ _ _ _ ((λ ⟨n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ), { convert (p.change_origin_summable_aux2 hr).comp_injective (change_origin_summable_aux_j_injective k), -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl }, have : (r : ℝ)^k ≠ 0, by simp [pow_ne_zero, nnreal.coe_eq_zero, ne_of_gt rpos], apply (summable_mul_right_iff this).2, convert S, -- again, cleanup that could be done by `tidy`: ext ⟨_, ⟨_, _⟩⟩, refl, end -- FIXME this causes a deterministic timeout with `-T50000` /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - nnnorm x ≤ (p.change_origin x).radius := begin cases le_or_lt p.radius (nnnorm x) with h h, { have : radius p - ↑(nnnorm x) = 0 := ennreal.sub_eq_zero_of_le h, rw this, exact zero_le _ }, refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ := λ ⟨k, n, s, hs⟩, ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, have SA : summable A := p.change_origin_summable_aux2 hr, have A_nonneg : ∀ i, 0 ≤ A i, { rintros ⟨k, n, s, hs⟩, change 0 ≤ ∥(p n).restr s hs x∥ * (r : ℝ) ^ k, refine mul_nonneg (norm_nonneg _) (pow_nonneg (nnreal.coe_nonneg _) _) }, have tsum_nonneg : 0 ≤ tsum A := tsum_nonneg A_nonneg, refine le_radius_of_bound _ (tsum A) (λ k, _), calc ∥change_origin p x k∥ * ↑r ^ k ≤ (∑' i : Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}, ∥(p i.1).restr i.2.1 i.2.2 x∥) * r ^ k : begin apply mul_le_mul_of_nonneg_right _ (pow_nonneg (nnreal.coe_nonneg _) _), apply norm_tsum_le_tsum_norm, convert p.change_origin_summable_aux3 k h, ext ⟨_, _, _⟩, refl end ... = tsum (λ i, ∥(p i.1).restr i.2.1 i.2.2 x∥ * ↑r ^ k : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → ℝ) : begin rw tsum_mul_right, end ... = tsum (A ∘ change_origin_summable_aux_j k) : begin congr, ext ⟨_, _, _⟩, refl end ... ≤ tsum A : tsum_comp_le_tsum_of_inj SA A_nonneg (change_origin_summable_aux_j_injective k) end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variable [complete_space F] /-- The `k`-th coefficient of `p.change_origin` is the sum of a summable series. -/ lemma change_origin_has_sum (k : ℕ) (h : (nnnorm x : ℝ≥0∞) < p.radius) : @has_sum (E [×k]→L[𝕜] F) _ _ _ ((λ i, (p i.1).restr i.2.1 i.2.2 x) : (Σ (n : ℕ), {s : finset (fin n) // finset.card s = k}) → (E [×k]→L[𝕜] F)) (p.change_origin x k) := begin apply summable.has_sum, apply summable_of_summable_norm, convert p.change_origin_summable_aux3 k h, ext ⟨_, _, _⟩, refl end /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (nnnorm x + nnnorm y : ℝ≥0∞) < p.radius) : has_sum ((λk:ℕ, p.change_origin x k (λ (i : fin k), y))) (p.sum (x + y)) := begin /- The series on the left is a series of series. If we order the terms differently, we get back to `p.sum (x + y)`, in which the `n`-th term is expanded by multilinearity. In the proof below, the term on the left is the sum of a series of terms `A`, the sum on the right is the sum of a series of terms `B`, and we show that they correspond to each other by reordering to conclude the proof. -/ have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, -- `A` is the terms of the series whose sum gives the series for `p.change_origin` let A : (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // s.card = k}) → F := λ ⟨k, n, s, hs⟩, (p n).restr s hs x (λ(i : fin k), y), -- `B` is the terms of the series whose sum gives `p (x + y)`, after expansion by multilinearity. let B : (Σ (n : ℕ), finset (fin n)) → F := λ ⟨n, s⟩, (p n).restr s rfl x (λ (i : fin s.card), y), let Bnorm : (Σ (n : ℕ), finset (fin n)) → ℝ := λ ⟨n, s⟩, ∥p n∥ * ∥x∥ ^ (n - s.card) * ∥y∥ ^ s.card, have SBnorm : summable Bnorm, by convert p.change_origin_summable_aux1 h, have SB : summable B, { refine summable_of_norm_bounded _ SBnorm _, rintros ⟨n, s⟩, calc ∥(p n).restr s rfl x (λ (i : fin s.card), y)∥ ≤ ∥(p n).restr s rfl x∥ * ∥y∥ ^ s.card : begin convert ((p n).restr s rfl x).le_op_norm (λ (i : fin s.card), y), simp [(finset.prod_const (∥y∥))], end ... ≤ (∥p n∥ * ∥x∥ ^ (n - s.card)) * ∥y∥ ^ s.card : mul_le_mul_of_nonneg_right ((p n).norm_restr _ _ _) (pow_nonneg (norm_nonneg _) _) }, -- Check that indeed the sum of `B` is `p (x + y)`. have has_sum_B : has_sum B (p.sum (x + y)), { have K1 : ∀ n, has_sum (λ (s : finset (fin n)), B ⟨n, s⟩) (p n (λ (i : fin n), x + y)), { assume n, have : (p n) (λ (i : fin n), y + x) = ∑ s : finset (fin n), p n (finset.piecewise s (λ (i : fin n), y) (λ (i : fin n), x)) := (p n).map_add_univ (λ i, y) (λ i, x), simp [add_comm y x] at this, rw this, exact has_sum_fintype _ }, have K2 : has_sum (λ (n : ℕ), (p n) (λ (i : fin n), x + y)) (p.sum (x + y)), { have : x + y ∈ emetric.ball (0 : E) p.radius, { apply lt_of_le_of_lt _ h, rw [edist_eq_coe_nnnorm, ← ennreal.coe_add, ennreal.coe_le_coe], exact norm_add_le x y }, simpa using (p.has_fpower_series_on_ball radius_pos).has_sum this }, exact has_sum.sigma_of_has_sum K2 K1 SB }, -- Deduce that the sum of `A` is also `p (x + y)`, as the terms `A` and `B` are the same up to -- reordering have has_sum_A : has_sum A (p.sum (x + y)), { let e : (Σ (n : ℕ), finset (fin n)) ≃ (Σ (k : ℕ) (n : ℕ), {s : finset (fin n) // finset.card s = k}) := { to_fun := λ ⟨n, s⟩, ⟨s.card, n, s, rfl⟩, inv_fun := λ ⟨k, n, s, hs⟩, ⟨n, s⟩, left_inv := λ ⟨n, s⟩, rfl, right_inv := λ ⟨k, n, s, hs⟩, by { induction hs, refl } }, have : A ∘ e = B, by { ext ⟨⟩, refl }, rw ← e.has_sum_iff, convert has_sum_B }, -- Summing `A ⟨k, c⟩` with fixed `k` and varying `c` is exactly the `k`-th term in the series -- defining `p.change_origin`, by definition have J : ∀k, has_sum (λ c, A ⟨k, c⟩) (p.change_origin x k (λ(i : fin k), y)), { assume k, have : (nnnorm x : ℝ≥0∞) < radius p := lt_of_le_of_lt (le_self_add) h, convert continuous_multilinear_map.has_sum_eval (p.change_origin_has_sum k this) (λ(i : fin k), y), ext ⟨_, _, _⟩, refl }, exact has_sum_A.sigma J end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (nnnorm y : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - nnnorm y) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := begin assume z hz, have A : (nnnorm y : ℝ≥0∞) + nnnorm z < r, { have : edist z 0 < r - ↑(nnnorm y) := hz, rwa [edist_eq_coe_nnnorm, ennreal.lt_sub_iff_add_lt, add_comm] at this }, convert p.change_origin_eval (lt_of_lt_of_le A hf.r_le), have : y + z ∈ emetric.ball (0 : E) r := calc edist (y + z) 0 ≤ ↑(nnnorm y) + ↑(nnnorm z) : by { rw edist_eq_coe_nnnorm, exact_mod_cast nnnorm_add_le y z } ... < r : A, simpa only [add_assoc] using hf.sum this end } lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (nnnorm (y - x) : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_forall_mem_open, rintro x ⟨p, r, hr⟩, refine ⟨emetric.ball x r, λ y hy, hr.analytic_at_of_mem hy, emetric.is_open_ball, _⟩, simp only [edist_self, emetric.mem_ball, hr.r_pos] end variables {𝕜 f} end
5897aa10b6fae4b55c562d2459a586b092591c0c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/units.lean
3f317f7075ec4737616d6b546f6fdc7b841d7144
[]
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
14,879
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.basic import Mathlib.logic.nontrivial import Mathlib.PostPort universes u l u_1 namespace Mathlib /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] where val : α inv : α val_inv : val * inv = 1 inv_val : inv * val = 1 /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] where val : α neg : α val_neg : val + neg = 0 neg_val : neg + val = 0 namespace units protected instance Mathlib.add_units.has_coe {α : Type u} [add_monoid α] : has_coe (add_units α) α := has_coe.mk add_units.val @[simp] theorem Mathlib.add_units.coe_mk {α : Type u} [add_monoid α] (a : α) (b : α) (h₁ : a + b = 0) (h₂ : b + a = 0) : ↑(add_units.mk a b h₁ h₂) = a := rfl theorem ext {α : Type u} [monoid α] : function.injective coe := sorry theorem Mathlib.add_units.eq_iff {α : Type u} [add_monoid α] {a : add_units α} {b : add_units α} : ↑a = ↑b ↔ a = b := function.injective.eq_iff add_units.ext theorem Mathlib.add_units.ext_iff {α : Type u} [add_monoid α] {a : add_units α} {b : add_units α} : a = b ↔ ↑a = ↑b := iff.symm add_units.eq_iff protected instance Mathlib.add_units.decidable_eq {α : Type u} [add_monoid α] [DecidableEq α] : DecidableEq (add_units α) := fun (a b : add_units α) => decidable_of_iff' (↑a = ↑b) add_units.ext_iff @[simp] theorem mk_coe {α : Type u} [monoid α] (u : units α) (y : α) (h₁ : ↑u * y = 1) (h₂ : y * ↑u = 1) : mk (↑u) y h₁ h₂ = u := ext rfl /-- Units of a monoid form a group. -/ protected instance group {α : Type u} [monoid α] : group (units α) := group.mk (fun (u₁ u₂ : units α) => mk (val u₁ * val u₂) (inv u₂ * inv u₁) sorry sorry) sorry (mk 1 1 sorry sorry) sorry sorry (fun (u : units α) => mk (inv u) (val u) (inv_val u) (val_inv u)) (div_inv_monoid.div._default (fun (u₁ u₂ : units α) => mk (val u₁ * val u₂) (inv u₂ * inv u₁) sorry sorry) sorry (mk 1 1 sorry sorry) sorry sorry fun (u : units α) => mk (inv u) (val u) (inv_val u) (val_inv u)) sorry @[simp] theorem Mathlib.add_units.coe_add {α : Type u} [add_monoid α] (a : add_units α) (b : add_units α) : ↑(a + b) = ↑a + ↑b := rfl @[simp] theorem coe_one {α : Type u} [monoid α] : ↑1 = 1 := rfl @[simp] theorem Mathlib.add_units.coe_eq_zero {α : Type u} [add_monoid α] {a : add_units α} : ↑a = 0 ↔ a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑a = 0 ↔ a = 0)) (Eq.symm add_units.coe_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑a = ↑0 ↔ a = 0)) (propext add_units.eq_iff))) (iff.refl (a = 0))) @[simp] theorem inv_mk {α : Type u} [monoid α] (x : α) (y : α) (h₁ : x * y = 1) (h₂ : y * x = 1) : mk x y h₁ h₂⁻¹ = mk y x h₂ h₁ := rfl theorem val_coe {α : Type u} [monoid α] (a : units α) : ↑a = val a := rfl theorem coe_inv {α : Type u} [monoid α] (a : units α) : ↑(a⁻¹) = inv a := rfl @[simp] theorem inv_mul {α : Type u} [monoid α] (a : units α) : ↑(a⁻¹) * ↑a = 1 := inv_val a @[simp] theorem Mathlib.add_units.add_neg {α : Type u} [add_monoid α] (a : add_units α) : ↑a + ↑(-a) = 0 := add_units.val_neg a theorem inv_mul_of_eq {α : Type u} [monoid α] {u : units α} {a : α} (h : ↑u = a) : ↑(u⁻¹) * a = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (↑(u⁻¹) * a = 1)) (Eq.symm h))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(u⁻¹) * ↑u = 1)) (inv_mul u))) (Eq.refl 1)) theorem Mathlib.add_units.add_neg_of_eq {α : Type u} [add_monoid α] {u : add_units α} {a : α} (h : ↑u = a) : a + ↑(-u) = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a + ↑(-u) = 0)) (Eq.symm h))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑u + ↑(-u) = 0)) (add_units.add_neg u))) (Eq.refl 0)) @[simp] theorem mul_inv_cancel_left {α : Type u} [monoid α] (a : units α) (b : α) : ↑a * (↑(a⁻¹) * b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (↑a * (↑(a⁻¹) * b) = b)) (Eq.symm (mul_assoc (↑a) (↑(a⁻¹)) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑a * ↑(a⁻¹) * b = b)) (mul_inv a))) (eq.mpr (id (Eq._oldrec (Eq.refl (1 * b = b)) (one_mul b))) (Eq.refl b))) @[simp] theorem Mathlib.add_units.neg_add_cancel_left {α : Type u} [add_monoid α] (a : add_units α) (b : α) : ↑(-a) + (↑a + b) = b := eq.mpr (id (Eq._oldrec (Eq.refl (↑(-a) + (↑a + b) = b)) (Eq.symm (add_assoc (↑(-a)) (↑a) b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(-a) + ↑a + b = b)) (add_units.neg_add a))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 + b = b)) (zero_add b))) (Eq.refl b))) @[simp] theorem mul_inv_cancel_right {α : Type u} [monoid α] (a : α) (b : units α) : a * ↑b * ↑(b⁻¹) = a := eq.mpr (id (Eq._oldrec (Eq.refl (a * ↑b * ↑(b⁻¹) = a)) (mul_assoc a ↑b ↑(b⁻¹)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (↑b * ↑(b⁻¹)) = a)) (mul_inv b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = a)) (mul_one a))) (Eq.refl a))) @[simp] theorem Mathlib.add_units.neg_add_cancel_right {α : Type u} [add_monoid α] (a : α) (b : add_units α) : a + ↑(-b) + ↑b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a + ↑(-b) + ↑b = a)) (add_assoc a ↑(-b) ↑b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + (↑(-b) + ↑b) = a)) (add_units.neg_add b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = a)) (add_zero a))) (Eq.refl a))) protected instance Mathlib.add_units.inhabited {α : Type u} [add_monoid α] : Inhabited (add_units α) := { default := 0 } protected instance comm_group {α : Type u_1} [comm_monoid α] : comm_group (units α) := comm_group.mk group.mul sorry group.one sorry sorry group.inv group.div sorry sorry protected instance Mathlib.add_units.has_repr {α : Type u} [add_monoid α] [has_repr α] : has_repr (add_units α) := has_repr.mk (repr ∘ add_units.val) @[simp] theorem Mathlib.add_units.add_right_inj {α : Type u} [add_monoid α] (a : add_units α) {b : α} {c : α} : ↑a + b = ↑a + c ↔ b = c := sorry @[simp] theorem Mathlib.add_units.add_left_inj {α : Type u} [add_monoid α] (a : add_units α) {b : α} {c : α} : b + ↑a = c + ↑a ↔ b = c := sorry theorem Mathlib.add_units.eq_add_neg_iff_add_eq {α : Type u} [add_monoid α] {c : add_units α} {a : α} {b : α} : a = b + ↑(-c) ↔ a + ↑c = b := sorry theorem eq_inv_mul_iff_mul_eq {α : Type u} [monoid α] (b : units α) {a : α} {c : α} : a = ↑(b⁻¹) * c ↔ ↑b * a = c := sorry theorem inv_mul_eq_iff_eq_mul {α : Type u} [monoid α] (a : units α) {b : α} {c : α} : ↑(a⁻¹) * b = c ↔ b = ↑a * c := sorry theorem mul_inv_eq_iff_eq_mul {α : Type u} [monoid α] (b : units α) {a : α} {c : α} : a * ↑(b⁻¹) = c ↔ a = c * ↑b := sorry theorem inv_eq_of_mul_eq_one {α : Type u} [monoid α] {u : units α} {a : α} (h : ↑u * a = 1) : ↑(u⁻¹) = a := sorry theorem inv_unique {α : Type u} [monoid α] {u₁ : units α} {u₂ : units α} (h : ↑u₁ = ↑u₂) : ↑(u₁⁻¹) = ↑(u₂⁻¹) := (fun (this : ↑u₁ * ↑(u₂⁻¹) = 1) => inv_eq_of_mul_eq_one this) (eq.mpr (id (Eq._oldrec (Eq.refl (↑u₁ * ↑(u₂⁻¹) = 1)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (↑u₂ * ↑(u₂⁻¹) = 1)) (mul_inv u₂))) (Eq.refl 1))) end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ def add_units.mk_of_add_eq_zero {α : Type u} [add_comm_monoid α] (a : α) (b : α) (hab : a + b = 0) : add_units α := add_units.mk a b hab sorry @[simp] theorem units.coe_mk_of_mul_eq_one {α : Type u} [comm_monoid α] {a : α} {b : α} (h : a * b = 1) : ↑(units.mk_of_mul_eq_one a b h) = a := rfl /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp {α : Type u} [monoid α] (a : α) (u : units α) : α := a * ↑(u⁻¹) infixl:70 " /ₚ " => Mathlib.divp @[simp] theorem divp_self {α : Type u} [monoid α] (u : units α) : ↑u /ₚ u = 1 := units.mul_inv u @[simp] theorem divp_one {α : Type u} [monoid α] (a : α) : a /ₚ 1 = a := mul_one a theorem divp_assoc {α : Type u} [monoid α] (a : α) (b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc a b ↑(u⁻¹) @[simp] theorem divp_inv {α : Type u} [monoid α] {a : α} (u : units α) : a /ₚ (u⁻¹) = a * ↑u := rfl @[simp] theorem divp_mul_cancel {α : Type u} [monoid α] (a : α) (u : units α) : a /ₚ u * ↑u = a := Eq.trans (mul_assoc a ↑(u⁻¹) ↑u) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (↑(u⁻¹) * ↑u) = a)) (units.inv_mul u))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = a)) (mul_one a))) (Eq.refl a))) @[simp] theorem mul_divp_cancel {α : Type u} [monoid α] (a : α) (u : units α) : a * ↑u /ₚ u = a := Eq.trans (mul_assoc a ↑u ↑(u⁻¹)) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (↑u * ↑(u⁻¹)) = a)) (units.mul_inv u))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = a)) (mul_one a))) (Eq.refl a))) @[simp] theorem divp_left_inj {α : Type u} [monoid α] (u : units α) {a : α} {b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj (u⁻¹) theorem divp_divp_eq_divp_mul {α : Type u} [monoid α] (x : α) (u₁ : units α) (u₂ : units α) : x /ₚ u₁ /ₚ u₂ = x /ₚ (u₂ * u₁) := sorry theorem divp_eq_iff_mul_eq {α : Type u} [monoid α] {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * ↑u = x := iff.trans (iff.symm (units.mul_left_inj u)) (eq.mpr (id (Eq._oldrec (Eq.refl (x /ₚ u * ↑u = y * ↑u ↔ y * ↑u = x)) (divp_mul_cancel x u))) { mp := Eq.symm, mpr := Eq.symm }) theorem divp_eq_one_iff_eq {α : Type u} [monoid α] {a : α} {u : units α} : a /ₚ u = 1 ↔ a = ↑u := iff.trans (iff.symm (units.mul_left_inj u)) (eq.mpr (id (Eq._oldrec (Eq.refl (a /ₚ u * ↑u = 1 * ↑u ↔ a = ↑u)) (divp_mul_cancel a u))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = 1 * ↑u ↔ a = ↑u)) (one_mul ↑u))) (iff.refl (a = ↑u)))) @[simp] theorem one_divp {α : Type u} [monoid α] (u : units α) : 1 /ₚ u = ↑(u⁻¹) := one_mul ↑(u⁻¹) theorem divp_eq_divp_iff {α : Type u} [comm_monoid α] {x : α} {y : α} {ux : units α} {uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * ↑uy = y * ↑ux := sorry theorem divp_mul_divp {α : Type u} [comm_monoid α] (x : α) (y : α) (ux : units α) (uy : units α) : x /ₚ ux * (y /ₚ uy) = x * y /ₚ (ux * uy) := sorry /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ def is_unit {M : Type u_1} [monoid M] (a : M) := ∃ (u : units M), ↑u = a theorem is_unit_of_subsingleton {M : Type u_1} [monoid M] [subsingleton M] (a : M) : is_unit a := Exists.intro (units.mk a a (subsingleton.elim (a * a) 1) (subsingleton.elim (a * a) 1)) rfl @[simp] theorem is_unit_unit {M : Type u_1} [monoid M] (u : units M) : is_unit ↑u := Exists.intro u rfl @[simp] theorem is_add_unit_zero {M : Type u_1} [add_monoid M] : is_add_unit 0 := Exists.intro 0 rfl theorem is_add_unit_of_add_eq_zero {M : Type u_1} [add_comm_monoid M] (a : M) (b : M) (h : a + b = 0) : is_add_unit a := Exists.intro (add_units.mk_of_add_eq_zero a b h) rfl theorem is_add_unit_iff_exists_neg {M : Type u_1} [add_comm_monoid M] {a : M} : is_add_unit a ↔ ∃ (b : M), a + b = 0 := sorry theorem is_add_unit_iff_exists_neg' {M : Type u_1} [add_comm_monoid M] {a : M} : is_add_unit a ↔ ∃ (b : M), b + a = 0 := sorry /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp] theorem units.is_unit_mul_units {M : Type u_1} [monoid M] (a : M) (u : units M) : is_unit (a * ↑u) ↔ is_unit a := sorry theorem is_unit.mul {M : Type u_1} [monoid M] {x : M} {y : M} : is_unit x → is_unit y → is_unit (x * y) := sorry theorem is_add_unit_of_add_is_add_unit_left {M : Type u_1} [add_comm_monoid M] {x : M} {y : M} (hu : is_add_unit (x + y)) : is_add_unit x := sorry theorem is_unit_of_mul_is_unit_right {M : Type u_1} [comm_monoid M] {x : M} {y : M} (hu : is_unit (x * y)) : is_unit y := is_unit_of_mul_is_unit_left (eq.mpr (id (Eq._oldrec (Eq.refl (is_unit (y * x))) (mul_comm y x))) hu) theorem is_unit.mul_right_inj {M : Type u_1} [monoid M] {a : M} {b : M} {c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := sorry theorem is_unit.mul_left_inj {M : Type u_1} [monoid M] {a : M} {b : M} {c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := sorry /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ def is_unit.unit {M : Type u_1} [monoid M] {a : M} (h : is_unit a) : units M := classical.some h theorem is_unit.unit_spec {M : Type u_1} [monoid M] {a : M} (h : is_unit a) : ↑(is_unit.unit h) = a := classical.some_spec h /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ def group_of_is_unit {M : Type u_1} [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := group.mk monoid.mul monoid.mul_assoc monoid.one monoid.one_mul monoid.mul_one (fun (a : M) => ↑(is_unit.unit (h a)⁻¹)) (div_inv_monoid.div._default monoid.mul monoid.mul_assoc monoid.one monoid.one_mul monoid.mul_one fun (a : M) => ↑(is_unit.unit (h a)⁻¹)) sorry /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ def comm_group_of_is_unit {M : Type u_1} [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := comm_group.mk comm_monoid.mul comm_monoid.mul_assoc comm_monoid.one comm_monoid.one_mul comm_monoid.mul_one (fun (a : M) => ↑(is_unit.unit (h a)⁻¹)) (group.div._default comm_monoid.mul comm_monoid.mul_assoc comm_monoid.one comm_monoid.one_mul comm_monoid.mul_one fun (a : M) => ↑(is_unit.unit (h a)⁻¹)) sorry comm_monoid.mul_comm
cf35678420c53d2f61aad4c1ad03fd8d6c93d9d1
cf39355caa609c0f33405126beee2739aa3cb77e
/library/tools/debugger/util.lean
07192a529ef433e5fbf708cec8965b2b903b3331
[ "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
3,961
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 -/ namespace debugger def is_space (c : char) : bool := if c = ' ' ∨ c = char.of_nat 11 ∨ c = '\n' then tt else ff private def split_core : list char → option string → list string | (c::cs) none := if is_space c then split_core cs none else split_core cs (some $ string.singleton c) | (c::cs) (some s) := if is_space c then s :: split_core cs none else split_core cs (s.str c) | [] none := [] | [] (some s) := [s] def split (s : string) : list string := split_core s.to_list none def to_qualified_name_core : list char → name → string → name | [] r s := if s.is_empty then r else r <.> s | (c::cs) r s := if is_space c then to_qualified_name_core cs r s else if c = '.' then if s.is_empty then to_qualified_name_core cs r "" else to_qualified_name_core cs (r <.> s) "" else to_qualified_name_core cs r (s.str c) def to_qualified_name (s : string) : name := to_qualified_name_core s.to_list name.anonymous "" def olean_to_lean (s : string) := s.popn_back 5 ++ "lean" meta def get_file (fn : name) : vm string := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (olean_to_lean n) } <|> return "[current file]" meta def pos_info (fn : name) : vm string := do { d ← vm.get_decl fn, some p ← return (vm_decl.pos d) | failure, file ← get_file fn, return sformat!"{file}:{p.line}:{p.column}" } <|> return "<position not available>" meta def show_fn (header : string) (fn : name) (frame : nat) : vm unit := do pos ← pos_info fn, vm.put_str sformat!"[{frame}] {header}", if header = "" then return () else vm.put_str " ", vm.put_str sformat!"{fn} at {pos}\n" meta def show_curr_fn (header : string) : vm unit := do fn ← vm.curr_fn, sz ← vm.call_stack_size, show_fn header fn (sz-1) meta def is_valid_fn_prefix (p : name) : vm bool := do env ← vm.get_env, return $ env.fold ff (λ d r, r || let n := d.to_name in p.is_prefix_of n) meta def show_frame (frame_idx : nat) : vm unit := do sz ← vm.call_stack_size, fn ← if frame_idx >= sz then vm.curr_fn else vm.call_stack_fn frame_idx, show_fn "" fn frame_idx meta def type_to_string : option expr → nat → vm string | none i := do o ← vm.stack_obj i, match o.kind with | vm_obj_kind.simple := return "[tagged value]" | vm_obj_kind.constructor := return "[constructor]" | vm_obj_kind.closure := return "[closure]" | vm_obj_kind.native_closure := return "[native closure]" | vm_obj_kind.mpz := return "[big num]" | vm_obj_kind.name := return "name" | vm_obj_kind.level := return "level" | vm_obj_kind.expr := return "expr" | vm_obj_kind.declaration := return "declaration" | vm_obj_kind.environment := return "environment" | vm_obj_kind.tactic_state := return "tactic_state" | vm_obj_kind.format := return "format" | vm_obj_kind.options := return "options" | vm_obj_kind.other := return "[other]" end | (some type) i := do fmt ← vm.pp_expr type, opts ← vm.get_options, return $ fmt.to_string opts meta def show_vars_core : nat → nat → nat → vm unit | c i e := if i = e then return () else do (n, type) ← vm.stack_obj_info i, type_str ← type_to_string type i, vm.put_str sformat!"#{c} {n} : {type_str}\n", show_vars_core (c+1) (i+1) e meta def show_vars (frame : nat) : vm unit := do (s, e) ← vm.call_stack_var_range frame, show_vars_core 0 s e meta def show_stack_core : nat → vm unit | 0 := return () | (i+1) := do fn ← vm.call_stack_fn i, show_fn "" fn i, show_stack_core i meta def show_stack : vm unit := do sz ← vm.call_stack_size, show_stack_core sz end debugger
f7e1b1360b66089346bfe46f4cfec98e617813bc
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/witt_vector/is_poly.lean
40fd85e10b91661d72786d80dd9887d178754c48
[ "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
23,409
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.ring.ulift import ring_theory.witt_vector.basic import data.mv_polynomial.funext /-! # The `is_poly` predicate `witt_vector.is_poly` is a (type-valued) predicate on functions `f : Π R, 𝕎 R → 𝕎 R`. It asserts that there is a family of polynomials `φ : ℕ → mv_polynomial ℕ ℤ`, such that the `n`th coefficient of `f x` is equal to `φ n` evaluated on the coefficients of `x`. Many operations on Witt vectors satisfy this predicate (or an analogue for higher arity functions). We say that such a function `f` is a *polynomial function*. The power of satisfying this predicate comes from `is_poly.ext`. It shows that if `φ` and `ψ` witness that `f` and `g` are polynomial functions, then `f = g` not merely when `φ = ψ`, but in fact it suffices to prove ``` ∀ n, bind₁ φ (witt_polynomial p _ n) = bind₁ ψ (witt_polynomial p _ n) ``` (in other words, when evaluating the Witt polynomials on `φ` and `ψ`, we get the same values) which will then imply `φ = ψ` and hence `f = g`. Even though this sufficient condition looks somewhat intimidating, it is rather pleasant to check in practice; more so than direct checking of `φ = ψ`. In practice, we apply this technique to show that the composition of `witt_vector.frobenius` and `witt_vector.verschiebung` is equal to multiplication by `p`. ## Main declarations * `witt_vector.is_poly`, `witt_vector.is_poly₂`: two predicates that assert that a unary/binary function on Witt vectors is polynomial in the coefficients of the input values. * `witt_vector.is_poly.ext`, `witt_vector.is_poly₂.ext`: two polynomial functions are equal if their families of polynomials are equal after evaluating the Witt polynomials on them. * `witt_vector.is_poly.comp` (+ many variants) show that unary/binary compositions of polynomial functions are polynomial. * `witt_vector.id_is_poly`, `witt_vector.neg_is_poly`, `witt_vector.add_is_poly₂`, `witt_vector.mul_is_poly₂`: several well-known operations are polynomial functions (for Verschiebung, Frobenius, and multiplication by `p`, see their respective files). ## On higher arity analogues Ideally, there should be a predicate `is_polyₙ` for functions of higher arity, together with `is_polyₙ.comp` that shows how such functions compose. Since mathlib does not have a library on composition of higher arity functions, we have only implemented the unary and binary variants so far. Nullary functions (a.k.a. constants) are treated as constant functions and fall under the unary case. ## Tactics There are important metaprograms defined in this file: the tactics `ghost_simp` and `ghost_calc` and the attributes `@[is_poly]` and `@[ghost_simps]`. These are used in combination to discharge proofs of identities between polynomial functions. Any atomic proof of `is_poly` or `is_poly₂` (i.e. not taking additional `is_poly` arguments) should be tagged as `@[is_poly]`. Any lemma doing "ring equation rewriting" with polynomial functions should be tagged `@[ghost_simps]`, e.g. ```lean @[ghost_simps] lemma bind₁_frobenius_poly_witt_polynomial (n : ℕ) : bind₁ (frobenius_poly p) (witt_polynomial p ℤ n) = (witt_polynomial p ℤ (n+1)) ``` Proofs of identities between polynomial functions will often follow the pattern ```lean begin ghost_calc _, <minor preprocessing>, ghost_simp end ``` ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ /- ### Simplification tactics `ghost_simp` is used later in the development for certain simplifications. We define it here so it is a shared import. -/ mk_simp_attribute ghost_simps "Simplification rules for ghost equations" namespace tactic namespace interactive setup_tactic_parser /-- A macro for a common simplification when rewriting with ghost component equations. -/ meta def ghost_simp (lems : parse simp_arg_list) : tactic unit := do tactic.try tactic.intro1, simp none none tt (lems ++ [simp_arg_type.symm_expr ``(sub_eq_add_neg)]) [`ghost_simps] (loc.ns [none]) /-- `ghost_calc` is a tactic for proving identities between polynomial functions. Typically, when faced with a goal like ```lean ∀ (x y : 𝕎 R), verschiebung (x * frobenius y) = verschiebung x * y ``` you can 1. call `ghost_calc` 2. do a small amount of manual work -- maybe nothing, maybe `rintro`, etc 3. call `ghost_simp` and this will close the goal. `ghost_calc` cannot detect whether you are dealing with unary or binary polynomial functions. You must give it arguments to determine this. If you are proving a universally quantified goal like the above, call `ghost_calc _ _`. If the variables are introduced already, call `ghost_calc x y`. In the unary case, use `ghost_calc _` or `ghost_calc x`. `ghost_calc` is a light wrapper around type class inference. All it does is apply the appropriate extensionality lemma and try to infer the resulting goals. This is subtle and Lean's elaborator doesn't like it because of the HO unification involved, so it is easier (and prettier) to put it in a tactic script. -/ meta def ghost_calc (ids' : parse ident_*) : tactic unit := do ids ← ids'.mmap $ λ n, get_local n <|> tactic.intro n, `(@eq (witt_vector _ %%R) _ _) ← target, match ids with | [x] := refine ```(is_poly.ext _ _ _ _ %%x) | [x, y] := refine ```(is_poly₂.ext _ _ _ _ %%x %%y) | _ := fail "ghost_calc takes one or two arguments" end, nm ← match R with | expr.local_const _ nm _ _ := return nm | _ := get_unused_name `R end, iterate_exactly 2 apply_instance, unfreezingI (tactic.clear' tt [R]), introsI $ [nm, nm<.>"_inst"] ++ ids', skip end interactive end tactic namespace witt_vector universe variable u variables {p : ℕ} {R S : Type u} {σ idx : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` open mv_polynomial open function (uncurry) include hp variables (p) noncomputable theory /-! ### The `is_poly` predicate -/ lemma poly_eq_of_witt_polynomial_bind_eq' (f g : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) : f = g := begin ext1 n, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw ← function.funext_iff at h, replace h := congr_arg (λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam) (X_in_terms_of_W p ℚ n)) h, simpa only [function.comp, map_bind₁, map_witt_polynomial, ← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h end lemma poly_eq_of_witt_polynomial_bind_eq (f g : ℕ → mv_polynomial ℕ ℤ) (h : ∀ n, bind₁ f (witt_polynomial p _ n) = bind₁ g (witt_polynomial p _ n)) : f = g := begin ext1 n, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw ← function.funext_iff at h, replace h := congr_arg (λ fam, bind₁ (mv_polynomial.map (int.cast_ring_hom ℚ) ∘ fam) (X_in_terms_of_W p ℚ n)) h, simpa only [function.comp, map_bind₁, map_witt_polynomial, ← bind₁_bind₁, bind₁_witt_polynomial_X_in_terms_of_W, bind₁_X_right] using h end omit hp -- Ideally, we would generalise this to n-ary functions -- But we don't have a good theory of n-ary compositions in mathlib /-- A function `f : Π R, 𝕎 R → 𝕎 R` that maps Witt vectors to Witt vectors over arbitrary base rings is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th coefficient of `f x` is given by evaluating `φₙ` at the coefficients of `x`. See also `witt_vector.is_poly₂` for the binary variant. The `ghost_calc` tactic treats `is_poly` as a type class, and the `@[is_poly]` attribute derives certain specialized composition instances for declarations of type `is_poly f`. For the most part, users are not expected to treat `is_poly` as a class. -/ class is_poly (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R) : Prop := mk' :: (poly : ∃ φ : ℕ → mv_polynomial ℕ ℤ, ∀ ⦃R⦄ [comm_ring R] (x : 𝕎 R), by exactI (f x).coeff = λ n, aeval x.coeff (φ n)) /-- The identity function on Witt vectors is a polynomial function. -/ instance id_is_poly : is_poly p (λ _ _, id) := ⟨⟨X, by { introsI, simp only [aeval_X, id] }⟩⟩ instance id_is_poly_i' : is_poly p (λ _ _ a, a) := witt_vector.id_is_poly _ namespace is_poly instance : inhabited (is_poly p (λ _ _, id)) := ⟨witt_vector.id_is_poly p⟩ variables {p} include hp lemma ext {f g} (hf : is_poly p f) (hg : is_poly p g) (h : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R) (n : ℕ), by exactI ghost_component n (f x) = ghost_component n (g x)) : ∀ (R : Type u) [_Rcr : comm_ring R] (x : 𝕎 R), by exactI f x = g x := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, intros, ext n, rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq p φ ψ], intro k, apply mv_polynomial.funext, intro x, simp only [hom_bind₁], specialize h (ulift ℤ) (mk p $ λ i, ⟨x i⟩) k, simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h, apply (ulift.ring_equiv.symm : ℤ ≃+* _).injective, simp only [←ring_equiv.coe_to_ring_hom, map_eval₂_hom], convert h using 1, all_goals { funext i, simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext1, apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, simp only [coeff_mk], refl } end omit hp /-- The composition of polynomial functions is polynomial. -/ lemma comp {g f} (hg : is_poly p g) (hf : is_poly p f) : is_poly p (λ R _Rcr, @g R _Rcr ∘ @f R _Rcr) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, use (λ n, bind₁ φ (ψ n)), intros, simp only [aeval_bind₁, function.comp, hg, hf] end end is_poly /-- A binary function `f : Π R, 𝕎 R → 𝕎 R → 𝕎 R` on Witt vectors is said to be *polynomial* if there is a family of polynomials `φₙ` over `ℤ` such that the `n`th coefficient of `f x y` is given by evaluating `φₙ` at the coefficients of `x` and `y`. See also `witt_vector.is_poly` for the unary variant. The `ghost_calc` tactic treats `is_poly₂` as a type class, and the `@[is_poly]` attribute derives certain specialized composition instances for declarations of type `is_poly₂ f`. For the most part, users are not expected to treat `is_poly₂` as a class. -/ class is_poly₂ (f : Π ⦃R⦄ [comm_ring R], witt_vector p R → 𝕎 R → 𝕎 R) : Prop := mk' :: (poly : ∃ φ : ℕ → mv_polynomial (fin 2 × ℕ) ℤ, ∀ ⦃R⦄ [comm_ring R] (x y : 𝕎 R), by exactI (f x y).coeff = λ n, peval (φ n) ![x.coeff, y.coeff]) variable {p} /-- The composition of polynomial functions is polynomial. -/ lemma is_poly₂.comp {h f g} (hh : is_poly₂ p h) (hf : is_poly p f) (hg : is_poly p g) : is_poly₂ p (λ R _Rcr x y, by exactI h (f x) (g y)) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg, obtain ⟨χ, hh⟩ := hh }, refine ⟨⟨(λ n, bind₁ (uncurry $ ![λ k, rename (prod.mk (0 : fin 2)) (φ k), λ k, rename (prod.mk (1 : fin 2)) (ψ k)]) (χ n)), _⟩⟩, intros, funext n, simp only [peval, aeval_bind₁, function.comp, hh, hf, hg, uncurry], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, n⟩, fin_cases i; simp only [aeval_eq_eval₂_hom, eval₂_hom_rename, function.comp, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one], end /-- The composition of a polynomial function with a binary polynomial function is polynomial. -/ lemma is_poly.comp₂ {g f} (hg : is_poly p g) (hf : is_poly₂ p f) : is_poly₂ p (λ R _Rcr x y, by exactI g (f x y)) := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, use (λ n, bind₁ φ (ψ n)), intros, simp only [peval, aeval_bind₁, function.comp, hg, hf] end /-- The diagonal `λ x, f x x` of a polynomial function `f` is polynomial. -/ lemma is_poly₂.diag {f} (hf : is_poly₂ p f) : is_poly p (λ R _Rcr x, by exactI f x x) := begin unfreezingI {obtain ⟨φ, hf⟩ := hf}, refine ⟨⟨λ n, bind₁ (uncurry ![X, X]) (φ n), _⟩⟩, intros, funext n, simp only [hf, peval, uncurry, aeval_bind₁], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, k⟩, fin_cases i; simp only [matrix.head_cons, aeval_X, matrix.cons_val_zero, matrix.cons_val_one], end namespace tactic open tactic /-! ### The `@[is_poly]` attribute This attribute is used to derive specialized composition instances for `is_poly` and `is_poly₂` declarations. -/ /-- If `n` is the name of a lemma with opened type `∀ vars, is_poly p _`, `mk_poly_comp_lemmas n vars p` adds composition instances to the environment `n.comp_i` and `n.comp₂_i`. -/ meta def mk_poly_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit := do c ← mk_const n, let appd := vars.foldl expr.app c, tgt_bod ← to_expr ``(λ f [hf : is_poly %%p f], is_poly.comp %%appd hf) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod, let nm := n <.> "comp_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm, tgt_bod ← to_expr ``(λ f [hf : is_poly₂ %%p f], is_poly.comp₂ %%appd hf) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod, let nm := n <.> "comp₂_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm /-- If `n` is the name of a lemma with opened type `∀ vars, is_poly₂ p _`, `mk_poly₂_comp_lemmas n vars p` adds composition instances to the environment `n.comp₂_i` and `n.comp_diag`. -/ meta def mk_poly₂_comp_lemmas (n : name) (vars : list expr) (p : expr) : tactic unit := do c ← mk_const n, let appd := vars.foldl expr.app c, tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g], is_poly₂.comp %%appd hf hg) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify, let nm := n <.> "comp₂_i", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm, tgt_bod ← to_expr ``(λ {f g} [hf : is_poly %%p f] [hg : is_poly %%p g], (is_poly₂.comp %%appd hf hg).diag) >>= replace_univ_metas_with_univ_params, tgt_bod ← lambdas vars tgt_bod, tgt_tp ← infer_type tgt_bod >>= simp_lemmas.mk.dsimplify, let nm := n <.> "comp_diag", add_decl $ mk_definition nm tgt_tp.collect_univ_params tgt_tp tgt_bod, set_attribute `instance nm /-- The `after_set` function for `@[is_poly]`. Calls `mk_poly(₂)_comp_lemmas`. -/ meta def mk_comp_lemmas (n : name) : tactic unit := do d ← get_decl n, (vars, tp) ← open_pis d.type, match tp with | `(is_poly %%p _) := mk_poly_comp_lemmas n vars p | `(is_poly₂ %%p _) := mk_poly₂_comp_lemmas n vars p | _ := fail "@[is_poly] should only be applied to terms of type `is_poly _ _` or `is_poly₂ _ _`" end /-- `@[is_poly]` is applied to lemmas of the form `is_poly f φ` or `is_poly₂ f φ`. These lemmas should *not* be tagged as instances, and only atomic `is_poly` defs should be tagged: composition lemmas should not. Roughly speaking, lemmas that take `is_poly` proofs as arguments should not be tagged. Type class inference struggles with function composition, and the higher order unification problems involved in inferring `is_poly` proofs are complex. The standard style writing these proofs by hand doesn't work very well. Instead, we construct the type class hierarchy "under the hood", with limited forms of composition. Applying `@[is_poly]` to a lemma creates a number of instances. Roughly, if the tagged lemma is a proof of `is_poly f φ`, the instances added have the form ```lean ∀ g ψ, [is_poly g ψ] → is_poly (f ∘ g) _ ``` Since `f` is fixed in this instance, it restricts the HO unification needed when the instance is applied. Composition lemmas relating `is_poly` with `is_poly₂` are also added. `id_is_poly` is an atomic instance. The user-written lemmas are not instances. Users should be able to assemble `is_poly` proofs by hand "as normal" if the tactic fails. -/ @[user_attribute] meta def is_poly_attr : user_attribute := { name := `is_poly, descr := "Lemmas with this attribute describe the polynomial structure of functions", after_set := some $ λ n _ _, mk_comp_lemmas n } end tactic include hp /-! ### `is_poly` instances These are not declared as instances at the top level, but the `@[is_poly]` attribute adds instances based on each one. Users are expected to use the non-instance versions manually. -/ /-- The additive negation is a polynomial function on Witt vectors. -/ @[is_poly] lemma neg_is_poly : is_poly p (λ R _, by exactI @has_neg.neg (𝕎 R) _) := ⟨⟨λ n, rename prod.snd (witt_neg p n), begin introsI, funext n, rw [neg_coeff, aeval_eq_eval₂_hom, eval₂_hom_rename], apply eval₂_hom_congr rfl _ rfl, ext ⟨i, k⟩, fin_cases i, refl, end⟩⟩ section zero_one /- To avoid a theory of 0-ary functions (a.k.a. constants) we model them as constant unary functions. -/ /-- The function that is constantly zero on Witt vectors is a polynomial function. -/ instance zero_is_poly : is_poly p (λ _ _ _, by exactI 0) := ⟨⟨0, by { introsI, funext n, simp only [pi.zero_apply, alg_hom.map_zero, zero_coeff] }⟩⟩ @[simp] lemma bind₁_zero_witt_polynomial (n : ℕ) : bind₁ (0 : ℕ → mv_polynomial ℕ R) (witt_polynomial p R n) = 0 := by rw [← aeval_eq_bind₁, aeval_zero, constant_coeff_witt_polynomial, ring_hom.map_zero] omit hp /-- The coefficients of `1 : 𝕎 R` as polynomials. -/ def one_poly (n : ℕ) : mv_polynomial ℕ ℤ := if n = 0 then 1 else 0 include hp @[simp] lemma bind₁_one_poly_witt_polynomial (n : ℕ) : bind₁ one_poly (witt_polynomial p ℤ n) = 1 := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum, finset.sum_eq_single 0], { simp only [one_poly, one_pow, one_mul, alg_hom.map_pow, C_1, pow_zero, bind₁_X_right, if_true, eq_self_iff_true], }, { intros i hi hi0, simp only [one_poly, if_neg hi0, zero_pow (pow_pos hp.1.pos _), mul_zero, alg_hom.map_pow, bind₁_X_right, alg_hom.map_mul], }, { rw finset.mem_range, dec_trivial } end /-- The function that is constantly one on Witt vectors is a polynomial function. -/ instance one_is_poly : is_poly p (λ _ _ _, by exactI 1) := ⟨⟨one_poly, begin introsI, funext n, cases n, { simp only [one_poly, if_true, eq_self_iff_true, one_coeff_zero, alg_hom.map_one], }, { simp only [one_poly, nat.succ_pos', one_coeff_eq_of_pos, if_neg n.succ_ne_zero, alg_hom.map_zero] } end⟩⟩ end zero_one omit hp /-- Addition of Witt vectors is a polynomial function. -/ @[is_poly] lemma add_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (+)) := ⟨⟨witt_add p, by { introsI, dunfold witt_vector.has_add, simp [eval] }⟩⟩ /-- Multiplication of Witt vectors is a polynomial function. -/ @[is_poly] lemma mul_is_poly₂ [fact p.prime] : is_poly₂ p (λ _ _, by exactI (*)) := ⟨⟨witt_mul p, by { introsI, dunfold witt_vector.has_mul, simp [eval] }⟩⟩ include hp -- unfortunately this is not universe polymorphic, merely because `f` isn't lemma is_poly.map {f} (hf : is_poly p f) (g : R →+* S) (x : 𝕎 R) : map g (f x) = f (map g x) := begin -- this could be turned into a tactic “macro” (taking `hf` as parameter) -- so that applications do not have to worry about the universe issue -- see `is_poly₂.map` for a slightly more general proof strategy unfreezingI {obtain ⟨φ, hf⟩ := hf}, ext n, simp only [map_coeff, hf, map_aeval], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, simp only [map_coeff] end namespace is_poly₂ omit hp instance [fact p.prime] : inhabited (is_poly₂ p _) := ⟨add_is_poly₂⟩ variables {p} /-- The composition of a binary polynomial function with a unary polynomial function in the first argument is polynomial. -/ lemma comp_left {g f} (hg : is_poly₂ p g) (hf : is_poly p f) : is_poly₂ p (λ R _Rcr x y, by exactI g (f x) y) := hg.comp hf (witt_vector.id_is_poly _) /-- The composition of a binary polynomial function with a unary polynomial function in the second argument is polynomial. -/ lemma comp_right {g f} (hg : is_poly₂ p g) (hf : is_poly p f) : is_poly₂ p (λ R _Rcr x y, by exactI g x (f y)) := hg.comp (witt_vector.id_is_poly p) hf include hp lemma ext {f g} (hf : is_poly₂ p f) (hg : is_poly₂ p g) (h : ∀ (R : Type u) [_Rcr : comm_ring R] (x y : 𝕎 R) (n : ℕ), by exactI ghost_component n (f x y) = ghost_component n (g x y)) : ∀ (R) [_Rcr : comm_ring R] (x y : 𝕎 R), by exactI f x y = g x y := begin unfreezingI { obtain ⟨φ, hf⟩ := hf, obtain ⟨ψ, hg⟩ := hg }, intros, ext n, rw [hf, hg, poly_eq_of_witt_polynomial_bind_eq' p φ ψ], clear x y, intro k, apply mv_polynomial.funext, intro x, simp only [hom_bind₁], specialize h (ulift ℤ) (mk p $ λ i, ⟨x (0, i)⟩) (mk p $ λ i, ⟨x (1, i)⟩) k, simp only [ghost_component_apply, aeval_eq_eval₂_hom] at h, apply (ulift.ring_equiv.symm : ℤ ≃+* _).injective, simp only [←ring_equiv.coe_to_ring_hom, map_eval₂_hom], convert h using 1, all_goals { funext i, simp only [hf, hg, mv_polynomial.eval, map_eval₂_hom], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext1, apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext ⟨b, _⟩, fin_cases b; simp only [coeff_mk, uncurry]; refl } end -- unfortunately this is not universe polymorphic, merely because `f` isn't lemma map {f} (hf : is_poly₂ p f) (g : R →+* S) (x y : 𝕎 R) : map g (f x y) = f (map g x) (map g y) := begin -- this could be turned into a tactic “macro” (taking `hf` as parameter) -- so that applications do not have to worry about the universe issue unfreezingI {obtain ⟨φ, hf⟩ := hf}, ext n, simp only [map_coeff, hf, map_aeval, peval, uncurry], apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, try { ext ⟨i, k⟩, fin_cases i }, all_goals { simp only [map_coeff, matrix.cons_val_zero, matrix.head_cons, matrix.cons_val_one] }, end end is_poly₂ attribute [ghost_simps] alg_hom.map_zero alg_hom.map_one alg_hom.map_add alg_hom.map_mul alg_hom.map_sub alg_hom.map_neg alg_hom.id_apply alg_hom.map_nat_cast ring_hom.map_zero ring_hom.map_one ring_hom.map_mul ring_hom.map_add ring_hom.map_sub ring_hom.map_neg ring_hom.id_apply ring_hom.map_nat_cast mul_add add_mul add_zero zero_add mul_one one_mul mul_zero zero_mul nat.succ_ne_zero nat.add_sub_cancel nat.succ_eq_add_one if_true eq_self_iff_true if_false forall_true_iff forall_2_true_iff forall_3_true_iff end witt_vector
d5bfb28fb1d2b28cafb9724f86e24670648c4069
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/lie/quotient.lean
95bce9a6887ca702d1b969559673cd02b35ebe67
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
7,615
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.submodule import algebra.lie.of_associative import linear_algebra.isomorphisms /-! # Quotients of Lie algebras and Lie modules Given a Lie submodule of a Lie module, the quotient carries a natural Lie module structure. In the special case that the Lie module is the Lie algebra itself via the adjoint action, the submodule is a Lie ideal and the quotient carries a natural Lie algebra structure. We define these quotient structures here. A notable omission at the time of writing (February 2021) is a statement and proof of the universal property of these quotients. ## Main definitions * `lie_submodule.quotient.lie_quotient_lie_module` * `lie_submodule.quotient.lie_quotient_lie_algebra` ## Tags lie algebra, quotient -/ universes u v w w₁ w₂ namespace lie_submodule variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) /-- The quotient of a Lie module by a Lie submodule. It is a Lie module. -/ instance : has_quotient M (lie_submodule R L M) := ⟨λ N, M ⧸ N.to_submodule⟩ namespace quotient variables {N I} instance add_comm_group : add_comm_group (M ⧸ N) := submodule.quotient.add_comm_group _ instance module' {S : Type*} [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] : module S (M ⧸ N) := submodule.quotient.module' _ instance module : module R (M ⧸ N) := submodule.quotient.module _ instance is_central_scalar {S : Type*} [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] [has_smul Sᵐᵒᵖ R] [module Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S (M ⧸ N) := submodule.quotient.is_central_scalar _ instance inhabited : inhabited (M ⧸ N) := ⟨0⟩ /-- Map sending an element of `M` to the corresponding element of `M/N`, when `N` is a lie_submodule of the lie_module `N`. -/ abbreviation mk : M → M ⧸ N := submodule.quotient.mk lemma is_quotient_mk (m : M) : quotient.mk' m = (mk m : M ⧸ N) := rfl /-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is a natural linear map from `L` to the endomorphisms of `M` leaving `N` invariant. -/ def lie_submodule_invariant : L →ₗ[R] submodule.compatible_maps N.to_submodule N.to_submodule := linear_map.cod_restrict _ (lie_module.to_endomorphism R L M) N.lie_mem variables (N) /-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is a natural Lie algebra morphism from `L` to the linear endomorphism of the quotient `M/N`. -/ def action_as_endo_map : L →ₗ⁅R⁆ module.End R (M ⧸ N) := { map_lie' := λ x y, submodule.linear_map_qext _ $ linear_map.ext $ λ m, congr_arg mk $ lie_lie _ _ _, ..linear_map.comp (submodule.mapq_linear (N : submodule R M) ↑N) lie_submodule_invariant } /-- Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M`, there is a natural bracket action of `L` on the quotient `M/N`. -/ instance action_as_endo_map_bracket : has_bracket L (M ⧸ N) := ⟨λ x n, action_as_endo_map N x n⟩ instance lie_quotient_lie_ring_module : lie_ring_module L (M ⧸ N) := { bracket := has_bracket.bracket, ..lie_ring_module.comp_lie_hom _ (action_as_endo_map N) } /-- The quotient of a Lie module by a Lie submodule, is a Lie module. -/ instance lie_quotient_lie_module : lie_module R L (M ⧸ N) := lie_module.comp_lie_hom _ (action_as_endo_map N) instance lie_quotient_has_bracket : has_bracket (L ⧸ I) (L ⧸ I) := ⟨begin intros x y, apply quotient.lift_on₂' x y (λ x' y', mk ⁅x', y'⁆), intros x₁ x₂ y₁ y₂ h₁ h₂, apply (submodule.quotient.eq I.to_submodule).2, rw submodule.quotient_rel_r_def at h₁ h₂, have h : ⁅x₁, x₂⁆ - ⁅y₁, y₂⁆ = ⁅x₁, x₂ - y₂⁆ + ⁅x₁ - y₁, y₂⁆, by simp [-lie_skew, sub_eq_add_neg, add_assoc], rw h, apply submodule.add_mem, { apply lie_mem_right R L I x₁ (x₂ - y₂) h₂, }, { apply lie_mem_left R L I (x₁ - y₁) y₂ h₁, }, end⟩ @[simp] lemma mk_bracket (x y : L) : mk ⁅x, y⁆ = ⁅(mk x : L ⧸ I), (mk y : L ⧸ I)⁆ := rfl instance lie_quotient_lie_ring : lie_ring (L ⧸ I) := { add_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply add_lie, }, lie_add := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply lie_add, }, lie_self := by { intros x', apply quotient.induction_on' x', intros x, rw [is_quotient_mk, ←mk_bracket], apply congr_arg, apply lie_self, }, leibniz_lie := by { intros x' y' z', apply quotient.induction_on₃' x' y' z', intros x y z, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_add, }, apply congr_arg, apply leibniz_lie, } } instance lie_quotient_lie_algebra : lie_algebra R (L ⧸ I) := { lie_smul := by { intros t x' y', apply quotient.induction_on₂' x' y', intros x y, repeat { rw is_quotient_mk <|> rw ←mk_bracket <|> rw ←submodule.quotient.mk_smul, }, apply congr_arg, apply lie_smul, } } /-- `lie_submodule.quotient.mk` as a `lie_module_hom`. -/ @[simps] def mk' : M →ₗ⁅R,L⁆ M ⧸ N := { to_fun := mk, map_lie' := λ r m, rfl, ..N.to_submodule.mkq} @[simp] lemma mk_eq_zero {m : M} : mk' N m = 0 ↔ m ∈ N := submodule.quotient.mk_eq_zero N.to_submodule @[simp] lemma mk'_ker : (mk' N).ker = N := by { ext, simp, } @[simp] lemma map_mk'_eq_bot_le : map (mk' N) N' = ⊥ ↔ N' ≤ N := by rw [← lie_module_hom.le_ker_iff_map, mk'_ker] /-- Two `lie_module_hom`s from a quotient lie module are equal if their compositions with `lie_submodule.quotient.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma lie_module_hom_ext ⦃f g : M ⧸ N →ₗ⁅R,L⁆ M⦄ (h : f.comp (mk' N) = g.comp (mk' N)) : f = g := lie_module_hom.ext $ λ x, quotient.induction_on' x $ lie_module_hom.congr_fun h end quotient end lie_submodule namespace lie_hom variables {R L L' : Type*} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables (f : L →ₗ⁅R⁆ L') /-- The first isomorphism theorem for morphisms of Lie algebras. -/ @[simps] noncomputable def quot_ker_equiv_range : L ⧸ f.ker ≃ₗ⁅R⁆ f.range := { to_fun := (f : L →ₗ[R] L').quot_ker_equiv_range, map_lie' := begin rintros ⟨x⟩ ⟨y⟩, rw [← set_like.coe_eq_coe, lie_subalgebra.coe_bracket], simp only [submodule.quotient.quot_mk_eq_mk, linear_map.quot_ker_equiv_range_apply_mk, ← lie_submodule.quotient.mk_bracket, coe_to_linear_map, map_lie], end, .. (f : L →ₗ[R] L').quot_ker_equiv_range, } end lie_hom
7fa450cf93beefc329713bfcbce6b90e27497ce4
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/277a.lean
b6b0a01e40c81441866cbc33309e363735209232
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
61
lean
infixl:67 " <>< " => nonexistant #eval (1 <>< 11 : UInt64)
9d7621f3944dc56858fa8490ea7cc238cba54232
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/derivation/to_square_zero.lean
d9d0d6aae248493c7e9f60be77019e42526898d0
[ "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
5,511
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Andrew Yang -/ import ring_theory.derivation.basic import ring_theory.ideal.quotient_operations /-! # Results > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. - `derivation_to_square_zero_equiv_lift`: The `R`-derivations from `A` into a square-zero ideal `I` of `B` corresponds to the lifts `A →ₐ[R] B` of the map `A →ₐ[R] B ⧸ I`. -/ section to_square_zero universes u v w variables {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [comm_semiring A] [comm_ring B] variables [algebra R A] [algebra R B] (I : ideal B) (hI : I ^ 2 = ⊥) /-- If `f₁ f₂ : A →ₐ[R] B` are two lifts of the same `A →ₐ[R] B ⧸ I`, we may define a map `f₁ - f₂ : A →ₗ[R] I`. -/ def diff_to_ideal_of_quotient_comp_eq (f₁ f₂ : A →ₐ[R] B) (e : (ideal.quotient.mkₐ R I).comp f₁ = (ideal.quotient.mkₐ R I).comp f₂) : A →ₗ[R] I := linear_map.cod_restrict (I.restrict_scalars _) (f₁.to_linear_map - f₂.to_linear_map) begin intro x, change f₁ x - f₂ x ∈ I, rw [← ideal.quotient.eq, ← ideal.quotient.mkₐ_eq_mk R, ← alg_hom.comp_apply, e], refl, end @[simp] lemma diff_to_ideal_of_quotient_comp_eq_apply (f₁ f₂ : A →ₐ[R] B) (e : (ideal.quotient.mkₐ R I).comp f₁ = (ideal.quotient.mkₐ R I).comp f₂) (x : A) : ((diff_to_ideal_of_quotient_comp_eq I f₁ f₂ e) x : B) = f₁ x - f₂ x := rfl variables [algebra A B] [is_scalar_tower R A B] include hI /-- Given a tower of algebras `R → A → B`, and a square-zero `I : ideal B`, each lift `A →ₐ[R] B` of the canonical map `A →ₐ[R] B ⧸ I` corresponds to a `R`-derivation from `A` to `I`. -/ def derivation_to_square_zero_of_lift (f : A →ₐ[R] B) (e : (ideal.quotient.mkₐ R I).comp f = is_scalar_tower.to_alg_hom R A (B ⧸ I)) : derivation R A I := begin refine { map_one_eq_zero' := _, leibniz' := _, ..(diff_to_ideal_of_quotient_comp_eq I f (is_scalar_tower.to_alg_hom R A B) _) }, { rw e, ext, refl }, { ext, change f 1 - algebra_map A B 1 = 0, rw [map_one, map_one, sub_self] }, { intros x y, let F := diff_to_ideal_of_quotient_comp_eq I f (is_scalar_tower.to_alg_hom R A B) (by { rw e, ext, refl }), have : (f x - algebra_map A B x) * (f y - algebra_map A B y) = 0, { rw [← ideal.mem_bot, ← hI, pow_two], convert (ideal.mul_mem_mul (F x).2 (F y).2) using 1 }, ext, dsimp only [submodule.coe_add, submodule.coe_mk, linear_map.coe_mk, diff_to_ideal_of_quotient_comp_eq_apply, submodule.coe_smul_of_tower, is_scalar_tower.coe_to_alg_hom', linear_map.to_fun_eq_coe], simp only [map_mul, sub_mul, mul_sub, algebra.smul_def] at ⊢ this, rw [sub_eq_iff_eq_add, sub_eq_iff_eq_add] at this, rw this, ring } end lemma derivation_to_square_zero_of_lift_apply (f : A →ₐ[R] B) (e : (ideal.quotient.mkₐ R I).comp f = is_scalar_tower.to_alg_hom R A (B ⧸ I)) (x : A) : (derivation_to_square_zero_of_lift I hI f e x : B) = f x - algebra_map A B x := rfl /-- Given a tower of algebras `R → A → B`, and a square-zero `I : ideal B`, each `R`-derivation from `A` to `I` corresponds to a lift `A →ₐ[R] B` of the canonical map `A →ₐ[R] B ⧸ I`. -/ @[simps {attrs := []}] def lift_of_derivation_to_square_zero (f : derivation R A I) : A →ₐ[R] B := { to_fun := λ x, f x + algebra_map A B x, map_one' := by rw [map_one, f.map_one_eq_zero, submodule.coe_zero, zero_add], map_mul' := λ x y, begin have : (f x : B) * (f y) = 0, { rw [← ideal.mem_bot, ← hI, pow_two], convert (ideal.mul_mem_mul (f x).2 (f y).2) using 1 }, simp only [map_mul, f.leibniz, add_mul, mul_add, submodule.coe_add, submodule.coe_smul_of_tower, algebra.smul_def, this], ring end, commutes' := λ r, by simp only [derivation.map_algebra_map, eq_self_iff_true, zero_add, submodule.coe_zero, ←is_scalar_tower.algebra_map_apply R A B r], map_zero' := ((I.restrict_scalars R).subtype.comp f.to_linear_map + (is_scalar_tower.to_alg_hom R A B).to_linear_map).map_zero, ..((I.restrict_scalars R).subtype.comp f.to_linear_map + (is_scalar_tower.to_alg_hom R A B).to_linear_map : A →ₗ[R] B) } @[simp] lemma lift_of_derivation_to_square_zero_mk_apply (d : derivation R A I) (x : A) : ideal.quotient.mk I (lift_of_derivation_to_square_zero I hI d x) = algebra_map A (B ⧸ I) x := by { rw [lift_of_derivation_to_square_zero_apply, map_add, ideal.quotient.eq_zero_iff_mem.mpr (d x).prop, zero_add], refl } /-- Given a tower of algebras `R → A → B`, and a square-zero `I : ideal B`, there is a 1-1 correspondance between `R`-derivations from `A` to `I` and lifts `A →ₐ[R] B` of the canonical map `A →ₐ[R] B ⧸ I`. -/ @[simps] def derivation_to_square_zero_equiv_lift : derivation R A I ≃ { f : A →ₐ[R] B // (ideal.quotient.mkₐ R I).comp f = is_scalar_tower.to_alg_hom R A (B ⧸ I) } := begin refine ⟨λ d, ⟨lift_of_derivation_to_square_zero I hI d, _⟩, λ f, (derivation_to_square_zero_of_lift I hI f.1 f.2 : _), _, _⟩, { ext x, exact lift_of_derivation_to_square_zero_mk_apply I hI d x }, { intro d, ext x, exact add_sub_cancel (d x : B) (algebra_map A B x) }, { rintro ⟨f, hf⟩, ext x, exact sub_add_cancel (f x) (algebra_map A B x) } end end to_square_zero
61dafa8ccc5cd7e23e20ac34bce8b2579fa69542
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/number_theory/ADE_inequality.lean
13906a3a352d9bc318122bb66d88e0aa20e2dd21
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,606
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.multiset.sort import data.pnat.basic import data.rat.order import tactic.norm_num import tactic.field_simp import tactic.interval_cases /-! # The inequality `p⁻¹ + q⁻¹ + r⁻¹ > 1` In this file we classify solutions to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`, for positive natural numbers `p`, `q`, and `r`. The solutions are exactly of the form. * `A' q r := {1,q,r}` * `D' r := {2,2,r}` * `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}` This inequality shows up in Lie theory, in the classification of Dynkin diagrams, root systems, and semisimple Lie algebras. ## Main declarations * `pqr.A' q r`, the multiset `{1,q,r}` * `pqr.D' r`, the multiset `{2,2,r}` * `pqr.E6`, the multiset `{2,3,3}` * `pqr.E7`, the multiset `{2,3,4}` * `pqr.E8`, the multiset `{2,3,5}` * `pqr.classification`, the classification of solutions to `p⁻¹ + q⁻¹ + r⁻¹ > 1` -/ namespace ADE_inequality open multiset /-- `A' q r := {1,q,r}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. -/ def A' (q r : ℕ+) : multiset ℕ+ := {1,q,r} /-- `A r := {1,1,r}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. These solutions are related to the Dynkin diagrams $A_r$. -/ def A (r : ℕ+) : multiset ℕ+ := A' 1 r /-- `D' r := {2,2,r}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. These solutions are related to the Dynkin diagrams $D_{r+2}$. -/ def D' (r : ℕ+) : multiset ℕ+ := {2,2,r} /-- `E' r := {2,3,r}` is a `multiset ℕ+`. For `r ∈ {3,4,5}` is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. These solutions are related to the Dynkin diagrams $E_{r+3}$. -/ def E' (r : ℕ+) : multiset ℕ+ := {2,3,r} /-- `E6 := {2,3,3}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. This solution is related to the Dynkin diagrams $E_6$. -/ def E6 : multiset ℕ+ := E' 3 /-- `E7 := {2,3,4}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. This solution is related to the Dynkin diagrams $E_7$. -/ def E7 : multiset ℕ+ := E' 4 /-- `E8 := {2,3,5}` is a `multiset ℕ+` that is a solution to the inequality `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1`. This solution is related to the Dynkin diagrams $E_8$. -/ def E8 : multiset ℕ+ := E' 5 /-- `sum_inv pqr` for a `pqr : multiset ℕ+` is the sum of the inverses of the elements of `pqr`, as rational number. The intended argument is a multiset `{p,q,r}` of cardinality `3`. -/ def sum_inv (pqr : multiset ℕ+) : ℚ := multiset.sum $ pqr.map $ λ x, x⁻¹ lemma sum_inv_pqr (p q r : ℕ+) : sum_inv {p,q,r} = p⁻¹ + q⁻¹ + r⁻¹ := by simp only [sum_inv, coe_coe, add_zero, insert_eq_cons, add_assoc, map_cons, sum_cons, map_singleton, sum_singleton] /-- A multiset `pqr` of positive natural numbers is `admissible` if it is equal to `A' q r`, or `D' r`, or one of `E6`, `E7`, or `E8`. -/ def admissible (pqr : multiset ℕ+) : Prop := (∃ q r, A' q r = pqr) ∨ (∃ r, D' r = pqr) ∨ (E' 3 = pqr ∨ E' 4 = pqr ∨ E' 5 = pqr) lemma admissible_A' (q r : ℕ+) : admissible (A' q r) := or.inl ⟨q, r, rfl⟩ lemma admissible_D' (n : ℕ+) : admissible (D' n) := or.inr $ or.inl ⟨n, rfl⟩ lemma admissible_E'3 : admissible (E' 3) := or.inr $ or.inr $ or.inl rfl lemma admissible_E'4 : admissible (E' 4) := or.inr $ or.inr $ or.inr $ or.inl rfl lemma admissible_E'5 : admissible (E' 5) := or.inr $ or.inr $ or.inr $ or.inr rfl lemma admissible_E6 : admissible (E6) := admissible_E'3 lemma admissible_E7 : admissible (E7) := admissible_E'4 lemma admissible_E8 : admissible (E8) := admissible_E'5 lemma admissible.one_lt_sum_inv {pqr : multiset ℕ+} : admissible pqr → 1 < sum_inv pqr := begin rw [admissible], rintro (⟨p', q', H⟩|⟨n, H⟩|H|H|H), { rw [← H, A', sum_inv_pqr, add_assoc], simp only [lt_add_iff_pos_right, pnat.one_coe, inv_one, nat.cast_one, coe_coe], apply add_pos; simp only [pnat.pos, nat.cast_pos, inv_pos] }, { rw [← H, D', sum_inv_pqr], simp only [lt_add_iff_pos_right, pnat.one_coe, inv_one, nat.cast_one, coe_coe, pnat.coe_bit0, nat.cast_bit0], norm_num }, all_goals { rw [← H, E', sum_inv_pqr], norm_num } end lemma lt_three {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r) (H : 1 < sum_inv {p, q, r}) : p < 3 := begin have h3 : (0:ℚ) < 3, by norm_num, contrapose! H, rw sum_inv_pqr, have h3q := H.trans hpq, have h3r := h3q.trans hqr, calc (p⁻¹ + q⁻¹ + r⁻¹ : ℚ) ≤ 3⁻¹ + 3⁻¹ + 3⁻¹ : add_le_add (add_le_add _ _) _ ... = 1 : by norm_num, all_goals { rw inv_le_inv _ h3; [assumption_mod_cast, norm_num] } end lemma lt_four {q r : ℕ+} (hqr : q ≤ r) (H : 1 < sum_inv {2, q, r}) : q < 4 := begin have h4 : (0:ℚ) < 4, by norm_num, contrapose! H, rw sum_inv_pqr, have h4r := H.trans hqr, simp only [pnat.coe_bit0, nat.cast_bit0, pnat.one_coe, nat.cast_one, coe_coe], calc (2⁻¹ + q⁻¹ + r⁻¹ : ℚ) ≤ 2⁻¹ + 4⁻¹ + 4⁻¹ : add_le_add (add_le_add le_rfl _) _ ... = 1 : by norm_num, all_goals { rw inv_le_inv _ h4; [assumption_mod_cast, norm_num] } end lemma lt_six {r : ℕ+} (H : 1 < sum_inv {2, 3, r}) : r < 6 := begin have h6 : (0:ℚ) < 6, by norm_num, contrapose! H, rw sum_inv_pqr, simp only [pnat.coe_bit0, nat.cast_bit0, pnat.one_coe, nat.cast_bit1, nat.cast_one, pnat.coe_bit1, coe_coe], calc (2⁻¹ + 3⁻¹ + r⁻¹ : ℚ) ≤ 2⁻¹ + 3⁻¹ + 6⁻¹ : add_le_add (add_le_add le_rfl le_rfl) _ ... = 1 : by norm_num, rw inv_le_inv _ h6; [assumption_mod_cast, norm_num] end lemma admissible_of_one_lt_sum_inv_aux' {p q r : ℕ+} (hpq : p ≤ q) (hqr : q ≤ r) (H : 1 < sum_inv {p,q,r}) : admissible {p,q,r} := begin have hp3 : p < 3 := lt_three hpq hqr H, interval_cases p, { exact admissible_A' q r }, have hq4 : q < 4 := lt_four hqr H, interval_cases q, { exact admissible_D' r }, have hr6 : r < 6 := lt_six H, interval_cases r, { exact admissible_E6 }, { exact admissible_E7 }, { exact admissible_E8 } end lemma admissible_of_one_lt_sum_inv_aux : ∀ {pqr : list ℕ+} (hs : pqr.sorted (≤)) (hl : pqr.length = 3) (H : 1 < sum_inv pqr), admissible pqr | [p,q,r] hs hl H := begin obtain ⟨⟨hpq, -⟩, hqr⟩ : (p ≤ q ∧ p ≤ r) ∧ q ≤ r, simpa using hs, exact admissible_of_one_lt_sum_inv_aux' hpq hqr H, end lemma admissible_of_one_lt_sum_inv {p q r : ℕ+} (H : 1 < sum_inv {p,q,r}) : admissible {p,q,r} := begin simp only [admissible], let S := sort ((≤) : ℕ+ → ℕ+ → Prop) {p,q,r}, have hS : S.sorted (≤) := sort_sorted _ _, have hpqr : ({p,q,r} : multiset ℕ+) = S := (sort_eq has_le.le {p, q, r}).symm, simp only [hpqr] at *, apply admissible_of_one_lt_sum_inv_aux hS _ H, simp only [S, length_sort], dec_trivial, end /-- A multiset `{p,q,r}` of positive natural numbers is a solution to `(p⁻¹ + q⁻¹ + r⁻¹ : ℚ) > 1` if and only if it is `admissible` which means it is one of: * `A' q r := {1,q,r}` * `D' r := {2,2,r}` * `E6 := {2,3,3}`, or `E7 := {2,3,4}`, or `E8 := {2,3,5}` -/ lemma classification (p q r : ℕ+) : 1 < sum_inv {p,q,r} ↔ admissible {p,q,r} := ⟨admissible_of_one_lt_sum_inv, admissible.one_lt_sum_inv⟩ end ADE_inequality
e7f4f908b9706d0f4e10af0106bac0f7fb0163bb
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/complex/basic.lean
b7f9f9f6324fe1724825668eff450d03098b295a
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
14,449
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.determinant import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `re_clm` * `im_clm` * `of_real_clm` * `conj_cle` They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear isometries in `of_real_li` and `conj_lie`. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex open_locale complex_conjugate topological_space instance : has_norm ℂ := ⟨abs⟩ @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl instance : normed_add_comm_group ℂ := normed_add_comm_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field, .. complex.normed_add_comm_group } instance : densely_normed_field ℂ := { lt_norm_lt := λ r₁ r₂ h₀ hr, let ⟨x, h⟩ := normed_field.exists_lt_norm_lt ℝ h₀ hr in have this : ∥(∥x∥ : ℂ)∥ = ∥(∥x∥)∥, by simp only [norm_eq_abs, abs_of_real, real.norm_eq_abs], ⟨∥x∥, by rwa [this, norm_norm]⟩ } instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ := { norm_smul_le := λ r x, begin rw [norm_eq_abs, norm_eq_abs, ←algebra_map_smul ℝ r x, algebra.smul_def, abs_mul, ←norm_algebra_map' ℝ r, coe_algebra_map, abs_of_real], refl, end, to_algebra := complex.algebra } variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E] /-- The module structure from `module.complex_to_real` is a normed space. -/ @[priority 900] -- see Note [lower instance priority] instance _root_.normed_space.complex_to_real : normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl lemma dist_eq_re_im (z w : ℂ) : dist z w = real.sqrt ((z.re - w.re) ^ 2 + (z.im - w.im) ^ 2) := by { rw [sq, sq], refl } @[simp] lemma dist_mk (x₁ y₁ x₂ y₂ : ℝ) : dist (mk x₁ y₁) (mk x₂ y₂) = real.sqrt ((x₁ - x₂) ^ 2 + (y₁ - y₂) ^ 2) := dist_eq_re_im _ _ lemma dist_of_re_eq {z w : ℂ} (h : z.re = w.re) : dist z w = dist z.im w.im := by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, zero_add, real.sqrt_sq_eq_abs, real.dist_eq] lemma nndist_of_re_eq {z w : ℂ} (h : z.re = w.re) : nndist z w = nndist z.im w.im := nnreal.eq $ dist_of_re_eq h lemma edist_of_re_eq {z w : ℂ} (h : z.re = w.re) : edist z w = edist z.im w.im := by rw [edist_nndist, edist_nndist, nndist_of_re_eq h] lemma dist_of_im_eq {z w : ℂ} (h : z.im = w.im) : dist z w = dist z.re w.re := by rw [dist_eq_re_im, h, sub_self, zero_pow two_pos, add_zero, real.sqrt_sq_eq_abs, real.dist_eq] lemma nndist_of_im_eq {z w : ℂ} (h : z.im = w.im) : nndist z w = nndist z.re w.re := nnreal.eq $ dist_of_im_eq h lemma edist_of_im_eq {z w : ℂ} (h : z.im = w.im) : edist z w = edist z.re w.re := by rw [edist_nndist, edist_nndist, nndist_of_im_eq h] lemma dist_conj_self (z : ℂ) : dist (conj z) z = 2 * |z.im| := by rw [dist_of_re_eq (conj_re z), conj_im, dist_comm, real.dist_eq, sub_neg_eq_add, ← two_mul, _root_.abs_mul, abs_of_pos (@two_pos ℝ _ _)] lemma nndist_conj_self (z : ℂ) : nndist (conj z) z = 2 * real.nnabs z.im := nnreal.eq $ by rw [← dist_nndist, nnreal.coe_mul, nnreal.coe_two, real.coe_nnabs, dist_conj_self] lemma dist_self_conj (z : ℂ) : dist z (conj z) = 2 * |z.im| := by rw [dist_comm, dist_conj_self] lemma nndist_self_conj (z : ℂ) : nndist z (conj z) = 2 * real.nnabs z.im := by rw [nndist_comm, nndist_conj_self] @[simp] lemma comap_abs_nhds_zero : filter.comap abs (𝓝 0) = 𝓝 0 := comap_norm_nhds_zero @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = |(r : ℝ)| := by { rw ← of_real_rat_cast, exact norm_real _ } @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = |n| := by simp [← rat.cast_coe_int] {single_pass := tt} lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by simp [hn] @[continuity] lemma continuous_abs : continuous abs := continuous_norm @[continuity] lemma continuous_norm_sq : continuous norm_sq := by simpa [← norm_sq_eq_abs] using continuous_abs.pow 2 @[simp, norm_cast] lemma nnnorm_real (r : ℝ) : ∥(r : ℂ)∥₊ = ∥r∥₊ := subtype.ext $ norm_real r @[simp, norm_cast] lemma nnnorm_nat (n : ℕ) : ∥(n : ℂ)∥₊ = n := subtype.ext $ by simp @[simp, norm_cast] lemma nnnorm_int (n : ℤ) : ∥(n : ℂ)∥₊ = ∥n∥₊ := subtype.ext $ by simp only [coe_nnnorm, norm_int, int.norm_eq_abs] lemma nnnorm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) : ∥ζ∥₊ = 1 := begin refine (@pow_left_inj nnreal _ _ _ _ zero_le' zero_le' hn.bot_lt).mp _, rw [←nnnorm_pow, h, nnnorm_one, one_pow], end lemma norm_eq_one_of_pow_eq_one {ζ : ℂ} {n : ℕ} (h : ζ ^ n = 1) (hn : n ≠ 0) : ∥ζ∥ = 1 := congr_arg coe (nnnorm_eq_one_of_pow_eq_one h hn) /-- The `abs` function on `ℂ` is proper. -/ lemma tendsto_abs_cocompact_at_top : filter.tendsto abs (filter.cocompact ℂ) filter.at_top := tendsto_norm_cocompact_at_top /-- The `norm_sq` function on `ℂ` is proper. -/ lemma tendsto_norm_sq_cocompact_at_top : filter.tendsto norm_sq (filter.cocompact ℂ) filter.at_top := by simpa [mul_self_abs] using tendsto_abs_cocompact_at_top.at_top_mul_at_top tendsto_abs_cocompact_at_top open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := re_clm.continuous @[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl @[simp] lemma re_clm_norm : ∥re_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥re_clm 1∥ : by simp ... ≤ ∥re_clm∥ : unit_le_op_norm _ _ (by simp) @[simp] lemma re_clm_nnnorm : ∥re_clm∥₊ = 1 := subtype.ext re_clm_norm /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := im_clm.continuous @[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl @[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl @[simp] lemma im_clm_norm : ∥im_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥im_clm I∥ : by simp ... ≤ ∥im_clm∥ : unit_le_op_norm _ _ (by simp) @[simp] lemma im_clm_nnnorm : ∥im_clm∥₊ = 1 := subtype.ext im_clm_norm lemma restrict_scalars_one_smul_right' (x : E) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] E) = re_clm.smul_right x + I • im_clm.smul_right x := by { ext ⟨a, b⟩, simp [mk_eq_add_mul_I, add_smul, mul_smul, smul_comm I] } lemma restrict_scalars_one_smul_right (x : ℂ) : continuous_linear_map.restrict_scalars ℝ ((1 : ℂ →L[ℂ] ℂ).smul_right x : ℂ →L[ℂ] ℂ) = x • 1 := by { ext1 z, dsimp, apply mul_comm } /-- The complex-conjugation function from `ℂ` to itself is an isometric linear equivalence. -/ def conj_lie : ℂ ≃ₗᵢ[ℝ] ℂ := ⟨conj_ae.to_linear_equiv, abs_conj⟩ @[simp] lemma conj_lie_apply (z : ℂ) : conj_lie z = conj z := rfl @[simp] lemma conj_lie_symm : conj_lie.symm = conj_lie := rfl lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_lie.isometry @[simp] lemma dist_conj_conj (z w : ℂ) : dist (conj z) (conj w) = dist z w := isometry_conj.dist_eq z w @[simp] lemma nndist_conj_conj (z w : ℂ) : nndist (conj z) (conj w) = nndist z w := isometry_conj.nndist_eq z w lemma dist_conj_comm (z w : ℂ) : dist (conj z) w = dist z (conj w) := by rw [← dist_conj_conj, conj_conj] lemma nndist_conj_comm (z w : ℂ) : nndist (conj z) w = nndist z (conj w) := subtype.ext $ dist_conj_comm _ _ /-- The determinant of `conj_lie`, as a linear map. -/ @[simp] lemma det_conj_lie : (conj_lie.to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = -1 := det_conj_ae /-- The determinant of `conj_lie`, as a linear equiv. -/ @[simp] lemma linear_equiv_det_conj_lie : conj_lie.to_linear_equiv.det = -1 := linear_equiv_det_conj_ae instance : has_continuous_star ℂ := ⟨conj_lie.continuous⟩ @[continuity] lemma continuous_conj : continuous (conj : ℂ → ℂ) := continuous_star /-- Continuous linear equiv version of the conj function, from `ℂ` to `ℂ`. -/ def conj_cle : ℂ ≃L[ℝ] ℂ := conj_lie @[simp] lemma conj_cle_coe : conj_cle.to_linear_equiv = conj_ae.to_linear_equiv := rfl @[simp] lemma conj_cle_apply (z : ℂ) : conj_cle z = conj z := rfl @[simp] lemma conj_cle_norm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥ = 1 := conj_lie.to_linear_isometry.norm_to_continuous_linear_map @[simp] lemma conj_cle_nnorm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥₊ = 1 := subtype.ext conj_cle_norm /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_am.to_linear_map, norm_real⟩ lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := of_real_li.continuous /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map @[simp] lemma of_real_clm_coe : (of_real_clm : ℝ →ₗ[ℝ] ℂ) = of_real_am.to_linear_map := rfl @[simp] lemma of_real_clm_apply (x : ℝ) : of_real_clm x = x := rfl @[simp] lemma of_real_clm_norm : ∥of_real_clm∥ = 1 := of_real_li.norm_to_continuous_linear_map @[simp] lemma of_real_clm_nnnorm : ∥of_real_clm∥₊ = 1 := subtype.ext $ of_real_clm_norm noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, rfl, conj_im_ax := λ z, rfl, conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } lemma _root_.is_R_or_C.re_eq_complex_re : ⇑(is_R_or_C.re : ℂ →+ ℝ) = complex.re := rfl lemma _root_.is_R_or_C.im_eq_complex_im : ⇑(is_R_or_C.im : ℂ →+ ℝ) = complex.im := rfl section variables {α β γ : Type*} [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] /-- The natural `add_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom : ℂ ≃+ ℝ × ℝ := { map_add' := by simp, .. equiv_real_prod } /-- The natural `linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prod_add_hom_lm : ℂ ≃ₗ[ℝ] ℝ × ℝ := { map_smul' := by simp [equiv_real_prod_add_hom], .. equiv_real_prod_add_hom } /-- The natural `continuous_linear_equiv` from `ℂ` to `ℝ × ℝ`. -/ @[simps apply symm_apply_re symm_apply_im { simp_rhs := tt }] def equiv_real_prodₗ : ℂ ≃L[ℝ] ℝ × ℝ := equiv_real_prod_add_hom_lm.to_continuous_linear_equiv end lemma has_sum_iff {α} (f : α → ℂ) (c : ℂ) : has_sum f c ↔ has_sum (λ x, (f x).re) c.re ∧ has_sum (λ x, (f x).im) c.im := begin -- For some reason, `continuous_linear_map.has_sum` is orders of magnitude faster than -- `has_sum.mapL` here: refine ⟨λ h, ⟨re_clm.has_sum h, im_clm.has_sum h⟩, _⟩, rintro ⟨h₁, h₂⟩, convert (h₁.prod_mk h₂).mapL equiv_real_prodₗ.symm.to_continuous_linear_map, { ext x; refl }, { cases c, refl } end end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
4ea252e109f417be9a966f6a23f4031389fd2be4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/group/defs.lean
ce364997528562043396f19402145f00c8b85ba4
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
10,982
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Simon Hudon, Mario Carneiro -/ import algebra.group.to_additive import tactic.basic /-! # Typeclasses for (semi)groups and monoid In this file we define typeclasses for algebraic structures with one binary operation. The classes are named `(add_)?(comm_)?(semigroup|monoid|group)`, where `add_` means that the class uses additive notation and `comm_` means that the class assumes that the binary operation is commutative. The file does not contain any lemmas except for * axioms of typeclasses restated in the root namespace; * lemmas required for instances. For basic lemmas about these classes see `algebra.group.basic`. -/ set_option default_priority 100 set_option old_structure_cmd true universe u /- Additive "sister" structures. Example, add_semigroup mirrors semigroup. These structures exist just to help automation. In an alternative design, we could have the binary operation as an extra argument for semigroup, monoid, group, etc. However, the lemmas would be hard to index since they would not contain any constant. For example, mul_assoc would be lemma mul_assoc {α : Type u} {op : α → α → α} [semigroup α op] : ∀ a b c : α, op (op a b) c = op a (op b c) := semigroup.mul_assoc The simplifier cannot effectively use this lemma since the pattern for the left-hand-side would be ?op (?op ?a ?b) ?c Remark: we use a tactic for transporting theorems from the multiplicative fragment to the additive one. -/ /-- A semigroup is a type with an associative `(*)`. -/ @[protect_proj, ancestor has_mul] class semigroup (G : Type u) extends has_mul G := (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) /-- An additive semigroup is a type with an associative `(+)`. -/ @[protect_proj, ancestor has_add] class add_semigroup (G : Type u) extends has_add G := (add_assoc : ∀ a b c : G, a + b + c = a + (b + c)) attribute [to_additive add_semigroup] semigroup section semigroup variables {G : Type u} [semigroup G] @[no_rsimp, to_additive] lemma mul_assoc : ∀ a b c : G, a * b * c = a * (b * c) := semigroup.mul_assoc attribute [no_rsimp] add_assoc -- TODO(Mario): find out why this isn't copying @[to_additive] instance semigroup.to_is_associative : is_associative G (*) := ⟨mul_assoc⟩ end semigroup /-- A commutative semigroup is a type with an associative commutative `(*)`. -/ @[protect_proj, ancestor semigroup] class comm_semigroup (G : Type u) extends semigroup G := (mul_comm : ∀ a b : G, a * b = b * a) /-- A commutative additive semigroup is a type with an associative commutative `(+)`. -/ @[protect_proj, ancestor add_semigroup] class add_comm_semigroup (G : Type u) extends add_semigroup G := (add_comm : ∀ a b : G, a + b = b + a) attribute [to_additive add_comm_semigroup] comm_semigroup section comm_semigroup variables {G : Type u} [comm_semigroup G] @[no_rsimp, to_additive] lemma mul_comm : ∀ a b : G, a * b = b * a := comm_semigroup.mul_comm attribute [no_rsimp] add_comm @[to_additive] instance comm_semigroup.to_is_commutative : is_commutative G (*) := ⟨mul_comm⟩ end comm_semigroup /-- A `left_cancel_semigroup` is a semigroup such that `a * b = a * c` implies `b = c`. -/ @[protect_proj, ancestor semigroup] class left_cancel_semigroup (G : Type u) extends semigroup G := (mul_left_cancel : ∀ a b c : G, a * b = a * c → b = c) /-- An `add_left_cancel_semigroup` is an additive semigroup such that `a + b = a + c` implies `b = c`. -/ @[protect_proj, ancestor add_semigroup] class add_left_cancel_semigroup (G : Type u) extends add_semigroup G := (add_left_cancel : ∀ a b c : G, a + b = a + c → b = c) attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup section left_cancel_semigroup variables {G : Type u} [left_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_left_cancel : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c @[to_additive] lemma mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[to_additive] theorem mul_right_injective (a : G) : function.injective ((*) a) := λ b c, mul_left_cancel @[simp, to_additive] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ end left_cancel_semigroup /-- A `right_cancel_semigroup` is a semigroup such that `a * b = c * b` implies `a = c`. -/ @[protect_proj, ancestor semigroup] class right_cancel_semigroup (G : Type u) extends semigroup G := (mul_right_cancel : ∀ a b c : G, a * b = c * b → a = c) /-- An `add_right_cancel_semigroup` is an additive semigroup such that `a + b = c + b` implies `a = c`. -/ @[protect_proj, ancestor add_semigroup] class add_right_cancel_semigroup (G : Type u) extends add_semigroup G := (add_right_cancel : ∀ a b c : G, a + b = c + b → a = c) attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup section right_cancel_semigroup variables {G : Type u} [right_cancel_semigroup G] {a b c : G} @[to_additive] lemma mul_right_cancel : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c @[to_additive] lemma mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ @[to_additive] theorem mul_left_injective (a : G) : function.injective (λ x, x * a) := λ b c, mul_right_cancel @[simp, to_additive] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ end right_cancel_semigroup /-- A `monoid` is a `semigroup` with an element `1` such that `1 * a = a * 1 = a`. -/ @[ancestor semigroup has_one] class monoid (M : Type u) extends semigroup M, has_one M := (one_mul : ∀ a : M, 1 * a = a) (mul_one : ∀ a : M, a * 1 = a) /-- An `add_monoid` is an `add_semigroup` with an element `0` such that `0 + a = a + 0 = a`. -/ @[ancestor add_semigroup has_zero] class add_monoid (M : Type u) extends add_semigroup M, has_zero M := (zero_add : ∀ a : M, 0 + a = a) (add_zero : ∀ a : M, a + 0 = a) attribute [to_additive add_monoid] monoid section monoid variables {M : Type u} [monoid M] @[ematch, simp, to_additive] lemma one_mul : ∀ a : M, 1 * a = a := monoid.one_mul @[ematch, simp, to_additive] lemma mul_one : ∀ a : M, a * 1 = a := monoid.mul_one attribute [ematch] add_zero zero_add -- TODO(Mario): Make to_additive transfer this @[to_additive add_monoid_to_is_left_id] instance monoid_to_is_left_id : is_left_id M (*) 1 := ⟨ monoid.one_mul ⟩ @[to_additive add_monoid_to_is_right_id] instance monoid_to_is_right_id : is_right_id M (*) 1 := ⟨ monoid.mul_one ⟩ @[to_additive] lemma left_inv_eq_right_inv {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] end monoid /-- A commutative monoid is a monoid with commutative `(*)`. -/ @[protect_proj, ancestor monoid comm_semigroup] class comm_monoid (M : Type u) extends monoid M, comm_semigroup M /-- An additive commutative monoid is an additive monoid with commutative `(+)`. -/ @[protect_proj, ancestor add_monoid add_comm_semigroup] class add_comm_monoid (M : Type u) extends add_monoid M, add_comm_semigroup M attribute [to_additive add_comm_monoid] comm_monoid /-- A monoid in which multiplication is left-cancellative. -/ @[protect_proj, ancestor left_cancel_semigroup monoid] class left_cancel_monoid (M : Type u) extends left_cancel_semigroup M, monoid M /-- An additive monoid in which addition is left-cancellative. Main examples are `ℕ` and groups. This is the right typeclass for many sum lemmas, as having a zero is useful to define the sum over the empty set, so `add_left_cancel_semigroup` is not enough. -/ @[protect_proj, ancestor add_left_cancel_semigroup add_monoid] class add_left_cancel_monoid (M : Type u) extends add_left_cancel_semigroup M, add_monoid M -- TODO: I found 1 (one) lemma assuming `[add_left_cancel_monoid]`. -- Should we port more lemmas to this typeclass? attribute [to_additive add_left_cancel_monoid] left_cancel_monoid /-- A `group` is a `monoid` with an operation `⁻¹` satisfying `a⁻¹ * a = 1`. -/ @[protect_proj, ancestor monoid has_inv] class group (α : Type u) extends monoid α, has_inv α := (mul_left_inv : ∀ a : α, a⁻¹ * a = 1) /-- An `add_group` is an `add_monoid` with a unary `-` satisfying `-a + a = 0`. -/ @[protect_proj, ancestor add_monoid has_neg] class add_group (α : Type u) extends add_monoid α, has_neg α := (add_left_neg : ∀ a : α, -a + a = 0) attribute [to_additive add_group] group section group variables {G : Type u} [group G] {a b c : G} @[simp, to_additive] lemma mul_left_inv : ∀ a : G, a⁻¹ * a = 1 := group.mul_left_inv @[to_additive] lemma inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp, to_additive] lemma inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp, to_additive] lemma inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp, to_additive] lemma inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp, to_additive] lemma mul_right_inv (a : G) : a * a⁻¹ = 1 := have a⁻¹⁻¹ * a⁻¹ = 1 := mul_left_inv a⁻¹, by rwa [inv_inv] at this @[to_additive] lemma mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp, to_additive] lemma mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] @[to_additive to_left_cancel_add_semigroup] instance group.to_left_cancel_semigroup : left_cancel_semigroup G := { mul_left_cancel := λ a b c h, by rw [← inv_mul_cancel_left a b, h, inv_mul_cancel_left], ..‹group G› } @[to_additive to_right_cancel_add_semigroup] instance group.to_right_cancel_semigroup : right_cancel_semigroup G := { mul_right_cancel := λ a b c h, by rw [← mul_inv_cancel_right a b, h, mul_inv_cancel_right], ..‹group G› } end group section add_group variables {G : Type u} [add_group G] @[reducible] protected def algebra.sub (a b : G) : G := a + -b instance add_group_has_sub : has_sub G := ⟨algebra.sub⟩ lemma sub_eq_add_neg (a b : G) : a - b = a + -b := rfl instance add_group.to_add_left_cancel_monoid : add_left_cancel_monoid G := { ..‹add_group G›, .. add_group.to_left_cancel_add_semigroup } end add_group /-- A commutative group is a group with commutative `(*)`. -/ @[protect_proj, ancestor group comm_monoid] class comm_group (G : Type u) extends group G, comm_monoid G /-- An additive commutative group is an additive group with commutative `(+)`. -/ @[protect_proj, ancestor add_group add_comm_monoid] class add_comm_group (G : Type u) extends add_group G, add_comm_monoid G attribute [to_additive add_comm_group] comm_group attribute [instance, priority 300] add_comm_group.to_add_comm_monoid
0b69381cef373909476d6b4a44775c63c296d62c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/scale_roots.lean
30fde081ee111106419c804b43eff7d66b289361
[ "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
5,316
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.polynomial.basic import ring_theory.non_zero_divisors /-! # Scaling the roots of a polynomial This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it. -/ section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open polynomial open_locale big_operators /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := ∑ i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : ℕ) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := by simp [scale_roots, coeff_monomial] {contextual := tt} lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p ≠ 0) (s : R) : scale_roots p s ≠ 0 := begin intro h, have : p.coeff p.nat_degree ≠ 0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R → ℕ → R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≤ p.support := by { intro, simpa using left_ne_zero_of_mul } lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [coeff_scale_roots, polynomial.mem_support_iff], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_eval₂_eq_zero {p : polynomial S} (f : S →+* R) {r : R} {s : S} (hr : eval₂ f r p = 0) : eval₂ f (f s * r) (scale_roots p s) = 0 := calc eval₂ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : by simp [eval₂_eq_sum, sum_def] ... = p.support.sum (λ i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (λ i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (λ (i : ℕ), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (λ i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (λ (i : ℕ), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (λ i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel], exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (λ (i : ℕ), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * eval₂ f r p : by { simp [eval₂_eq_sum, sum_def] } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero (algebra_map S R) hr lemma scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero {p : polynomial A} {f : A →+* K} (hf : function.injective f) {r s : A} (hr : eval₂ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : eval₂ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact map_ne_zero_of_mem_non_zero_divisors hf hs end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_eval₂_eq_zero_of_eval₂_div_eq_zero inj hr hs end scale_roots
99142ce49dfcb7b868526d921e64fa52704c703e
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/library/init/meta/congr_tactic.lean
96b6e7e82f30e3e397874c12f9426a24bcef2cc4
[ "Apache-2.0" ]
permissive
HGldJ1966/lean
e7f0068f8a69fde3593b77d8a44609ae446d7738
049d940167c419cd5935d12b459c0695d8615ae9
refs/heads/master
1,611,340,395,700
1,503,103,829,000
1,503,103,829,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,894
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam -/ prelude import init.meta.tactic init.meta.congr_lemma init.meta.relation_tactics init.function namespace tactic meta def apply_congr_core (clemma : congr_lemma) : tactic unit := do assert `H_congr_lemma clemma.type, exact clemma.proof, get_local `H_congr_lemma >>= apply, all_goals $ get_local `H_congr_lemma >>= clear meta def apply_eq_congr_core (tgt : expr) : tactic unit := do (lhs, rhs) ← match_eq tgt, guard lhs.is_app, clemma ← mk_specialized_congr_lemma lhs, apply_congr_core clemma meta def apply_heq_congr_core (tgt : expr) : tactic unit := do (lhs, rhs) ← (match_eq tgt <|> do (α, lhs, β, rhs) ← match_heq tgt, return (lhs, rhs)), guard lhs.is_app, clemma ← mk_hcongr_lemma lhs.get_app_fn lhs.get_app_num_args, apply_congr_core clemma meta def apply_rel_iff_congr_core (tgt : expr) : tactic unit := do (lhs, rhs) ← match_iff tgt, guard lhs.is_app, clemma ← mk_rel_iff_congr_lemma lhs.get_app_fn, apply_congr_core clemma meta def apply_rel_eq_congr_core (tgt : expr) : tactic unit := do (lhs, rhs) ← match_eq tgt, guard lhs.is_app, clemma ← mk_rel_eq_congr_lemma lhs.get_app_fn, apply_congr_core clemma meta def congr_core : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core tgt <|> fail "congr tactic failed" meta def rel_congr_core : tactic unit := do tgt ← target, apply_rel_iff_congr_core tgt <|> apply_rel_eq_congr_core tgt <|> fail "rel_congr tactic failed" meta def congr : tactic unit := do focus1 (try assumption >> congr_core >> all_goals (try reflexivity >> try congr)) meta def rel_congr : tactic unit := do focus1 (try assumption >> rel_congr_core >> all_goals (try reflexivity)) end tactic
f73385e0e0db33a68944bfb1cbaabb2ec00f8479
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/bquant.lean
78bddacc09b0dd11741357916c1a7e700a55bc91
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
252
lean
import data.nat.bquant open nat example : is_true (∀ x, x ≤ 4 → x ≠ 6) := trivial example : is_false (∀ x, x ≤ 5 → ∀ y, y < x → y * y ≠ x) := trivial example : is_true (∀ x, x < 5 → ∃ y, y ≤ x + 5 ∧ y = 2*x) := trivial
9caa0b7ca6dfc8e501b435d468be7a7d15ddf42b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/replacer.lean
f5c16ce185cff607bef62c72fa8ad864268aba5c
[ "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
5,822
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.core /-! # `def_replacer` A mechanism for defining tactics for use in auto params, whose meaning is defined incrementally through attributes. -/ namespace tactic meta def replacer_core {α : Type} [reflected _ α] (ntac : name) (eval : ∀ β [reflected _ β], expr → tactic β) : list name → tactic α | [] := fail ("no implementation defined for " ++ to_string ntac) | (n::ns) := do d ← get_decl n, let t := d.type, tac ← do { mk_const n >>= eval (tactic α) } <|> do { tac ← mk_const n >>= eval (tactic α → tactic α), return (tac (replacer_core ns)) } <|> do { tac ← mk_const n >>= eval (option (tactic α) → tactic α), return (tac (guard (ns ≠ []) >> some (replacer_core ns))) }, tac meta def replacer (ntac : name) {α : Type} [reflected _ α] (F : Type → Type) (eF : ∀ β, reflected _ β → reflected _ (F β)) (R : ∀ β, F β → β) : tactic α := attribute.get_instances ntac >>= replacer_core ntac (λ β eβ e, R β <$> @eval_expr' (F β) (eF β eβ) e) meta def mk_replacer₁ : expr → nat → expr × expr | (expr.pi n bi d b) i := let (e₁, e₂) := mk_replacer₁ b (i+1) in (expr.pi n bi d e₁, (`(expr.pi n bi d) : expr) e₂) | _ i := (expr.var i, expr.var 0) meta def mk_replacer₂ (ntac : name) (v : expr × expr) : expr → nat → option expr | (expr.pi n bi d b) i := do b' ← mk_replacer₂ b (i+1), some (expr.lam n bi d b') | `(tactic %%β) i := some $ (expr.const ``replacer []).mk_app [ reflect ntac, β, reflect β, expr.lam `γ binder_info.default `(Type) v.1, expr.lam `γ binder_info.default `(Type) $ expr.lam `eγ binder_info.inst_implicit ((`(reflected Type) : expr) β) v.2, expr.lam `γ binder_info.default `(Type) $ expr.lam `f binder_info.default v.1 $ (list.range i).foldr (λ i e', e' (expr.var (i+2))) (expr.var 0) ] | _ i := none meta def mk_replacer (ntac : name) (e : expr) : tactic expr := mk_replacer₂ ntac (mk_replacer₁ e 0) e 0 meta def valid_types : expr → list expr | (expr.pi n bi d b) := expr.pi n bi d <$> valid_types b | `(tactic %%β) := [`(tactic.{0} %%β), `(tactic.{0} %%β → tactic.{0} %%β), `(option (tactic.{0} %%β) → tactic.{0} %%β)] | _ := [] meta def replacer_attr (ntac : name) : user_attribute := { name := ntac, descr := "Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++ "applied to a definition with the type `tactic unit`, which will be " ++ "called whenever `" ++ to_string ntac ++ "` is called. The definition " ++ "can optionally have an argument of type `tactic unit` or " ++ "`option (tactic unit)` which refers to the previous definition, if any.", after_set := some $ λ n _ _, do d ← get_decl n, base ← get_decl ntac, guardb ((valid_types base.type).any (=ₐ d.type)) <|> fail format!"incorrect type for @[{ntac}]" } /-- Define a new replaceable tactic. -/ meta def def_replacer (ntac : name) (ty : expr) : tactic unit := let nattr := ntac <.> "attr" in do add_meta_definition nattr [] `(user_attribute) `(replacer_attr %%(reflect ntac)), set_basic_attribute `user_attribute nattr tt, v ← mk_replacer ntac ty, add_meta_definition ntac [] ty v, add_doc_string ntac $ "The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++ "tactic, which means that its meaning is defined by tactics that " ++ "are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++ "It is intended for use with `auto_param`s for structure fields." setup_tactic_parser /-- `def_replacer foo` sets up a stub definition `foo : tactic unit`, which can effectively be defined and re-defined later, by tagging definitions with `@[foo]`. - `@[foo] meta def foo_1 : tactic unit := ...` replaces the current definition of `foo`. - `@[foo] meta def foo_2 (old : tactic unit) : tactic unit := ...` replaces the current definition of `foo`, and provides access to the previous definition via `old`. (The argument can also be an `option (tactic unit)`, which is provided as `none` if this is the first definition tagged with `@[foo]` since `def_replacer` was invoked.) `def_replacer foo : α → β → tactic γ` allows the specification of a replacer with custom input and output types. In this case all subsequent redefinitions must have the same type, or the type `α → β → tactic γ → tactic γ` or `α → β → option (tactic γ) → tactic γ` analogously to the previous cases. -/ @[user_command] meta def def_replacer_cmd (_ : parse $ tk "def_replacer") : lean.parser unit := do ntac ← ident, ty ← optional (tk ":" *> types.texpr), match ty with | (some p) := do t ← to_expr p, def_replacer ntac t | none := def_replacer ntac `(tactic unit) end add_tactic_doc { name := "def_replacer", category := doc_category.cmd, decl_names := [`tactic.def_replacer_cmd], tags := ["environment", "renaming"] } meta def unprime : name → tactic name | nn@(name.mk_string s n) := let s' := (s.split_on ''').head in if s'.length < s.length then pure (name.mk_string s' n) else fail format!"expecting primed name: {nn}" | n := fail format!"invalid name: {n}" @[user_attribute] meta def replaceable_attr : user_attribute := { name := `replaceable, descr := "make definition replaceable in dependent modules", after_set := some $ λ n' _ _, do { n ← unprime n', d ← get_decl n', «def_replacer» n d.type, (replacer_attr n).set n' () tt } } end tactic
d52b43c4c291e0ae710573ba28540489d7da9a70
618003631150032a5676f229d13a079ac875ff77
/src/topology/metric_space/antilipschitz.lean
96cb9bf115fe0ab74b57daa8820911d885c6d889
[ "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
5,456
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz /-! # Antilipschitz functions We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `nnreal`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ennreal`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal open set /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `K * edist x y ≤ edist (f x) (f y)`. -/ def antilipschitz_with [emetric_space α] [emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) lemma antilipschitz_with_iff_le_mul_dist [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist lemma antilipschitz_with.mul_le_dist [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * dist x y ≤ dist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK, dist_nonneg], rw [nnreal.coe_inv, ← div_eq_inv_mul], apply div_le_of_le_mul (nnreal.coe_pos.2 $ zero_lt_iff_ne_zero.2 hK), exact hf.le_mul_dist x y end namespace antilipschitz_with variables [emetric_space α] [emetric_space β] [emetric_space γ] {K : ℝ≥0} {f : α → β} /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * edist x y ≤ edist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK], rw [ennreal.coe_inv hK, mul_comm, ← ennreal.div_def], apply ennreal.div_le_of_le_mul, rw mul_comm, exact hf x y end protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma uniform_embedding (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := begin refine emetric.uniform_embedding_iff.2 ⟨hf.injective, hfc, λ δ δ0, _⟩, by_cases hK : K = 0, { refine ⟨1, ennreal.zero_lt_one, λ x y _, lt_of_le_of_lt _ δ0⟩, simpa only [hK, ennreal.coe_zero, zero_mul] using hf x y }, { refine ⟨K⁻¹ * δ, _, λ x y hxy, lt_of_le_of_lt (hf x y) _⟩, { exact canonically_ordered_semiring.mul_pos.2 ⟨ennreal.inv_pos.2 ennreal.coe_ne_top, δ0⟩ }, { rw [mul_comm, ← ennreal.div_def] at hxy, have := ennreal.mul_lt_of_lt_div hxy, rwa mul_comm } } end lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] end antilipschitz_with lemma lipschitz_with.to_right_inverse [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y)
3fca447853a8fba49b32b56cb814a6aba9da1642
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Builtin.lean
1c687997ca1515867a0a0f6cc925e1ef9bf8f744
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
2,936
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Daniel Selsam -/ import Mathport.Syntax.Translate.Basic namespace Mathport.Translate open Lean hiding Expr Expr.app Expr.const Expr.sort Level Level.imax Level.max Level.param Command open Lean.Elab (Visibility) open Lean.Elab.Command (CommandElabM liftCoreM) open AST3 partial def trTacticOrList : Spanned Tactic → M (Syntax.Tactic ⊕ Array Syntax.Tactic) | ⟨_, Tactic.«[]» args⟩ => Sum.inr <$> args.mapM fun arg => trTactic arg | tac => Sum.inl <$> trTactic tac def trSeqFocusList : List (Spanned Tactic) → M Syntax.Tactic | [] => `(tactic| skip) | tac::rest => do let tac ← trTacticRaw tac if tac.raw.getKind == blockTransform then match rest with | [] => pure (fillBlockTransform tac #[]) | tac2::rest => do let res ← go rest (← trTactic tac2) pure ⟨tac.raw.modifyArgs (·.push res)⟩ else go rest tac where go : List (Spanned Tactic) → Syntax.Tactic → M Syntax.Tactic | [], lhs => pure lhs | tac::rest, lhs => do match ← trTacticOrList tac with | .inl tac => go rest <|← `(tactic| $lhs <;> $tac) | .inr tacs => go rest <|← `(tactic| $lhs <;> [$tacs;*]) partial def trTactic' : Tactic → M Syntax.Tactic | .block bl => do `(tactic| · ($(← trBlock bl):tacticSeq)) | .by tac => do `(tactic| · $(← trTactic tac):tactic) | .«;» tacs => trSeqFocusList tacs.toList | .«<|>» tacs => do `(tactic| first $[| $(← tacs.mapM fun tac => trTactic tac):tactic]*) | .«[]» _tacs => warn! "unsupported (impossible)" | .exact_shortcut ⟨m, Expr.calc args⟩ => withSpanS m do `(tactic| calc $(← trCalcSteps args)) | .exact_shortcut e => do `(tactic| exact $(← trExpr e)) | .expr e => match e.unparen with | ⟨_, Expr.«`[]» tacs⟩ => trIdTactic ⟨true, none, none, tacs⟩ | e => do let rec head | .const _ _ #[x] | .const ⟨_, x⟩ _ _ | .ident x => some x | .paren e => head e.kind | .app e _ => head e.kind | _ => none let rec fallback := do match ← trExpr e with | `(do $[$els]*) => `(tactic| run_tac $[$els:doSeqItem]*) | stx => `(tactic| run_tac $stx:term) match head e.kind with | none => -- warn! "unsupported non-interactive tactic {repr e}" fallback | some n => match (← get).niTactics.find? n with | some f => try f e.kind catch e => warn! "in {n}: {← e.toMessageData.toString}" | none => warn! "unsupported non-interactive tactic {n}" | fallback | Tactic.interactive n args => do match (← get).tactics.find? n with | some f => try f args catch e => warn! "in {n} {repr args}: {← e.toMessageData.toString}" | none => warn! "unsupported tactic {repr n} {repr args}"
3261cd6841d5217ea87fb76244f362a003b74377
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/lint/type_classes.lean
06ee1e48c3fe52cc433e2b9556d21f38cdca0b25
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
17,285
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority * `has_inhabited_instances` checks that every type has an `inhabited` instance * `impossible_instance` checks that there are no instances which can never apply * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments * `dangerous_instance` checks for instances that generate subproblems with metavariables * `fails_quickly` checks that type class resolution finishes quickly * `has_coe_variable` checks that there is no instance of type `has_coe α t` * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]` * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- Instances that always apply should be applied after instances that only apply in specific cases, see note [lower instance priority] above. Classes that use the `extends` keyword automatically generate instances that always apply. Therefore, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000) using `set_option default_priority 100`. We have to put this option inside a section, so that the default priority is the default 1000 outside the section. -/ library_note "default priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. If this is an automatically generated instance (using the keywords `class` and `extends`), see note [lower instance priority] and see note [default priority] for instructions to change the priority", auto_decls := tt } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← mk_local_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances", errors_found := "TYPES ARE MISSING INHABITED INSTANCES", is_fast := ff } attribute [nolint has_inhabited_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_dep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and therefore can never succeed. Either mark the arguments with square brackets (if it is a class), or don't make it an instance" } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← mk_local_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← mk_local_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← mk_local_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, auto_decls := tt, no_errors_found := "No type-class searches timed out", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search.", is_fast := ff } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_dep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused elsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_dep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em by_contradiction not_not of_not_not of_not_imp not.imp_symm not_imp_comm or_iff_not_imp_left or_iff_not_imp_right not_imp_not not_or_of_imp imp_iff_not_or imp_or_distrib imp_or_distrib' not_imp peirce not_iff_not not_iff_comm not_iff iff_not_comm iff_iff_and_or_not_and_not not_and_not_right not_and_distrib not_and_distrib' or_iff_not_and_not and_iff_not_or_not not_forall not_forall_not forall_or_distrib_left forall_or_distrib_right not_ball private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do reset_instance_cache, mk_meta_var d.type >>= set_goals ∘ pure, args ← intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note function coercions]." }
45d062862f23077372bcb7c3be5ce9e01e48256b
a7dd8b83f933e72c40845fd168dde330f050b1c9
/src/category_theory/instances/CommRing/default.lean
04b4ea738f665e625a2c637fdd6ce04c2e47e501
[ "Apache-2.0" ]
permissive
NeilStrickland/mathlib
10420e92ee5cb7aba1163c9a01dea2f04652ed67
3efbd6f6dff0fb9b0946849b43b39948560a1ffe
refs/heads/master
1,589,043,046,346
1,558,938,706,000
1,558,938,706,000
181,285,984
0
0
Apache-2.0
1,568,941,848,000
1,555,233,833,000
Lean
UTF-8
Lean
false
false
308
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.instances.CommRing.basic import category_theory.instances.CommRing.adjunctions import category_theory.instances.CommRing.colimits
d360b3fedb526cc8d752acd3e3266f2f006fbb6e
94637389e03c919023691dcd05bd4411b1034aa5
/src/profNotes/02_polymorphicTypes.lean
1b5110260c1122aeb5c46eede94fab676db93bb0
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
10,303
lean
namespace hidden /- Inductive, aka algebraic, data types - sum types - product types and case analysis - parametrically polymorphic - sum of product types and destructuring -/ /- SUM TYPES A value of such a type is "one of these OR one of those OR one of something else." SUM means OR in this sense. -/ inductive romanNumeral : Type | I : romanNumeral | II : romanNumeral | III : romanNumeral | IV : romanNumeral | V : romanNumeral -- The empty data type inductive empty : Type -- Look Ma, no terms ("uninhabited") -- Cannot create a value of this type def x : empty := _ /- We can define a function from empty to empty, however, and the reason is a function body is written based on the *assumption* that is has received values of specified argument types. -/ def funny : empty → empty | e := e /- Of course there's no way to actually call this function because there is an argument of type empty doesn't exist. -/ #eval funny _ -- There's no way to fill in _ /- Start of some new stuff. We will cover the following additional material on the empty type at the beginning of our next class. -/ /- Preliminary: the match...with construct. We can pattern match on an inductively defined object (not on functions, for example) using the match ... with ... end construct in Lean. When doing so it is both necessary and it is sufficient to match each possible case that might occur. In the following example, we take a romanNumeral and return tt is it's less than or equal to II, and ff otherwise. The function is define by cases analysis but here we use match ... with ... end to do the case analysis. We introduce match here so we can use it without further explanation in the examples that follow. -/ open romanNumeral def lessOrEqII (n : romanNumeral) : bool := match n with | I := tt | II := tt | _ := ff end /- Even more strangely we can define a function from the empty type to any other type at all. -/ -- example 1 (introduces "match ... with") def weird (e : empty) : nat := match e with -- no cases to consider, so we're done!!! end /- We can even make this function polymorphic so that it returns a value of any given type whatsoever. -/ def strange (α : Type) (e : empty) : α := match e with -- no cases to consider, so we're done!!! end /- These functions look like magic. As long as we can come up with a value of type empty, they can produce values of any type at all! But there is no magic. EXERCISE: Explain why. -/ /- Exercise: Can you maybe just create a function of type, say, ℕ to empty, and use it to get an (e : empty) that you can then use to do magic? EXERCISE: Explain where you get stuck if you try. -/ -- [End of new stuff] /- Having seen the empty type (aka ∅) we now see sum types with one, two, and several constructors. -/ -- unit type (one constructor) inductive unit : Type | star : unit -- bnit is void in C, Java, etc -- bool (two variants) inductive bool : Type | tt : bool | ff -- ": bool" is inferred -- A day type: seven variants inductive day : Type | sun | mon | tue | wed | thu | fri | sat open day /- CASE ANALYSIS We generally define functions that consume values of sum types by case analysis. To know what to return, we need to know what form of value the function got as an argument. -/ def next_day : day → day | sun := mon | mon := tue | tue := wed | wed := thu | thu := fri | fri := sat | sat := sun /- The left side of a case is usually called a pattern. Argument values are matched to patterns in the order in which patterns are using what is called a "unification" algorithm (more later). Function evaluation finds the first pattern in top to bottom order that matches, and return the result obtained by evaluating the expression on the right hand side of that rule (or "equation"). -/ #reduce next_day sun #reduce next_day sat /- The _ character can be used in a pattern to match any value. All functions in Lean must be total. We often use _ to cover cases not covered explicitly by other rules. -/ def isWeekday : day → bool | sat := bool.ff | sun := bool.ff | _ := bool.tt /- PRODUCT TYPES (records, structures) -/ /- A product type has one constructor that takes and bundles up values of zero or more other types into records, aka structures. In a value of a product type there a value for the first field of an object AND a value for the second AND a value for the third, etc. So PRODUCT, in this sense means, AND. -/ /- Note: The empty type can be viewed as a product type with zero fields. -/ /- We now define a product type with one field. -/ inductive box_nat' : Type | mk (val : ℕ) -- /--/ To understand such a definition you need to understand that a constructor, C, is a specific kind of function, namely one that takes zero or more arguments, a₀ ... aₙ, and simply constructs a term, (C a₀ ... aₙ). You can think of such a term as a box, labelled with the constructor name, C, and containing each argument value supplied to the constructor. A value of our box type can thus be visualized as a box (term) with a single value, the argument to box.mk, inside. As usual there are a few syntactic styles for defining such types. We illustrate the syntactic forms and the general ideas by defining a new type, box_nat, a value of which you can visualize as a box (or record or structure) with a single value (field) of type nat. -/ inductive box_nat'' : Type | mk : ℕ → box_nat'' structure box_nat''' : Type := mk :: (val : ℕ) structure box_nat := -- readable (val : ℕ) -- Let's create such a value def aBox := box_nat.mk 3 -- What does the term look like? -- Lean prints it using a record notation #reduce aBox /- Given such a box, we "destructure" (open) it using "pattern matching" to (1) get at the argument values used in its construction, (2) to give temporary names to those value so that we can compute with them. Here we see a more interesting form of unification. The key ideas are (1) the algorithm determines whether a pattern matches, (2) it binds specified names to the values of the fields in the object being matched. In general we use these temporary names to write expressions that define return values. -/ def unbox_nat : box_nat → ℕ -- box_nat.mk 3 -- pattern matching -- | | -- n is now bound to 3 | (box_nat.mk n) := n -- return value of n #eval unbox_nat aBox -- it works /- When you use the "structure" syntax, Lean generates a projection (accessor) function for each field automatically. Each such function as the same name as that of the field it projects/accesses. -/ #eval box_nat.val aBox #eval aBox.val -- Preferred notation /- Polymorphic types -/ /- We now have the same problem we had with functions: the need for a many copies varying only in the type of value(s) "contained in the box". For example we might want a box type a value of which contains value of type nat, or of type string, or bool, etc. The solution is the same: make our types *polymorphic* by having their definitions parameterized by other types, and by using the *values* of these type parameters as the *types* of other values. -/ /- Here's a polymorphic box type. -/ structure box (α : Type) : Type := (val : α) /- box is now a "type builder", a function that takes a *type), α, (e.g., nat, bool) as an argument and that builds and returns a type, box α (e.g., box nat, box bool), whose constructor, mk, take a value of that type. Here the projection function, val, is also polymorphic with an implicit type parameter, α. -/ /- Here are examples where we construct values of type "box nat" and "box bool" respectively. Note that box.mk takes no explicit type argument. -/ def nat_box : box nat := box.mk 3 def bool_box : box bool := box.mk bool.tt /- Tiny note: We defined our own version of bool above. If we were to write tt in this example, we'd pick up Lean's tt, not our own, so we write bool.tt instead, picking up the version of bool we've defined in this namespace (hidden). -/ /- So what's the type of box itself? It's not type, but rather reflects the fact that box takes a type (of type, Type) as an argument and returns a type (of type, Type) as a result. -/ #check nat_box -- Example uses of the "box α" type -- box string def str_box : box string:= box.mk "Hello, Lean!" -- box bool def bool_box' := box.mk bool.tt #eval nat_box.val #eval str_box.val #eval bool_box.val -- Lean doesn't know how to print -- We can also create boxes that contain functions #check nat.succ #eval nat.succ 4 def fun_box : box (nat → nat) := box.mk (nat.succ) /- Polymorphic product types with two fields -- the type of ordered pairs -- and two type parameters accordingly. -/ structure prod (α β : Type) : Type := (fst : α) (snd : β) -- Self-test: What's the type of prod? -- "Introduce" some pairs def pair1 := prod.mk 4 "Hi" -- prod "type" has two type arguments #check pair1 #check prod -- polymorphic projection functions #eval prod.fst pair1 #eval prod.snd pair1 -- dot notation, like in C, C++, Java, etc #eval pair1.fst #eval pair1.snd /- A forward-looking example: a structure type the values of which are pythagorean triples. The first three fields are the lengths of 3 sides of a triangle. The value of the last field is a proof (whatever that is in Lean) that the values of the first three fields satisfy the condition of being such a triple. What this means is that you simply cannot construct a triple of this form without a proof that it really is Pythagorean. The *type* of proof required as a value in the last field is *uninhabited* (empty) if the three numbers don't add up right. -/ structure phythagorean_triple : Type := (a : ℕ) (b : ℕ) (c : ℕ) (cert: a*a + b*b = c*c) /- Without explaining what rfl does exactly, here's a case where the require proof is constructed automatically (by rfl). -/ def py_tri : phythagorean_triple := phythagorean_triple.mk 3 4 5 rfl /- Here, however, there is no such proof, so its construction fails, and the bug in our argument values is revealed by this failure. -/ def py_tri_bad : phythagorean_triple := phythagorean_triple.mk 3 4 6 rfl -- can't construct proof of 25 = 36 -- Try that in Java or mere Haskell! end hidden
343605f2a61d066b65759ce2fbae0651613993c2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/lie/subalgebra.lean
70b3bafb9cc4f58cfc33bf13c07ef380f92bb215
[ "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
20,325
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import ring_theory.noetherian /-! # Lie subalgebras This file defines Lie subalgebras of a Lie algebra and provides basic related definitions and results. ## Main definitions * `lie_subalgebra` * `lie_subalgebra.incl` * `lie_subalgebra.map` * `lie_hom.range` * `lie_equiv.of_injective` * `lie_equiv.of_eq` * `lie_equiv.of_subalgebra` * `lie_equiv.of_subalgebras` ## Tags lie algebra, lie subalgebra -/ universes u v w w₁ w₂ section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] set_option old_structure_cmd true /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem' : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) attribute [nolint doc_blame] lie_subalgebra.to_submodule /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ instance : has_mem L (lie_subalgebra R L) := ⟨λ x L', x ∈ (L' : set L)⟩ /-- A Lie subalgebra forms a new Lie ring. -/ instance lie_subalgebra_lie_ring (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem' x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, leibniz_lie := by { intros, apply set_coe.ext, apply leibniz_lie, } } /-- A Lie subalgebra forms a new Lie algebra. -/ instance lie_subalgebra_lie_algebra (L' : lie_subalgebra R L) : lie_algebra R L' := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } namespace lie_subalgebra variables {R L} (L' : lie_subalgebra R L) @[simp] lemma zero_mem : (0 : L) ∈ L' := (L' : submodule R L).zero_mem lemma smul_mem (t : R) {x : L} (h : x ∈ L') : t • x ∈ L' := (L' : submodule R L).smul_mem t h lemma add_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (x + y : L) ∈ L' := (L' : submodule R L).add_mem hx hy lemma sub_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (x - y : L) ∈ L' := (L' : submodule R L).sub_mem hx hy lemma lie_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (⁅x, y⁆ : L) ∈ L' := L'.lie_mem' hx hy @[simp] lemma mem_carrier {x : L} : x ∈ L'.carrier ↔ x ∈ (L' : set L) := iff.rfl @[simp] lemma mem_mk_iff (S : set L) (h₁ h₂ h₃ h₄) {x : L} : x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_subalgebra R L) ↔ x ∈ S := iff.rfl @[simp] lemma mem_coe_submodule {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl lemma mem_coe {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl @[simp, norm_cast] lemma coe_bracket (x y : L') : (↑⁅x, y⁆ : L) = ⁅(↑x : L), ↑y⁆ := rfl lemma ext_iff (x y : L') : x = y ↔ (x : L) = y := subtype.ext_iff lemma coe_zero_iff_zero (x : L') : (x : L) = 0 ↔ x = 0 := (ext_iff L' x 0).symm @[ext] lemma ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') : L₁' = L₂' := by { cases L₁', cases L₂', simp only [], ext x, exact h x, } lemma ext_iff' (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' := ⟨λ h x, by rw h, ext L₁' L₂'⟩ @[simp] lemma mk_coe (S : set L) (h₁ h₂ h₃ h₄) : ((⟨S, h₁, h₂, h₃, h₄⟩ : lie_subalgebra R L) : set L) = S := rfl @[simp] lemma coe_to_submodule_mk (p : submodule R L) (h) : (({lie_mem' := h, ..p} : lie_subalgebra R L) : submodule R L) = p := by { cases p, refl, } lemma coe_injective : function.injective (coe : lie_subalgebra R L → set L) := λ L₁' L₂' h, by cases L₁'; cases L₂'; congr' @[norm_cast] theorem coe_set_eq (L₁' L₂' : lie_subalgebra R L) : (L₁' : set L) = L₂' ↔ L₁' = L₂' := coe_injective.eq_iff lemma to_submodule_injective : function.injective (coe : lie_subalgebra R L → submodule R L) := λ L₁' L₂' h, by { rw set_like.ext'_iff at h, rw ← coe_set_eq, exact h, } @[simp] lemma coe_to_submodule_eq_iff (L₁' L₂' : lie_subalgebra R L) : (L₁' : submodule R L) = (L₂' : submodule R L) ↔ L₁' = L₂' := to_submodule_injective.eq_iff @[norm_cast] lemma coe_to_submodule : ((L' : submodule R L) : set L) = L' := rfl section lie_module variables {M : Type w} [add_comm_group M] [lie_ring_module L M] variables {N : Type w₁} [add_comm_group N] [lie_ring_module L N] [module R N] [lie_module R L N] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie ring module `M` of `L`, we may regard `M` as a Lie ring module of `L'` by restriction. -/ instance : lie_ring_module L' M := { bracket := λ x m, ⁅(x : L), m⁆, add_lie := λ x y m, add_lie x y m, lie_add := λ x y m, lie_add x y m, leibniz_lie := λ x y m, leibniz_lie x y m, } @[simp] lemma coe_bracket_of_module (x : L') (m : M) : ⁅x, m⁆ = ⁅(x : L), m⁆ := rfl variables [module R M] [lie_module R L M] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie module `M` of `L`, we may regard `M` as a Lie module of `L'` by restriction. -/ instance : lie_module R L' M := { smul_lie := λ t x m, by simp only [coe_bracket_of_module, smul_lie, submodule.coe_smul_of_tower], lie_smul := λ t x m, by simp only [coe_bracket_of_module, lie_smul], } /-- An `L`-equivariant map of Lie modules `M → N` is `L'`-equivariant for any Lie subalgebra `L' ⊆ L`. -/ def _root_.lie_module_hom.restrict_lie (f : M →ₗ⁅R,L⁆ N) (L' : lie_subalgebra R L) : M →ₗ⁅R,L'⁆ N := { map_lie' := λ x m, f.map_lie ↑x m, .. (f : M →ₗ[R] N)} @[simp] lemma _root_.lie_module_hom.coe_restrict_lie (f : M →ₗ⁅R,L⁆ N) : ⇑(f.restrict_lie L') = f := rfl end lie_module /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie algebras. -/ def incl : L' →ₗ⁅R⁆ L := { map_lie' := λ x y, by { simp only [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, }, .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl : ⇑L'.incl = coe := rfl /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie modules. -/ def incl' : L' →ₗ⁅R,L'⁆ L := { map_lie' := λ x y, by simp only [coe_bracket_of_module, linear_map.to_fun_eq_coe, submodule.subtype_apply, coe_bracket], .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl' : ⇑L'.incl' = coe := rfl end lie_subalgebra variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂] variables (f : L →ₗ⁅R⁆ L₂) namespace lie_hom /-- The range of a morphism of Lie algebras is a Lie subalgebra. -/ def range : lie_subalgebra R L₂ := { lie_mem' := λ x y, show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range, by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩, rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw map_lie, }, ..(f : L →ₗ[R] L₂).range } @[simp] lemma range_coe : (f.range : set L₂) = set.range f := linear_map.range_coe ↑f @[simp] lemma mem_range (x : L₂) : x ∈ f.range ↔ ∃ (y : L), f y = x := linear_map.mem_range lemma mem_range_self (x : L) : f x ∈ f.range := linear_map.mem_range_self f x /-- We can restrict a morphism to a (surjective) map to its range. -/ def range_restrict : L →ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply subtype.ext, exact f.map_lie x y, }, ..(f : L →ₗ[R] L₂).range_restrict, } @[simp] lemma range_restrict_apply (x : L) : f.range_restrict x = ⟨f x, f.mem_range_self x⟩ := rfl lemma surjective_range_restrict : function.surjective (f.range_restrict) := begin rintros ⟨y, hy⟩, erw mem_range at hy, obtain ⟨x, rfl⟩ := hy, use x, simp only [subtype.mk_eq_mk, range_restrict_apply], end end lie_hom lemma submodule.exists_lie_subalgebra_coe_eq_iff (p : submodule R L) : (∃ (K : lie_subalgebra R L), ↑K = p) ↔ ∀ (x y : L), x ∈ p → y ∈ p → ⁅x, y⁆ ∈ p := begin split, { rintros ⟨K, rfl⟩, exact K.lie_mem', }, { intros h, use { lie_mem' := h, ..p }, exact lie_subalgebra.coe_to_submodule_mk p _, }, end namespace lie_subalgebra variables (K K' : lie_subalgebra R L) (K₂ : lie_subalgebra R L₂) @[simp] lemma incl_range : K.incl.range = K := by { rw ← coe_to_submodule_eq_iff, exact (K : submodule R L).range_subtype, } /-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the codomain. -/ def map : lie_subalgebra R L₂ := { lie_mem' := λ x y hx hy, by { erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx, erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy, erw submodule.mem_map, exact ⟨⁅x', y'⁆, K.lie_mem hx' hy', f.map_lie x' y'⟩, }, ..((K : submodule R L).map (f : L →ₗ[R] L₂)) } @[simp] lemma mem_map (x : L₂) : x ∈ K.map f ↔ ∃ (y : L), y ∈ K ∧ f y = x := submodule.mem_map -- TODO Rename and state for homs instead of equivs. @[simp] lemma mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (x : L₂) : x ∈ K.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (K : submodule R L).map (e : L →ₗ[R] L₂) := iff.rfl /-- The preimage of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the domain. -/ def comap : lie_subalgebra R L := { lie_mem' := λ x y hx hy, by { suffices : ⁅f x, f y⁆ ∈ K₂, by { simp [this], }, exact K₂.lie_mem hx hy, }, ..((K₂ : submodule R L₂).comap (f : L →ₗ[R] L₂)), } section lattice_structure open set instance : partial_order (lie_subalgebra R L) := { le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq. ..partial_order.lift (coe : lie_subalgebra R L → set L) coe_injective } lemma le_def : K ≤ K' ↔ (K : set L) ⊆ K' := iff.rfl @[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (K : submodule R L) ≤ K' ↔ K ≤ K' := iff.rfl instance : has_bot (lie_subalgebra R L) := ⟨0⟩ @[simp] lemma bot_coe : ((⊥ : lie_subalgebra R L) : set L) = {0} := rfl @[simp] lemma bot_coe_submodule : ((⊥ : lie_subalgebra R L) : submodule R L) = ⊥ := rfl @[simp] lemma mem_bot (x : L) : x ∈ (⊥ : lie_subalgebra R L) ↔ x = 0 := mem_singleton_iff instance : has_top (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, mem_univ ⁅x, y⁆, ..(⊤ : submodule R L) }⟩ @[simp] lemma top_coe : ((⊤ : lie_subalgebra R L) : set L) = univ := rfl @[simp] lemma top_coe_submodule : ((⊤ : lie_subalgebra R L) : submodule R L) = ⊤ := rfl @[simp] lemma mem_top (x : L) : x ∈ (⊤ : lie_subalgebra R L) := mem_univ x lemma _root_.lie_hom.range_eq_map : f.range = map f ⊤ := by { ext, simp } instance : has_inf (lie_subalgebra R L) := ⟨λ K K', { lie_mem' := λ x y hx hy, mem_inter (K.lie_mem hx.1 hy.1) (K'.lie_mem hx.2 hy.2), ..(K ⊓ K' : submodule R L) }⟩ instance : has_Inf (lie_subalgebra R L) := ⟨λ S, { lie_mem' := λ x y hx hy, by { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib] at *, intros K hK, exact K.lie_mem (hx K hK) (hy K hK), }, ..Inf {(s : submodule R L) | s ∈ S} }⟩ @[simp] theorem inf_coe : (↑(K ⊓ K') : set L) = K ∩ K' := rfl @[simp] lemma Inf_coe_to_submodule (S : set (lie_subalgebra R L)) : (↑(Inf S) : submodule R L) = Inf {(s : submodule R L) | s ∈ S} := rfl @[simp] lemma Inf_coe (S : set (lie_subalgebra R L)) : (↑(Inf S) : set L) = ⋂ s ∈ S, (s : set L) := begin rw [← coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe], ext x, simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib], end lemma Inf_glb (S : set (lie_subalgebra R L)) : is_glb S (Inf S) := begin have h : ∀ (K K' : lie_subalgebra R L), (K : set L) ≤ K' ↔ K ≤ K', { intros, exact iff.rfl, }, simp only [is_glb.of_image h, Inf_coe, is_glb_binfi], end /-- The set of Lie subalgebras of a Lie algebra form a complete lattice. We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions than we would otherwise obtain from `complete_lattice_of_Inf`. -/ instance : complete_lattice (lie_subalgebra R L) := { bot := ⊥, bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', }, top := ⊤, le_top := λ _ _ _, trivial, inf := (⊓), le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩, inf_le_left := λ _ _ _, and.left, inf_le_right := λ _ _ _, and.right, ..complete_lattice_of_Inf _ Inf_glb } instance : add_comm_monoid (lie_subalgebra R L) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm, } @[simp] lemma add_eq_sup : K + K' = K ⊔ K' := rfl @[norm_cast, simp] lemma inf_coe_to_submodule : (↑(K ⊓ K') : submodule R L) = (K : submodule R L) ⊓ (K' : submodule R L) := rfl @[simp] lemma mem_inf (x : L) : x ∈ K ⊓ K' ↔ x ∈ K ∧ x ∈ K' := by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule, submodule.mem_inf] lemma eq_bot_iff : K = ⊥ ↔ ∀ (x : L), x ∈ K → x = 0 := by { rw eq_bot_iff, exact iff.rfl, } -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_bot : subsingleton (lie_subalgebra R ↥(⊥ : lie_subalgebra R L)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, mem_bot], end variables (R L) lemma well_founded_of_noetherian [is_noetherian R L] : well_founded ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) := begin let f : ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) →r ((>) : submodule R L → submodule R L → Prop) := { to_fun := coe, map_rel' := λ N N' h, h, }, apply f.well_founded, rw ← is_noetherian_iff_well_founded, apply_instance, end variables {R L K K' f} section nested_subalgebras variables (h : K ≤ K') /-- Given two nested Lie subalgebras `K ⊆ K'`, the inclusion `K ↪ K'` is a morphism of Lie algebras. -/ def hom_of_le : K →ₗ⁅R⁆ K' := { map_lie' := λ x y, rfl, ..submodule.of_le h } @[simp] lemma coe_hom_of_le (x : K) : (hom_of_le h x : L) = x := rfl lemma hom_of_le_apply (x : K) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl lemma hom_of_le_injective : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] /-- Given two nested Lie subalgebras `K ⊆ K'`, we can view `K` as a Lie subalgebra of `K'`, regarded as Lie algebra in its own right. -/ def of_le : lie_subalgebra R K' := (hom_of_le h).range @[simp] lemma mem_of_le (x : K') : x ∈ of_le h ↔ (x : L) ∈ K := begin simp only [of_le, hom_of_le_apply, lie_hom.mem_range], split, { rintros ⟨y, rfl⟩, exact y.property, }, { intros h, use ⟨(x : L), h⟩, simp, }, end lemma of_le_eq_comap_incl : of_le h = K.comap K'.incl := by { ext, rw mem_of_le, refl, } end nested_subalgebras lemma map_le_iff_le_comap {K : lie_subalgebra R L} {K' : lie_subalgebra R L₂} : map f K ≤ K' ↔ K ≤ comap f K' := set.image_subset_iff lemma gc_map_comap : galois_connection (map f) (comap f) := λ K K', map_le_iff_le_comap end lattice_structure section lie_span variables (R L) (s : set L) /-- The Lie subalgebra of a Lie algebra `L` generated by a subset `s ⊆ L`. -/ def lie_span : lie_subalgebra R L := Inf {N | s ⊆ N} variables {R L s} lemma mem_lie_span {x : L} : x ∈ lie_span R L s ↔ ∀ K : lie_subalgebra R L, s ⊆ K → x ∈ K := by { change x ∈ (lie_span R L s : set L) ↔ _, erw Inf_coe, exact set.mem_bInter_iff, } lemma subset_lie_span : s ⊆ lie_span R L s := by { intros m hm, erw mem_lie_span, intros K hK, exact hK hm, } lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s := by { rw submodule.span_le, apply subset_lie_span, } lemma lie_span_le {K} : lie_span R L s ≤ K ↔ s ⊆ K := begin split, { exact set.subset.trans subset_lie_span, }, { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, }, end lemma lie_span_mono {t : set L} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t := by { rw lie_span_le, exact set.subset.trans h subset_lie_span, } lemma lie_span_eq : lie_span R L (K : set L) = K := le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span lemma coe_lie_span_submodule_eq_iff {p : submodule R L} : (lie_span R L (p : set L) : submodule R L) = p ↔ ∃ (K : lie_subalgebra R L), ↑K = p := begin rw p.exists_lie_subalgebra_coe_eq_iff, split; intros h, { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), }, { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], }, end end lie_span end lie_subalgebra end lie_subalgebra namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] /-- An injective Lie algebra morphism is an equivalence onto its range. -/ noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) : L₁ ≃ₗ⁅R⁆ f.range := have h' : (f : L₁ →ₗ[R] L₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective h, { map_lie' := λ x y, by { apply set_coe.ext, simpa, }, ..(linear_equiv.of_injective ↑f h')} @[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) : ↑(of_injective f h x) = f x := rfl variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂) /-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/ def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' := { map_lie' := λ x y, by { apply set_coe.ext, simp, }, ..(linear_equiv.of_eq ↑L₁' ↑L₁'' (by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) } @[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) : (↑(of_eq L L' h x) : L₁) = x := rfl variables (e : L₁ ≃ₗ⁅R⁆ L₂) /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebra : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, } ..(linear_equiv.of_submodule (e : L₁ ≃ₗ[R] L₂) ↑L₁'') } @[simp] lemma of_subalgebra_apply (x : L₁'') : ↑(e.of_subalgebra _ x) = e x := rfl /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }, ..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) } @[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') : ↑(e.of_subalgebras _ _ h x) = e x := rfl @[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') : ↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl end lie_equiv
ce7447d24ce2e012bf5c1c0037f87056daf66e80
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Meta/AppBuilder.lean
a3fb5aaf1e8fefd1e72a8f3f029380e02b0ee252
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,659
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.SynthInstance import Lean.Meta.Check namespace Lean.Meta variables {m : Type → Type} [MonadLiftT MetaM m] private def mkIdImp (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type pure $ mkApp2 (mkConst `id [u]) type e /-- Return `id e` -/ def mkId (e : Expr) : m Expr := liftMetaM $ mkIdImp e private def mkExpectedTypeHintImp (e : Expr) (expectedType : Expr) : MetaM Expr := do let u ← getLevel expectedType pure $ mkApp2 (mkConst `id [u]) expectedType e /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : m Expr := liftMetaM $ mkExpectedTypeHintImp e expectedType private def mkEqImp (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp3 (mkConst `Eq [u]) aType a b def mkEq (a b : Expr) : m Expr := liftMetaM $ mkEqImp a b private def mkHEqImp (a b : Expr) : MetaM Expr := do let aType ← inferType a let bType ← inferType b let u ← getLevel aType pure $ mkApp4 (mkConst `HEq [u]) aType a bType b def mkHEq (a b : Expr) : m Expr := liftMetaM $ mkHEqImp a b private def mkEqReflImp (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst `Eq.refl [u]) aType a def mkEqRefl (a : Expr) : m Expr := liftMetaM $ mkEqReflImp a private def mkHEqReflImp (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst `HEq.refl [u]) aType a def mkHEqRefl (a : Expr) : m Expr := liftMetaM $ mkHEqReflImp a private def infer (h : Expr) : MetaM Expr := do let hType ← inferType h whnfD hType private def hasTypeMsg (e type : Expr) : MessageData := msg!"{indentExpr e}\nhas type{indentExpr type}" private def throwAppBuilderException {α} (op : Name) (msg : MessageData) : MetaM α := throwError! "AppBuilder for '{op}', {msg}" private def mkEqSymmImp (h : Expr) : MetaM Expr := if h.isAppOf `Eq.refl then pure h else do let hType ← infer h match hType.eq? with | some (α, a, b) => do let u ← getLevel α; pure $ mkApp4 (mkConst `Eq.symm [u]) α a b h | none => throwAppBuilderException `Eq.symm ("equality proof expected" ++ hasTypeMsg h hType) def mkEqSymm (h : Expr) : m Expr := liftMetaM $ mkEqSymmImp h private def mkEqTransImp (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `Eq.refl then pure h₂ else if h₂.isAppOf `Eq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => do let u ← getLevel α; pure $ mkApp6 (mkConst `Eq.trans [u]) α a b c h₁ h₂ | none, _ => throwAppBuilderException `Eq.trans ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `Eq.trans ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkEqTrans (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkEqTransImp h₁ h₂ private def mkHEqSymmImp (h : Expr) : MetaM Expr := if h.isAppOf `HEq.refl then pure h else do let hType ← infer h match hType.heq? with | some (α, a, β, b) => do let u ← getLevel α; pure $ mkApp5 (mkConst `HEq.symm [u]) α β a b h | none => throwAppBuilderException `HEq.symm ("heterogeneous equality proof expected" ++ hasTypeMsg h hType) def mkHEqSymm (h : Expr) : m Expr := liftMetaM $ mkHEqSymmImp h private def mkHEqTransImp (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf `HEq.refl then pure h₂ else if h₂.isAppOf `HEq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => let u ← getLevel α; pure $ mkApp8 (mkConst `HEq.trans [u]) α β γ a b c h₁ h₂ | none, _ => throwAppBuilderException `HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkHEqTrans (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkHEqTransImp h₁ h₂ private def mkEqOfHEqImp (h : Expr) : MetaM Expr := do let hType ← infer h match hType.heq? with | some (α, a, β, b) => unless (← isDefEq α β) do throwAppBuilderException `eqOfHEq msg!"heterogeneous equality types are not definitionally equal{indentExpr α}\nis not definitionally equal to{indentExpr β}" let u ← getLevel α pure $ mkApp4 (mkConst `eqOfHEq [u]) α a b h | _ => throwAppBuilderException `HEq.trans msg!"heterogeneous equality proof expected{indentExpr h}" def mkEqOfHEq (h : Expr) : m Expr := liftMetaM $ mkEqOfHEqImp h private def mkCongrArgImp (f h : Expr) : MetaM Expr := do let hType ← infer h let fType ← infer f match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => let u ← getLevel α; let v ← getLevel β; pure $ mkApp6 (mkConst `congrArg [u, v]) α β a b f h | none, _ => throwAppBuilderException `congrArg ("non-dependent function expected" ++ hasTypeMsg f fType) | _, none => throwAppBuilderException `congrArg ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrArg (f h : Expr) : m Expr := liftMetaM $ mkCongrArgImp f h private def mkCongrFunImp (h a : Expr) : MetaM Expr := do let hType ← infer h match hType.eq? with | some (ρ, f, g) => do let ρ ← whnfD ρ match ρ with | Expr.forallE n α β _ => do let β' := Lean.mkLambda n BinderInfo.default α β let u ← getLevel α let v ← getLevel (mkApp β' a) pure $ mkApp6 (mkConst `congrFun [u, v]) α β' f g h a | _ => throwAppBuilderException `congrFun ("equality proof between functions expected" ++ hasTypeMsg h hType) | _ => throwAppBuilderException `congrFun ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrFun (h a : Expr) : m Expr := liftMetaM $ mkCongrFunImp h a private def mkCongrImp (h₁ h₂ : Expr) : MetaM Expr := do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => do let ρ ← whnfD ρ match ρ.arrow? with | some (_, β) => do let u ← getLevel α let v ← getLevel β pure $ mkApp8 (mkConst `congr [u, v]) α β f g a b h₁ h₂ | _ => throwAppBuilderException `congr ("non-dependent function expected" ++ hasTypeMsg h₁ hType₁) | none, _ => throwAppBuilderException `congr ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `congr ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkCongr (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkCongrImp h₁ h₂ private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM fun mvarId => do let mvarDecl ← getMVarDecl mvarId let mvarVal ← synthInstance mvarDecl.type assignExprMVar mvarId mvarVal let result ← instantiateMVars (mkAppN f args) if (← hasAssignableMVar result) then throwAppBuilderException methodName ("result contains metavariables" ++ indentExpr result) pure result private partial def mkAppMArgs (f : Expr) (fType : Expr) (xs : Array Expr) : MetaM Expr := let rec loop (type : Expr) (i : Nat) (j : Nat) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do if i >= xs.size then mkAppMFinal `mkAppM f args instMVars else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j args.size args match c.binderInfo with | BinderInfo.implicit => let mvar ← mkFreshExprMVar d MetavarKind.natural n loop b i j (args.push mvar) instMVars | BinderInfo.instImplicit => let mvar ← mkFreshExprMVar d MetavarKind.synthetic n loop b i j (args.push mvar) (instMVars.push mvar.mvarId!) | _ => let x := xs[i] let xType ← inferType x if (← isDefEq d xType) then loop b (i+1) j (args.push x) instMVars else throwAppTypeMismatch (mkAppN f args) x | type => let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then loop type i args.size args instMVars else throwAppBuilderException `mkAppM msg!"too many explicit arguments provided to{indentExpr f}\narguments{indentD xs}" loop fType 0 0 #[] #[] private def mkFun (constName : Name) : MetaM (Expr × Expr) := do let cinfo ← getConstInfo constName let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar let f := mkConst constName us let fType := cinfo.instantiateTypeLevelParams us pure (f, fType) /-- Return the application `constName xs`. It tries to fill the implicit arguments before the last element in `xs`. Remark: ``mkAppM `arbitrary #[α]`` returns `@arbitrary.{u} α` without synthesizing the implicit argument occurring after `α`. Given a `x : (([Decidable p] → Bool) × Nat`, ``mkAppM `Prod.fst #[x]`` returns `@Prod.fst ([Decidable p] → Bool) Nat x` -/ def mkAppM (constName : Name) (xs : Array Expr) : m Expr := liftMetaM do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName let r ← mkAppMArgs f fType xs trace[Meta.appBuilder]! "constName: {constName}, xs: {xs}, result: {r}" pure r private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args if h : i < xs.size then match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do let mvar ← mkFreshExprMVar d MetavarKind.synthetic n mkAppOptMAux f xs (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do let mvar ← mkFreshExprMVar d MetavarKind.natural n mkAppOptMAux f xs (i+1) (args.push mvar) j instMVars b | some x => let xType ← inferType x if (← isDefEq d xType) then mkAppOptMAux f xs (i+1) (args.push x) j instMVars b else throwAppTypeMismatch (mkAppN f args) x else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then mkAppOptMAux f xs i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[] throwAppBuilderException `mkAppOptM ("too many arguments provided to" ++ indentExpr f ++ Format.line ++ "arguments" ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `Pure.pure {m : Type u → Type v} [Pure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `Pure.pure #[m, none, none, a] ``` returns a `Pure.pure` application if the instance `Pure m` can be synthesized, and the universes match. Note that, ``` mkAppM `Pure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : m Expr := liftMetaM do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName mkAppOptMAux f xs 0 #[] 0 #[] fType private def mkEqNDRecImp (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf `Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException `Eq.ndrec ("equality proof expected" ++ hasTypeMsg h2 h2Type) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => pure $ mkAppN (mkConst `Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException `Eq.ndrec ("invalid motive" ++ indentExpr motive) def mkEqNDRec (motive h1 h2 : Expr) : m Expr := liftMetaM $ mkEqNDRecImp motive h1 h2 private def mkEqRecImp (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf `Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException `Eq.rec ("equality proof expected" ++ indentExpr h2) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => pure $ mkAppN (mkConst `Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException `Eq.rec ("invalid motive" ++ indentExpr motive) def mkEqRec (motive h1 h2 : Expr) : m Expr := liftMetaM $ mkEqRecImp motive h1 h2 def mkEqMP (eqProof pr : Expr) : m Expr := mkAppM `Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : m Expr := mkAppM `Eq.mpr #[eqProof, pr] private def mkNoConfusionImp (target : Expr) (h : Expr) : MetaM Expr := do let type ← inferType h let type ← whnf type match type.eq? with | none => throwAppBuilderException `noConfusion ("equality expected" ++ hasTypeMsg h type) | some (α, a, b) => let α ← whnf α matchConstInduct α.getAppFn (fun _ => throwAppBuilderException `noConfusion ("inductive type expected" ++ indentExpr α)) fun v us => do let u ← getLevel target pure $ mkAppN (mkConst (Name.mkStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) def mkNoConfusion (target : Expr) (h : Expr) : m Expr := liftMetaM $ mkNoConfusionImp target h def mkPure (monad : Expr) (e : Expr) : m Expr := mkAppOptM `Pure.pure #[monad, none, none, e] /-- `mkProjection s fieldName` return an expression for accessing field `fieldName` of the structure `s`. Remark: `fieldName` may be a subfield of `s`. -/ private partial def mkProjectionImp : Expr → Name → MetaM Expr | s, fieldName => do let type ← inferType s let type ← whnf type match type.getAppFn with | Expr.const structName us _ => let env ← getEnv unless isStructureLike env structName do throwAppBuilderException `mkProjection ("structure expected" ++ hasTypeMsg s type) match getProjFnForField? env structName fieldName with | some projFn => let params := type.getAppArgs pure $ mkApp (mkAppN (mkConst projFn us) params) s | none => do let fields := getStructureFields env structName let r? ← fields.findSomeM? fun fieldName' => do match isSubobjectField? env structName fieldName' with | none => pure none | some _ => let parent ← mkProjectionImp s fieldName' (do let r ← mkProjectionImp parent fieldName; pure $ some r) <|> pure none match r? with | some r => pure r | none => throwAppBuilderException `mkProjectionn ("invalid field name '" ++ toString fieldName ++ "' for" ++ hasTypeMsg s type) | _ => throwAppBuilderException `mkProjectionn ("structure expected" ++ hasTypeMsg s type) def mkProjection (s : Expr) (fieldName : Name) : m Expr := liftMetaM $ mkProjectionImp s fieldName private def mkListLitAux (nil : Expr) (cons : Expr) : List Expr → Expr | [] => nil | x::xs => mkApp (mkApp cons x) (mkListLitAux nil cons xs) private def mkListLitImp (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let nil := mkApp (mkConst `List.nil [u]) type match xs with | [] => pure nil | _ => let cons := mkApp (mkConst `List.cons [u]) type pure $ mkListLitAux nil cons xs def mkListLit (type : Expr) (xs : List Expr) : m Expr := liftMetaM $ mkListLitImp type xs def mkArrayLit (type : Expr) (xs : List Expr) : m Expr := liftMetaM do let u ← getDecLevel type let listLit ← mkListLit type xs pure (mkApp (mkApp (mkConst `List.toArray [u]) type) listLit) def mkSorry (type : Expr) (synthetic : Bool) : m Expr := liftMetaM do let u ← getLevel type pure $ mkApp2 (mkConst `sorryAx [u]) type (toExpr synthetic) /-- Return `Decidable.decide p` -/ def mkDecide (p : Expr) : m Expr := mkAppOptM `Decidable.decide #[p, none] /-- Return a proof for `p : Prop` using `decide p` -/ def mkDecideProof (p : Expr) : m Expr := liftMetaM do let decP ← mkDecide p let decEqTrue ← mkEq decP (mkConst `Bool.true) let h ← mkEqRefl (mkConst `Bool.true) let h ← mkExpectedTypeHint h decEqTrue mkAppM `ofDecideEqTrue #[h] /-- Return `a < b` -/ def mkLt (a b : Expr) : m Expr := mkAppM `HasLess.Less #[a, b] /-- Return `a <= b` -/ def mkLe (a b : Expr) : m Expr := mkAppM `HasLessEq.LessEq #[a, b] /-- Return `arbitrary α` -/ def mkArbitrary (α : Expr) : m Expr := mkAppOptM `arbitrary #[α, none] builtin_initialize registerTraceClass `Meta.appBuilder end Lean.Meta
0288bd0781d3501c01a92ecfae3c5d2637ad86e7
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Meta/ExprDefEq.lean
900988a1f366828664af2679e43213cc62778a45
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
57,619
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.LevelDefEq import Lean.Meta.Check import Lean.Meta.Offset import Lean.Meta.ForEachExpr import Lean.Meta.UnificationHint namespace Lean.Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else pure false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf `String.mk then isDefEq (toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId _) => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure false else if (← isExprMVarAssigned mvarId) then pure false else pure true | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do let rec loop (i : Nat) (postponed : Array Nat) := do if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩ let a₁ := args₁[i] let a₂ := args₂[i] if info.implicit || info.instImplicit then if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else loop (i+1) (postponed.push i) else if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else pure (some postponed) loop 0 #[] @[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do let finfo ← getFunInfoNArgs f args₁.size let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false let rec processOtherArgs (i : Nat) : MetaM Bool := do if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩ let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩ if (← Meta.isExprDefEqAux a₁ a₂) then processOtherArgs (i+1) else pure false else pure true if (← processOtherArgs finfo.paramInfo.size) then postponed.allM fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i] let a₂ := args₂[i] let info := finfo.paramInfo[i] if info.instImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂ else pure false else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i] if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes do if !mvar.isMVar then trace[Meta.isDefEq.assign.final] "metavariable expected at {mvar} := {v}" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then trace[Meta.isDefEq.assign.final] "{mvar} := {v}" assignExprMVar mvar.mvarId! v pure true else trace[Meta.isDefEq.assign.typeMismatch] "{mvar} : {mvarType} := {v} : {vType}" pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps trace[Meta.debug] "ys: {ys}, v: {v}" mkLambdaFVars ys v where /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := do let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then pure false else check (← getLCtx) /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => let localDecl ← getLocalDecl fvarId if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT NameHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM NameHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.ctxApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← getMVarDecl mvarId let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (LocalDecl.ldecl (value := v) ..) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read let mctx ← getMCtx if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl => if ctx.mvarDecl.lctx.contains localDecl.fvarId then toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too toErase.push localDecl.fvarId else toErase else toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar } pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit checkMVar f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← isDelayedAssigned f.mvarId!) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b _ => return e.updateMData! (← visit check b) | Expr.proj _ _ s _ => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit checkFVar e | Expr.mvar .. => visit checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b _ => visit b | Expr.proj _ _ s _ => visit s | Expr.app f a _ => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' _ => match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← getMVarDecl mvarId let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do let decl ← getLocalDecl fvarId match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← getMVarDecl mvar.mvarId! forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then assignConst mvar numArgs v else pure false /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign do trace[Meta.isDefEq.assign] "{mvarApp} := {v}" let mvar := mvarApp.getAppFn let mvarDecl ← getMVarDecl mvar.mvarId! let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId _ => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := let tFn := t.getAppFn let sFn := s.getAppFn traceCtx `Meta.isDefEq.delta do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! unless b do trace[Meta.isDefEq.delta] "heuristic failed {t} =?= {s}" pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProj? ← isProjectionFn tInfo.name let sProj? ← isProjectionFn sInfo.name if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t.getAppFn let sInfo? ← isDeltaCandidate? s.getAppFn match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do match tFn with | Expr.mvar mvarId _ => if (← isDelayedAssigned mvarId) then let tNew ← instantiateMVars t return tNew != t else pure false | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do let decl ← getLocalDecl fvarId pure decl.isLet private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do let status ← isProofQuick t match status with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType else pure LBool.undef /- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `processConstApprox`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | Expr.lit l₁ _, Expr.lit l₂ _ => return (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM <| isLevelDefEqAux u v | Expr.lam .., Expr.lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | Expr.forallE .., Expr.forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => do if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then pure LBool.undef else if fvarId₁ == fvarId₂ then pure LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do if t == s then pure LBool.true else if etaEq t s || etaEq s t then pure LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then pure LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if (← isDelayedAssignedHead tFn t) then let t ← instantiateMVars t isDefEqQuick t s else if (← isDelayedAssignedHead sFn s) then let s ← instantiateMVars s isDefEqQuick t s else if (← isSynthetic tFn <&&> trySynthPending tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isSynthetic sFn <&&> trySynthPending sFn) then let s ← instantiateMVars s isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else pure LBool.false else pure LBool.undef else isDefEqQuickMVarMVar t s -- Both `t` and `s` are terms of the form `?m ...` private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do let tFn := t.getAppFn let sFn := s.getAppFn let tMVarDecl ← getMVarDecl tFn.mvarId! let sMVarDecl ← getMVarDecl sFn.mvarId! if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then pure LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then pure LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s | _, _ => pure false /- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do trace[Meta.isDefEq.step] "{t} =?= {s}" checkMaxHeartbeats "isDefEq" withNestedTraces do whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then isExprDefEqAuxImpl t' s' else do if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else if (← isDefEqProj t s) then pure true else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else pure false else if t.isApp && s.isApp then isDefEqApp t s else whenUndefDo (isDefEqStringLit t s) do isDefEqOnFailure t s builtin_initialize isExprDefEqAuxRef.set isExprDefEqAuxImpl builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta registerTraceClass `Meta.isDefEq.step registerTraceClass `Meta.isDefEq.assign end Lean.Meta
4b3516c5d79ca730d878d279815276570e6a5f5d
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/logic/eq.lean
4a9b5f3500087dc9405f7141071055ee670fd0ad
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,573
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, Jeremy Avigad, Floris van Doorn Additional declarations/theorems about equality. See also init.datatypes and init.logic. -/ open eq.ops namespace eq variables {A B : Type} {a a' a₁ a₂ a₃ a₄ : A} theorem irrel (H₁ H₂ : a = a') : H₁ = H₂ := !proof_irrel theorem id_refl (H₁ : a = a) : H₁ = (eq.refl a) := rfl theorem rec_on_id {B : A → Type} (H : a = a) (b : B a) : eq.rec_on H b = b := rfl theorem rec_on_constant (H : a = a') {B : Type} (b : B) : eq.rec_on H b = b := eq.drec_on H rfl theorem rec_on_constant2 (H₁ : a₁ = a₂) (H₂ : a₃ = a₄) (b : B) : eq.rec_on H₁ b = eq.rec_on H₂ b := rec_on_constant H₁ b ⬝ (rec_on_constant H₂ b)⁻¹ theorem rec_on_irrel_arg {f : A → B} {D : B → Type} (H : a = a') (H' : f a = f a') (b : D (f a)) : eq.rec_on H b = eq.rec_on H' b := eq.drec_on H (λ(H' : f a = f a), !rec_on_id⁻¹) H' theorem rec_on_irrel {a a' : A} {D : A → Type} (H H' : a = a') (b : D a) : eq.drec_on H b = eq.drec_on H' b := proof_irrel H H' ▸ rfl theorem rec_on_compose {a b c : A} {P : A → Type} (H₁ : a = b) (H₂ : b = c) (u : P a) : eq.rec_on H₂ (eq.rec_on H₁ u) = eq.rec_on (trans H₁ H₂) u := (show ∀ H₂ : b = c, eq.rec_on H₂ (eq.rec_on H₁ u) = eq.rec_on (trans H₁ H₂) u, from eq.drec_on H₂ (take (H₂ : b = b), rec_on_id H₂ _)) H₂ end eq open eq section variables {A B C D E F : Type} variables {a a' : A} {b b' : B} {c c' : C} {d d' : D} {e e' : E} theorem congr_arg2 (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := by substvars theorem congr_arg3 (f : A → B → C → D) (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f a' b' c' := by substvars theorem congr_arg4 (f : A → B → C → D → E) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f a' b' c' d' := by substvars theorem congr_arg5 (f : A → B → C → D → E → F) (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f a' b' c' d' e' := by substvars theorem congr2 (f f' : A → B → C) (Hf : f = f') (Ha : a = a') (Hb : b = b') : f a b = f' a' b' := by substvars theorem congr3 (f f' : A → B → C → D) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') : f a b c = f' a' b' c' := by substvars theorem congr4 (f f' : A → B → C → D → E) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') : f a b c d = f' a' b' c' d' := by substvars theorem congr5 (f f' : A → B → C → D → E → F) (Hf : f = f') (Ha : a = a') (Hb : b = b') (Hc : c = c') (Hd : d = d') (He : e = e') : f a b c d e = f' a' b' c' d' e' := by substvars end theorem equal_f {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) : ∀x, f x = g x := take x, congr_fun H x section variables {a b c : Prop} theorem eqmp (H₁ : a = b) (H₂ : a) : b := H₁ ▸ H₂ theorem eqmpr (H₁ : a = b) (H₂ : b) : a := H₁⁻¹ ▸ H₂ theorem imp_trans (H₁ : a → b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ Ha) theorem imp_eq_trans (H₁ : a → b) (H₂ : b = c) : a → c := assume Ha, H₂ ▸ (H₁ Ha) theorem eq_imp_trans (H₁ : a = b) (H₂ : b → c) : a → c := assume Ha, H₂ (H₁ ▸ Ha) end