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
23513e59cc5d19df909c0ac3700a3cf3acc7bf2f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/252.lean
585d5fceb967d32bd9c9c526b61f7b3f70578679
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
327
lean
open nat inductive tree (A : Type) := leaf : A β†’ tree A, node : tree A β†’ tree A β†’ tree A check tree.node definition size {A : Type} (t : tree A) : nat := tree.rec (Ξ» a, 1) (Ξ» t₁ tβ‚‚ n₁ nβ‚‚, n₁ + nβ‚‚) t check size eval size (tree.node (tree.node (tree.leaf 0) (tree.leaf 1)) (tree.leaf 0))
db17603495b9222c74515426b7e15322e7242d94
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/finish3.lean
65ca0f4b415f23207d3569cee0d0de0a9cdfec46
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,036
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import tactic.finish /-! # Examples for `finish` Those come from the tutorial. -/ open auto section variables p q r s : Prop -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := by finish example : p ∨ q ↔ q ∨ p := by finish -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by finish example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by finish -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by finish [iff_def] example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := by finish [iff_def] -- other properties example : (p β†’ (q β†’ r)) ↔ (p ∧ q β†’ r) := by finish [iff_def] example : ((p ∨ q) β†’ r) ↔ (p β†’ r) ∧ (q β†’ r) := by finish [iff_def] example : Β¬(p ∨ q) ↔ Β¬p ∧ Β¬q := by finish example : Β¬p ∨ Β¬q β†’ Β¬(p ∧ q) := by finish example : Β¬(p ∧ Β¬ p) := by finish example : p ∧ Β¬q β†’ Β¬(p β†’ q) := by finish example : Β¬p β†’ (p β†’ q) := by finish example : (Β¬p ∨ q) β†’ (p β†’ q) := by finish example : p ∨ false ↔ p := by finish example : p ∧ false ↔ false := by finish example : Β¬(p ↔ Β¬p) := by finish example : (p β†’ q) β†’ (Β¬q β†’ Β¬p) := by finish -- these require classical reasoning example : (p β†’ r ∨ s) β†’ ((p β†’ r) ∨ (p β†’ s)) := by finish example : Β¬(p ∧ q) β†’ Β¬p ∨ Β¬q := by finish example : Β¬(p β†’ q) β†’ p ∧ Β¬q := by finish example : (p β†’ q) β†’ (Β¬p ∨ q) := by finish example : (Β¬q β†’ Β¬p) β†’ (p β†’ q) := by finish example : p ∨ Β¬p := by finish example : (((p β†’ q) β†’ p) β†’ p) := by finish end section variables (A : Type) (p q : A β†’ Prop) variable a : A variable r : Prop example : (βˆƒ x : A, r) β†’ r := by finish -- TODO(Jeremy): can we get these automatically? example (a : A) : r β†’ (βˆƒ x : A, r) := begin safe; apply_assumption; assumption end example : (βˆƒ x, p x ∧ r) ↔ (βˆƒ x, p x) ∧ r := by finish theorem foo': (βˆƒ x, p x ∨ q x) ↔ (βˆƒ x, p x) ∨ (βˆƒ x, q x) := by finish [iff_def] example (h : βˆ€ x, Β¬ Β¬ p x) : p a := by finish example (h : βˆ€ x, Β¬ Β¬ p x) : βˆ€ x, p x := by finish example : (βˆ€ x, p x) ↔ Β¬ (βˆƒ x, Β¬ p x) := by finish example : (βˆƒ x, p x) ↔ Β¬ (βˆ€ x, Β¬ p x) := by finish example : (Β¬ βˆƒ x, p x) ↔ (βˆ€ x, Β¬ p x) := by finish example : (Β¬ βˆ€ x, p x) ↔ (βˆƒ x, Β¬ p x) := by finish example : (βˆƒ x, Β¬ p x) β†’ (Β¬ βˆ€ x, p x) := by finish example : (βˆ€ x, p x β†’ r) ↔ (βˆƒ x, p x) β†’ r := by finish [iff_def] -- TODO(Jeremy): can we get these automatically? example (a : A) : (βˆƒ x, p x β†’ r) ↔ (βˆ€ x, p x) β†’ r := begin safe [iff_def]; exact h a end example (a : A) : (βˆƒ x, r β†’ p x) ↔ (r β†’ βˆƒ x, p x) := begin safe [iff_def]; exact h a end example : (βˆƒ x, p x β†’ r) β†’ (βˆ€ x, p x) β†’ r := by finish example : (βˆƒ x, r β†’ p x) β†’ (r β†’ βˆƒ x, p x) := by finish end
33c5a1081d003d71ac6f51cc94467625b18d585a
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/test/out/script/type.lean
41fe1c909f4bdcf3ce49600c7f908c503aa616ff
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,636
lean
import Papyrus.Script.Type open Papyrus Script -- # Floating Point Types #check llvm type half #check llvm type bfloat #check llvm type float #check llvm type double #check llvm type x86_fp80 #check llvm type fp128 #check llvm type ppc_fp128 -- # Special Types #check llvm type void #check llvm type label #check llvm type metadata #check llvm type x86_mmx #check llvm type x86_amx #check llvm type token -- # Integer Types #check i1 #check i32 #check i1942652 #check llvm type i1 #check llvm type i32 #check llvm type i1942652 -- # Function Types #check llvm type i32 (i32) #check llvm type float (i16, i32 *) * #check llvm type i32 (i8*, ...) #check llvm type {i32, i32} (i32) -- # Pointer Types #check i8* #check llvm type i8* #check llvm type [4 x i32]* #check llvm type i32 (i32*) * #check llvm type i32 addrspace(5) * -- # (Literal) Struct Types #check llvm type { i32, i32, i32 } #check llvm type { float, i32 (i32) * } #check llvm type <{ i8, i32 }> -- # Array Types #check llvm type [40 x i32] #check llvm type [41 x i32] #check llvm type [4 x i8] #check llvm type [3 x [4 x i32]] #check llvm type [12 x [10 x float]] #check llvm type [2 x [3 x [4 x i16]]] -- # Vector Types #check llvm type <4 x i32> #check llvm type <8 x float> #check llvm type <2 x i64> #check llvm type < 4 x i64* > #check llvm type <vscale x 4 x i32> -- # Nested Terms #check llvm type [4 Γ— type(int8Type)] #check llvm type { type(int8Type), type(floatType) } -- #check llvm type <4 x i64*> -- fails: `*>` is a separate token -- #check llvm type %X -- #check llvm type %T1 { i32, i32, i32 } -- #check llvm type %T2 <{ i8, i32 }>
229056efd51b99636d5eb2bd3822a2218a3d7633
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/topological_simplex.lean
87a07cc883be3c026913443f66180037535ede2f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,255
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Adam Topaz -/ import algebraic_topology.simplex_category import topology.category.Top.basic import topology.instances.nnreal /-! # Topological simplices We define the natural functor from `simplex_category` to `Top` sending `[n]` to the topological `n`-simplex. This is used to define `Top.to_sSet` in `algebraic_topology.simpliciaL_set`. -/ noncomputable theory namespace simplex_category open_locale simplicial nnreal big_operators classical local attribute [instance] category_theory.concrete_category.has_coe_to_sort category_theory.concrete_category.has_coe_to_fun /-- The topological simplex associated to `x : simplex_category`. This is the object part of the functor `simplex_category.to_Top`. -/ def to_Top_obj (x : simplex_category) := { f : x β†’ ℝβ‰₯0 | βˆ‘ i, f i = 1 } instance (x : simplex_category) : has_coe_to_fun x.to_Top_obj (Ξ» _, x β†’ ℝβ‰₯0) := ⟨λ f, (f : x β†’ ℝβ‰₯0)⟩ @[ext] lemma to_Top_obj.ext {x : simplex_category} (f g : x.to_Top_obj) : (f : x β†’ ℝβ‰₯0) = g β†’ f = g := subtype.ext /-- A morphism in `simplex_category` induces a map on the associated topological spaces. -/ def to_Top_map {x y : simplex_category} (f : x ⟢ y) : x.to_Top_obj β†’ y.to_Top_obj := Ξ» g, ⟨λ i, βˆ‘ j in (finset.univ.filter (Ξ» k, f k = i)), g j, begin simp only [finset.filter_congr_decidable, finset.sum_congr, to_Top_obj, set.mem_set_of], rw ← finset.sum_bUnion, convert g.2, { rw finset.eq_univ_iff_forall, intros i, rw finset.mem_bUnion, exact ⟨f i, by simp, by simp⟩ }, { intros i hi j hj h, rw [function.on_fun, disjoint_iff_inf_le], intros e he, apply h, simp only [true_and, finset.inf_eq_inter, finset.mem_univ, finset.mem_filter, finset.mem_inter] at he, rw [← he.1, ← he.2] } end⟩ @[simp] lemma coe_to_Top_map {x y : simplex_category} (f : x ⟢ y) (g : x.to_Top_obj) (i : y) : to_Top_map f g i = βˆ‘ j in (finset.univ.filter (Ξ» k, f k = i)), g j := rfl @[continuity] lemma continuous_to_Top_map {x y : simplex_category} (f : x ⟢ y) : continuous (to_Top_map f) := continuous.subtype_mk (continuous_pi $ Ξ» i, continuous_finset_sum _ $ Ξ» j hj, (continuous_apply _).comp continuous_subtype_val) _ /-- The functor associating the topological `n`-simplex to `[n] : simplex_category`. -/ @[simps] def to_Top : simplex_category β₯€ Top := { obj := Ξ» x, Top.of x.to_Top_obj, map := Ξ» x y f, ⟨to_Top_map f⟩, map_id' := begin intros x, ext f i : 3, change (finset.univ.filter (Ξ» k, k = i)).sum _ = _, simp [finset.sum_filter] end, map_comp' := begin intros x y z f g, ext h i : 3, dsimp, erw ← finset.sum_bUnion, apply finset.sum_congr, { exact finset.ext (Ξ» j, ⟨λ hj, by simpa using hj, Ξ» hj, by simpa using hj⟩) }, { tauto }, { intros j hj k hk h, rw [function.on_fun, disjoint_iff_inf_le], intros e he, apply h, simp only [true_and, finset.inf_eq_inter, finset.mem_univ, finset.mem_filter, finset.mem_inter] at he, rw [← he.1, ← he.2] }, end } end simplex_category
adb0a3a80352f99ab5663cb676117236640536f9
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Elab/Quotation.lean
e21187fc4086a7374981363965099ae9bc00c87c
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,478
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term namespace Lean.Elab.Term.Quotation open Lean.Syntax (isQuot isAntiquot) open Meta -- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. def isEscapedAntiquot (stx : Syntax) : Bool := !stx[1].getArgs.isEmpty def unescapeAntiquot (stx : Syntax) : Syntax := if isAntiquot stx then stx.setArg 1 $ mkNullNode stx[1].getArgs.pop else stx def getAntiquotTerm (stx : Syntax) : Syntax := let e := stx[2] if e.isIdent then e else -- `e` is from `"(" >> termParser >> ")"` e[1] def antiquotKind? : Syntax β†’ Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot" _) args => if args[3].isOfKind `antiquotName then some k else -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`) some Name.anonymous | _ => none -- `$e*` is an antiquotation "splice" matching an arbitrary number of syntax nodes def isAntiquotSplice (stx : Syntax) : Bool := isAntiquot stx && stx[4].getOptional?.isSome -- If any item of a `many` node is an antiquotation splice, its result should -- be substituted into the `many` node's children def isAntiquotSplicePat (stx : Syntax) : Bool := stx.isOfKind nullKind && stx.getArgs.any fun arg => isAntiquotSplice arg && !isEscapedAntiquot arg /-- A term like `($e) is actually ambiguous: the antiquotation could be of kind `term`, or `ident`, or ... . But it shouldn't really matter because antiquotations without explicit kinds behave the same at runtime. So we replace `choice` nodes that contain at least one implicit antiquotation with that antiquotation. -/ private partial def elimAntiquotChoices : Syntax β†’ Syntax | Syntax.node `choice args => match args.find? fun arg => antiquotKind? arg == Name.anonymous with | some anti => anti | none => Syntax.node `choice $ args.map elimAntiquotChoices | Syntax.node k args => Syntax.node k $ args.map elimAntiquotChoices | stx => stx -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax β†’ TermElabM Syntax | Syntax.ident info rawVal val preresolved => do -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val let preresolved := r ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident (SourceInfo.mk none none none) $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => do if isAntiquot stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node if isAntiquotSplice stx then throwErrorAt stx "unexpected antiquotation splice" else pure $ getAntiquotTerm stx else let empty ← `(Array.empty); -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let args ← stx.getArgs.foldlM (fun args arg => if k == nullKind && isAntiquotSplice arg then -- antiquotation splice pattern: inject args array `(Array.appendCore $args $(getAntiquotTerm arg)) else do let arg ← quoteSyntax arg; `(Array.push $args $arg)) empty `(Syntax.node $(quote k) $args) | Syntax.atom info val => `(Syntax.atom (SourceInfo.mk none none none) $(quote val)) | Syntax.missing => unreachable! def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do let quoted := stx[1] /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax (elimAntiquotChoices quoted); `(Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ @[builtinTermElab Parser.Level.quot] def elabLevelQuot : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Term.quot] def elabTermQuot : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Term.funBinder.quot] def elabfunBinderQuot : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Tactic.quot] def elabTacticQuot : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Tactic.quotSeq] def elabTacticQuotSeq : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Term.stx.quot] def elabStxQuot : TermElab := adaptExpander stxQuot.expand @[builtinTermElab Parser.Term.doElem.quot] def elabDoElemQuot : TermElab := adaptExpander stxQuot.expand /- match_syntax -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax Γ— Syntax /-- Information on a pattern's head that influences the compilation of a single match step. -/ structure HeadInfo := -- Node kind to match, if any (kind : Option SyntaxNodeKind := none) -- Nested patterns for each argument, if any. In a single match step, we only -- check that the arity matches. The arity is usually implied by the node kind, -- but not in the case of `many` nodes. (argPats : Option (Array Syntax) := none) -- Function to apply to the right-hand side in case the match succeeds. Used to -- bind pattern variables. (rhsFn : Syntax β†’ TermElabM Syntax := pure) instance : Inhabited HeadInfo := ⟨{}⟩ /-- `h1.generalizes h2` iff h1 is equal to or more general than h2, i.e. it matches all nodes h2 matches. This induces a partial ordering. -/ def HeadInfo.generalizes : HeadInfo β†’ HeadInfo β†’ Bool | { kind := none, .. }, _ => true | { kind := some k1, argPats := none, .. }, { kind := some k2, .. } => k1 == k2 | { kind := some k1, argPats := some ps1, .. }, { kind := some k2, argPats := some ps2, .. } => k1 == k2 && ps1.size == ps2.size | _, _ => false private def getHeadInfo (alt : Alt) : HeadInfo := let pat := alt.fst.head!; let unconditional (rhsFn) := { rhsFn := rhsFn : HeadInfo }; -- variable pattern if pat.isIdent then unconditional $ fun rhs => `(let $pat := discr; $rhs) -- wildcard pattern else if pat.isOfKind `Lean.Parser.Term.hole then unconditional pure -- quotation pattern else if isQuot pat then let quoted := pat[1] if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditional pure else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted; -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- match_syntax (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; ... -- else -- let e := stx; ... let kind := if k == Name.anonymous then none else k let anti := getAntiquotTerm quoted -- Splices should only appear inside a nullKind node, see next case if isAntiquotSplice quoted then unconditional $ fun _ => throwErrorAt quoted "unexpected antiquotation splice" else if anti.isIdent then { kind := kind, rhsFn := fun rhs => `(let $anti := discr; $rhs) } else unconditional fun _ => throwErrorAt anti ("match_syntax: antiquotation must be variable " ++ toString anti) else if isAntiquotSplicePat quoted && quoted.getArgs.size == 1 then -- quotation is a single antiquotation splice => bind args array let anti := getAntiquotTerm quoted[0] unconditional fun rhs => `(let $anti := Syntax.getArgs discr; $rhs) -- TODO: support for more complex antiquotation splices else -- not an antiquotation or escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let argPats := quoted.getArgs.map (pat.setArg 1); { kind := quoted.getKind, argPats := argPats } else unconditional $ fun _ => throwErrorAt pat ("match_syntax: unexpected pattern kind " ++ toString pat) -- Assuming that the first pattern of the alternative is taken, replace it with patterns (if any) for its -- child nodes. -- Ex: `($a + (- $b)) => `($a), `(+), `(- $b) -- Note: The atom pattern `(+) will be discarded in a later step private def explodeHeadPat (numArgs : Nat) : HeadInfo Γ— Alt β†’ TermElabM Alt | (info, (pat::pats, rhs)) => do let newPats := match info.argPats with | some argPats => argPats.toList | none => List.replicate numArgs $ Unhygienic.run `(_) let rhs ← info.rhsFn rhs pure (newPats ++ pats, rhs) | _ => unreachable! private partial def compileStxMatch : List Syntax β†’ List Alt β†’ TermElabM Syntax | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => throwError "non-exhaustive 'match_syntax'" | discr::discrs, alts => do let alts := (alts.map getHeadInfo).zip alts; -- Choose a most specific pattern, ie. a minimal element according to `generalizes`. -- If there are multiple minimal elements, the choice does not matter. let (info, alt) := alts.tail!.foldl (fun (min : HeadInfo Γ— Alt) (alt : HeadInfo Γ— Alt) => if min.1.generalizes alt.1 then alt else min) alts.head!; -- introduce pattern matches on the discriminant's children if there are any nested patterns let newDiscrs ← match info.argPats with | some pats => (List.range pats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) | none => pure [] -- collect matching alternatives and explode them let yesAlts := alts.filter fun (alt : HeadInfo Γ— Alt) => alt.1.generalizes info let yesAlts ← yesAlts.mapM $ explodeHeadPat newDiscrs.length -- NOTE: use fresh macro scopes for recursive call so that different `discr`s introduced by the quotations below do not collide let yes ← withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts let some kind ← pure info.kind -- unconditional match step | `(let discr := $discr; $yes) -- conditional match step let noAlts := (alts.filter $ fun (alt : HeadInfo Γ— Alt) => !info.generalizes alt.1).map (Β·.2) let no ← withFreshMacroScope $ compileStxMatch (discr::discrs) noAlts let cond ← match info.argPats with | some pats => `(and (Syntax.isOfKind discr $(quote kind)) (BEq.beq (Array.size (Syntax.getArgs discr)) $(quote pats.size))) | none => `(Syntax.isOfKind discr $(quote kind)) `(let discr := $discr; ite (Eq $cond true) $yes $no) | _, _ => unreachable! private partial def getPatternVarsAux : Syntax β†’ List Syntax | stx@(Syntax.node k args) => if isAntiquot stx && !isEscapedAntiquot stx then let anti := getAntiquotTerm stx if anti.isIdent then [anti] else [] else List.join $ args.toList.map getPatternVarsAux | _ => [] -- Get all pattern vars (as `Syntax.ident`s) in `stx` partial def getPatternVars (stx : Syntax) : List Syntax := if isQuot stx then do let quoted := stx.getArg 1; getPatternVarsAux stx else if stx.isIdent then [stx] else [] -- Transform alternatives by binding all right-hand sides to outside the match_syntax in order to prevent -- code duplication during match_syntax compilation private def letBindRhss (cont : List Alt β†’ TermElabM Syntax) : List Alt β†’ List Alt β†’ TermElabM Syntax | [], altsRev' => cont altsRev'.reverse | (pats, rhs)::alts, altsRev' => do let vars := List.join $ pats.map getPatternVars match vars with -- no antiquotations => introduce Unit parameter to preserve evaluation order | [] => -- NOTE: references binding below let rhs' ← `(rhs ()) -- NOTE: new macro scope so that introduced bindings do not collide let stx ← withFreshMacroScope $ letBindRhss cont alts ((pats, rhs')::altsRev') `(let rhs := fun _ => $rhs; $stx) | _ => -- rhs ← `(fun $vars* => $rhs) let rhs := Syntax.node `Lean.Parser.Term.fun #[mkAtom "fun", Syntax.node `null vars.toArray, mkAtom "=>", rhs] let rhs' ← `(rhs) let stx ← withFreshMacroScope $ letBindRhss cont alts ((pats, rhs')::altsRev') `(let rhs := $rhs; $stx) def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do let discr := stx[1] let alts := stx[3][1] let alts ← alts.getSepArgs.mapM $ fun alt => do let pats := alt.getArg 0; let pat ← if pats.getArgs.size == 1 then pure pats[0] else throwError "match_syntax: expected exactly one pattern per alternative" let pat := if isQuot pat then pat.setArg 1 $ elimAntiquotChoices $ pat[1] else pat match pat.find? $ fun stx => stx.getKind == choiceKind with | some choiceStx => throwErrorAt choiceStx "invalid pattern, nested syntax has multiple interpretations" | none => let rhs := alt.getArg 2 pure ([pat], rhs) -- letBindRhss (compileStxMatch stx [discr]) alts.toList [] compileStxMatch [discr] alts.toList @[builtinTermElab Β«match_syntaxΒ»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand end Lean.Elab.Term.Quotation
5b295f4480c6415588bebf8158976eee46f6c569
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/monotonicity/interactive.lean
7d0091697c6ebc02b7b500ee9dca659dcaea0f64
[ "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
23,578
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.traversable.derive import control.traversable.lemmas import data.dlist import tactic.monotonicity.basic variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab β†’ list (expr elab) β†’ list (expr elab) β†’ mono_function | assoc : expr elab β†’ option (expr elab) β†’ option (expr elab) β†’ mono_function | assoc_comm : expr elab β†’ expr elab β†’ mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function β†’ tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr β†’ expr β†’ expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr β†’ expr β†’ expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }}" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr β†’ expr β†’ expr β†’ tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr β†’ tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr β†’ tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr β†’ list expr β†’ tactic (list expr Γ— list expr Γ— list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (l : list expr) (r : list expr) : tactic (list expr Γ— list expr Γ— list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr β†’ list expr β†’ tactic (list expr Γ— list expr Γ— list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr Γ— list expr Γ— list expr Γ— list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,lβ‚‚,rβ‚‚) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse lβ‚‚,reverse rβ‚‚,reverse suf) meta def check_ac : expr β†’ tactic (bool Γ— bool Γ— option (expr Γ— expr Γ— expr) Γ— expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr β†’ tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr β†’ tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr Γ— expr Γ— expr) β†’ list expr β†’ option (expr Γ— list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,xβ‚€)) [] := some (xβ‚€,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr β†’ option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr β†’ list expr β†’ expr β†’ expr β†’ tactic (expr Γ— list expr Γ— list expr) | xsβ‚€ xs₁ (expr.app fβ‚€ aβ‚€) (expr.app f₁ a₁) := same_function_aux (aβ‚€ :: xsβ‚€) (a₁ :: xs₁) fβ‚€ f₁ | xsβ‚€ xs₁ eβ‚€ e₁ := is_def_eq eβ‚€ e₁ >> return (eβ‚€,xsβ‚€,xs₁) meta def same_function : expr β†’ expr β†’ tactic (expr Γ— list expr Γ— list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr Γ— expr Γ— list expr Γ— mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ Β¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- Β¬ a (xsβ‚€,xβ‚€,x₁,xs₁) ← find_one_difference opt ls rs, return (xβ‚€,x₁,[],mono_function.non_assoc full_f xsβ‚€ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr β†’ tactic (expr Γ— expr Γ— list expr Γ— ac_mono_ctx) | `(%%eβ‚€ β†’ %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function eβ‚€ e₁, tβ‚€ ← infer_type eβ‚€, t₁ ← infer_type e₁, rel_def ← to_expr ``(Ξ» xβ‚€ x₁, (xβ‚€ : %%tβ‚€) β†’ (x₁ : %%t₁)), return (eβ‚€, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%eβ‚€ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function eβ‚€ e₁, tβ‚€ ← infer_type eβ‚€, t₁ ← infer_type e₁, rel_def ← to_expr ``(Ξ» xβ‚€ x₁, (xβ‚€ : %%tβ‚€) = (x₁ : %%t₁)), return (eβ‚€, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel eβ‚€) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function eβ‚€ e₁, return (eβ‚€, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr β†’ expr β†’ expr | none e := e | (some eβ‚€) e₁ := f.mk_app [eβ‚€,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr β†’ option expr β†’ expr | e none := e | eβ‚€ (some e₁) := f.mk_app [eβ‚€,e₁] meta def mk_fun_app : mono_function β†’ expr β†’ expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (lβ‚€,rβ‚€) (r₁,l₁)` gives first how to find rules to prove x+(yβ‚€+z) R x+(y₁+z); if that fails, helps prove (x+yβ‚€)+z R (x+y₁)+z -/ | assoc : expr Γ— expr β†’ expr Γ— expr β†’ mono_law /- `congr r` gives the rule to prove `x = y β†’ f x = f y` -/ | congr : expr β†’ mono_law | other : expr β†’ mono_law meta def mono_law.to_tactic_format : mono_law β†’ tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (xβ‚€,x₁) (yβ‚€,y₁)) := do xβ‚€ ← pp xβ‚€, x₁ ← pp x₁, yβ‚€ ← pp yβ‚€, y₁ ← pp y₁, return format!"assoc {xβ‚€}; {x₁} | {yβ‚€}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr β†’ expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xsβ‚€ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xsβ‚€ ++ l :: xs₁,fn.mk_app $ xsβ‚€ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f xβ‚€ x₁) := if (xβ‚€ <|> x₁).is_some then mk_congr_args f xβ‚€.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f xβ‚€) := mk_congr_args f [xβ‚€] [] ctx.left ctx.right | (mono_function.non_assoc f xβ‚€ x₁) := mk_congr_args f xβ‚€ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (Ξ» i, bin_op f x (bin_op f i y)) , mk_rel ctx (Ξ» i, bin_op f i y)) ( mk_rel ctx (Ξ» i, bin_op f (bin_op f x i) y) , mk_rel ctx (Ξ» i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (Ξ» e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (Ξ» e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (Ξ» e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [ simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)], match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name β†’ tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (xβ‚€ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ β†’ %%xβ‚€), rβ‚€ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> rβ‚€ <*> r₁) meta def find_rule (ls : list name) : mono_law β†’ tactic (list expr) | (mono_law.assoc (xβ‚€,x₁) (yβ‚€,y₁)) := (match_chaining_rules ls xβ‚€ x₁) <|> (match_chaining_rules ls yβ‚€ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {Ξ± : Sort u} (R : Ξ± β†’ Ξ± β†’ Sort v) {x y : Ξ±} (x' y' : Ξ±) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr Γ— expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(Ξ» y : %%t, Ξ  x, y = x β†’ %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Ξ» y : %%t, Ξ  x, %%v = x β†’ %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr β†’ tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (Ξ» v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ Ξ» _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {Ξ± Ξ²} [linear_order Ξ²] (f : Ξ± β†’ Ξ²) : list Ξ± β†’ list Ξ± | [] := [] | (x :: xs) := prod.snd $ xs.foldl (Ξ» ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {Ξ²} (xs : list expr) (tac : expr β†’ tactic Ξ²) : tactic unit := do t ← target, xs ← xs.mmap (Ξ» x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (Ξ» ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" $ list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg), let msg := foldl compose "" lmms, fail format!("ambiguous match: {msg}\n\n" ++ "Tip: try asserting a side condition to distinguish between the lemmas") end meta def mono_aux (dir : parse side) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (Ξ» law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≀ y` or `mono with [0 ≀ x,0 ≀ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≀ w` and `y < z` or - right: `x < w` and `y ≀ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?` To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : β„€) (h : 3 ≀ (4 : β„€)) (h' : z ≀ y) : (k + 3 + x) - y ≀ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊒ k + 3 + x ≀ k + 4 + x mono, -- apply add_le_add, refl -- ⊒ k + 3 ≀ k + 4 mono }, { -- ⊒ -y ≀ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : β„€) (h : 3 ≀ (4 : β„€)) (h' : z ≀ y) : (k + 3 + x) - y ≀ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) : tactic unit := do hyps ← hyps.mmap (Ξ» p, to_expr p >>= mk_meta_var), hyps.mmap' (Ξ» pr, do h ← get_unused_name `h, note h none pr), when (Β¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip), if many.is_some then repeat $ mono_aux dir else mono_aux dir, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x β‰Ό f y` into `x ≀ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ Ξ» asms, do try `[simp only [sub_eq_add_neg]], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (Ξ» rule, do tβ‚€ ← mk_meta_var `(Prop), vβ‚€ ← mk_meta_var tβ‚€, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%vβ‚€ %%v₁), solve_mvar vβ‚€ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat β†’ tactic unit β†’ tactic unit β†’ tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit β†’ tactic unit β†’ tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : β„•) | many meta def repeat_or_not : rep_arity β†’ tactic unit β†’ option (tactic unit) β†’ tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly' n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr βŠ• pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := tk "*" *> pure rep_arity.many <|> 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
fe99ac853bae6ab9b28f491bd8e8660424caa331
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp31.lean
f3fc883aebb5d8c9ce4a8f34c55751bcb28cdaf8
[ "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,037
lean
rewrite_set simple add_rewrite Nat::add_comm Nat::add_left_comm Nat::add_assoc Nat::add_zeror : simple variables a b c : Nat (* function indent(s) for i = 1, s:depth()-1 do io.write(" ") end end local m = simplifier_monitor(function(s, e) print("Visit, depth: " .. s:depth() .. ", " .. tostring(e)) end, function(s, e, new_e, pr) print("Step: " .. tostring(e) .. " ===> " .. tostring(new_e)) end, function(s, e, new_e, ceq, ceq_id) print("Rewrite using: " .. tostring(ceq_id)) print(" " .. tostring(e) .. " ===> " .. tostring(new_e)) end ) local s = simplifier("simple", options(), m) local t = parse_lean('a + (b + 0) + a') print(t) print("=====>") local t2, pr = s(t) print(t2) print(pr) get_environment():type_check(pr) *)
bc69a08ae89d983f00e40c74f5bb18b6dac01eaf
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/ring.lean
82a18559f2a72230089b64eb05f352afdfd485ed
[ "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
30,715
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {Ξ±} [comm_semiring Ξ±] (a x : Ξ±) (n : β„•) (b : Ξ±) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (Ξ± : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (Ξ± : Type) : Type := reader_t cache tactic Ξ± /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : β„•) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m β„• := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (Ξ» n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {Ξ±} (m : tactic Ξ±) : ring_m Ξ± := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := do Ξ± ← infer_type e, u ← mk_meta_univ, infer_type Ξ± >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache Ξ±, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(β„•), using_new_ref ic $ Ξ» r, using_new_ref nc $ Ξ» nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := using_new_ref mk_buffer $ Ξ» atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `Ξ±`, or `β„•` for exponents). -/ @[inline] meta def ic_lift' (icf : cache β†’ ref instance_cache) {Ξ±} (f : instance_cache β†’ tactic (instance_cache Γ— Ξ±)) : ring_m Ξ± := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `Ξ±`. -/ @[inline] meta def ic_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `β„•`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr β†’ expr := (@expr.const tt n [c.univ] c.Ξ± c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `β„•` and `β„š` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : β„š) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr β†’ expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr β†’ bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr (Ξ» _, expr β†’ expr) := ⟨λ e, ⇑(e : expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr β†’ string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr β†’ tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr Γ— expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {Ξ±} [comm_semiring Ξ±] (x n b) : @horner Ξ± _ 0 x n b = b := by simp [horner] theorem horner_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ nβ‚‚ b n') (h : n₁ + nβ‚‚ = n') : @horner Ξ± _ (horner a₁ x n₁ 0) x nβ‚‚ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr β†’ expr Γ— β„• β†’ expr Γ— β„• β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ Ξ» nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {Ξ±} [comm_semiring Ξ±] (k a x n b b') (h : k + b = b') : k + @horner Ξ± _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {Ξ±} [comm_semiring Ξ±] (a x n b k b') (h : b + k = b') : @horner Ξ± _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : n₁ + k = nβ‚‚) (hβ‚‚ : (a₁ + horner aβ‚‚ x k 0 : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x n₁ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : nβ‚‚ + k = n₁) (hβ‚‚ : (horner a₁ x k 0 + aβ‚‚ : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x nβ‚‚ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {Ξ±} [comm_semiring Ξ±] (a₁ x n b₁ aβ‚‚ bβ‚‚ a' b' t) (h₁ : a₁ + aβ‚‚ = a') (hβ‚‚ : b₁ + bβ‚‚ = b') (h₃ : horner a' x n b' = t) : @horner Ξ± _ a₁ x n b₁ + horner aβ‚‚ x n bβ‚‚ = t := by simp [h₃.symm, hβ‚‚.symm, h₁.symm, horner, add_mul, mul_comm (x ^ n)]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := ic_lift $ Ξ» ic, do let n := c₁ + cβ‚‚, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ eβ‚‚ e c₁ cβ‚‚ n, return (ic, const e n, p) | he₁@(const e₁ c₁) heβ‚‚@(xadd eβ‚‚ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``zero_add [eβ‚‚], return (ic, heβ‚‚, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) heβ‚‚@(const eβ‚‚ cβ‚‚) := do c ← get_cache, if cβ‚‚ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b heβ‚‚, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, eβ‚‚, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (b', h) ← eval_add b₁ heβ‚‚, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, b', h]) else if x₁.2 β‰  xβ‚‚.2 then do (b', h) ← eval_add he₁ bβ‚‚, return (xadd' c aβ‚‚ xβ‚‚ nβ‚‚ b', c.cs_app ``const_add_horner [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, b', h]) else if n₁.2 < nβ‚‚.2 then do let k := nβ‚‚.2 - n₁.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek nβ‚‚.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add a₁ (xadd' c aβ‚‚ x₁ (ek, k) (const Ξ±0 0)), (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else if n₁.2 β‰  nβ‚‚.2 then do let k := n₁.2 - nβ‚‚.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc nβ‚‚.1 ek n₁.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add (xadd' c a₁ x₁ (ek, k) (const Ξ±0 0)) aβ‚‚, (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ nβ‚‚ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else do (a', h₁) ← eval_add a₁ aβ‚‚, (b', hβ‚‚) ← eval_add b₁ bβ‚‚, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, aβ‚‚, bβ‚‚, a', b', t, h₁, hβ‚‚, h₃]) theorem horner_neg {Ξ±} [comm_ring Ξ±] (a x n b a' b') (h₁ : -a = a') (hβ‚‚ : -b = b') : -@horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', hβ‚‚) ← eval_neg b, p ← ic_lift $ Ξ» ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, hβ‚‚], return (xadd' c a' x n b', p) theorem horner_const_mul {Ξ±} [comm_semiring Ξ±] (c a x n b a' b') (h₁ : c * a = a') (hβ‚‚ : c * b = b') : c * @horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {Ξ±} [comm_semiring Ξ±] (a x n b c a' b') (h₁ : a * c = a') (hβ‚‚ : b * c = b') : @horner Ξ± _ a x n b * c = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr Γ— β„š) : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', hβ‚‚) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, hβ‚‚]) theorem horner_mul_horner_zero {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ aa t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ 0 = t := by rw [← hβ‚‚, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ aa haa ab bb t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = haa) (h₃ : a₁ * bβ‚‚ = ab) (hβ‚„ : b₁ * bβ‚‚ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ bβ‚‚ = t := by rw [← H, ← hβ‚‚, ← h₁, ← h₃, ← hβ‚„]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic e₁ eβ‚‚ c₁ cβ‚‚, return (const e' (c₁ * cβ‚‚), p) | (const e₁ c₁) eβ‚‚ := if c₁ = 0 then do c ← get_cache, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ Ξ» ic, ic.mk_app ``zero_mul [eβ‚‚], return (const Ξ±0 0, p) else if c₁ = 1 then do p ← ic_lift $ Ξ» ic, ic.mk_app ``one_mul [eβ‚‚], return (eβ‚‚, p) else eval_const_mul (e₁, c₁) eβ‚‚ | e₁ heβ‚‚@(const eβ‚‚ cβ‚‚) := do p₁ ← ic_lift $ Ξ» ic, ic.mk_app ``mul_comm [e₁, eβ‚‚], (e', pβ‚‚) ← eval_mul heβ‚‚ e₁, p ← lift $ mk_eq_trans p₁ pβ‚‚, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (a', h₁) ← eval_mul a₁ heβ‚‚, (b', hβ‚‚) ← eval_mul b₁ heβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, a', b', h₁, hβ‚‚]) else if x₁.2 β‰  xβ‚‚.2 then do (a', h₁) ← eval_mul he₁ aβ‚‚, (b', hβ‚‚) ← eval_mul he₁ bβ‚‚, return (xadd' c a' xβ‚‚ nβ‚‚ b', c.cs_app ``horner_const_mul [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, a', b', h₁, hβ‚‚]) else do (aa, h₁) ← eval_mul he₁ aβ‚‚, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (haa, hβ‚‚) ← eval_horner aa x₁ nβ‚‚ (const Ξ±0 0), if bβ‚‚.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, aa, haa, h₁, hβ‚‚]) else do (ab, h₃) ← eval_mul a₁ bβ‚‚, (bb, hβ‚„) ← eval_mul b₁ bβ‚‚, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, aa, haa, ab, bb, t, h₁, hβ‚‚, h₃, hβ‚„, H]) theorem horner_pow {Ξ±} [comm_semiring Ξ±] (a x n m n' a') (h₁ : n * m = n') (hβ‚‚ : a ^ m = a') : @horner Ξ± _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, hβ‚‚.symm, horner, mul_pow, pow_mul] theorem pow_succ {Ξ±} [comm_semiring Ξ±] (a n b c) (h₁ : (a:Ξ±) ^ n = b) (hβ‚‚ : b * a = c) : a ^ (n + 1) = c := by rw [← hβ‚‚, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr β†’ expr Γ— β„• β†’ ring_m (horner_expr Γ— expr) | e (_, 0) := do c ← get_cache, Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_zero [e], return (const Ξ±1 1, p) | e (_, 1) := do p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (eβ‚‚, m) := ic_lift $ Ξ» ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic eβ‚‚, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ Ξ» nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', hβ‚‚) ← eval_pow a m, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const Ξ±0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, hβ‚‚]) | _ := do eβ‚‚ ← nc_lift $ Ξ» nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (eβ‚‚, m.2-1), (t, pβ‚‚) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, eβ‚‚, tl, t, hl, pβ‚‚]) end theorem horner_atom {Ξ±} [comm_semiring Ξ±] (x : Ξ±) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr Γ— expr) := do c ← get_cache, i ← add_atom e, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], return (xadd' c (const Ξ±1 1) (e, i) (`(1), 1) (const Ξ±0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {Ξ±} [monoid Ξ±] (l r tl tr t) (prl : (l : Ξ±) = tl) (prr : (r : β„•) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {Ξ±} [division_ring Ξ±] (a b c : Ξ±) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr β†’ ring_m (horner_expr Γ— expr) | `(%%e₁ + %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_add e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_add [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(@has_sub.sub %%Ξ± %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (lift $ mk_app ``comm_ring [Ξ±] >>= mk_instance)) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_neg.neg [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_add.add [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_sub [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (eβ‚‚, pβ‚‚) ← eval_neg e₁, p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, eβ‚‚, p₁, pβ‚‚], return (eβ‚‚, p) | `(%%e₁ * %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_mul e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_mul [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (do inst' ← ic_lift $ Ξ» ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_inv.inv [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_mul.mul [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_div [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%eβ‚‚) := do (eβ‚‚', pβ‚‚) ← lift $ norm_num.derive eβ‚‚ <|> refl_conv eβ‚‚, match eβ‚‚'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (eβ‚‚, k), p ← ic_lift $ Ξ» ic, ic.mk_app ``subst_into_pow [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (e : expr) : tactic (expr Γ— expr) := ring_m.run' red atoms e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {Ξ±} [comm_semiring Ξ±] (a x n b) : @horner Ξ± _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {Ξ±} [semigroup Ξ±] (a b c : Ξ±) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {Ξ±} [monoid Ξ±] (a : Ξ±) (m n : β„•) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {Ξ±} [monoid Ξ±] (a b : Ξ±) (m n : β„•) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {Ξ±} [add_group Ξ±] (a b : Ξ±) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive [has_reflect, decidable_eq]] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. See `normalize`. This version takes a list of atoms to persist across multiple calls. -/ meta def normalize' (atoms : ref (buffer expr)) (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ— expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, trans_conv (Ξ» e, do guard (mode β‰  normalize_mode.raw), (e', pr, _) ← simplify simp_lemmas.mk [] e, pure (e', pr)) (Ξ» e, do a ← read_ref atoms, (a, e', pr) ← ext_simplify_core a {} simp_lemmas.mk (Ξ» _, failed) (Ξ» a _ _ _ e, do write_ref atoms a, (new_e, pr) ← eval' red atoms e, (new_e, pr) ← match mode with | normalize_mode.raw := Ξ» _, pure (new_e, pr) | normalize_mode.horner := trans_conv (Ξ» _, pure (new_e, pr)) (Ξ» e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) | normalize_mode.SOP := trans_conv (Ξ» _, pure (new_e, pr)) $ trans_conv (Ξ» e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) $ simp_bottom_up' (Ξ» e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (Β¬ new_e =ₐ e), a ← read_ref atoms, pure (a, new_e, some pr, ff)) (Ξ» _ _ _ _ _, failed) `eq e, write_ref atoms a, pure (e', pr)) e /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ— expr) := using_new_ref mk_buffer $ Ξ» atoms, normalize' atoms red mode e end ring namespace interactive open tactic.ring setup_tactic_parser /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%eβ‚‚) ← target >>= instantiate_mvars, ((e₁', p₁), (eβ‚‚', pβ‚‚)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval eβ‚‚, is_def_eq e₁' eβ‚‚', p ← mk_eq_symm pβ‚‚ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring_nf`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := pure ring.normalize_mode.horner | some `horner := pure ring.normalize_mode.horner | some `SOP := pure ring.normalize_mode.SOP | some `raw := pure ring.normalize_mode.raw | _ := failed end /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. When writing a normal form, `ring_nf SOP` will use sum-of-products form instead of horner form. `ring_nf!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring_nf (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← using_new_ref mk_buffer $ Ξ» atoms, tactic.replace_at (normalize' atoms transp SOP) ns loc.include_goal | fail "ring_nf failed to simplify", when loc.include_goal $ try tactic.reflexivity /-- Tactic for solving equations in the language of *commutative* (semi)rings. `ring!` will use a more aggressive reducibility setting to identify atoms. If the goal is not solvable, it falls back to rewriting all ring expressions into a normal form, with a suggestion to use `ring_nf` instead, if this is the intent. See also `ring1`, which is the same as `ring` but without the fallback behavior. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin GrΓ©goire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) : tactic unit := ring1 red <|> (ring_nf red normalize_mode.horner (loc.ns [none]) >> trace "Try this: ring_nf") add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [``ring, ``ring_nf, ``ring1], inherit_description_from := ``ring, tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize normalize_mode.horner) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring_nf (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in replace_lhs (normalize transp SOP) <|> fail "ring_nf failed to simplify" /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> (replace_lhs (normalize transp normalize_mode.horner) >> trace "Try this: ring_nf") <|> fail "ring failed to simplify" end conv.interactive
be211b8b3fdd4d6938a90c37ea5a3018f09459d8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/multilinear/finite_dimensional.lean
aa328791e6c389e284492f43e9b1f0a9e2438bf1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,762
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.multilinear.basic import linear_algebra.free_module.finite.matrix /-! # Multilinear maps over finite dimensional spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The main results are that multilinear maps over finitely-generated, free modules are finitely-generated and free. * `module.finite.multilinear_map` * `module.free.multilinear_map` We do not put this in `linear_algebra/multilinear_map/basic` to avoid making the imports too large there. -/ namespace multilinear_map variables {ΞΉ R Mβ‚‚ : Type*} {M₁ : ΞΉ β†’ Type*} variables [finite ΞΉ] variables [comm_ring R] [add_comm_group Mβ‚‚] [module R Mβ‚‚] variables [Ξ  i, add_comm_group (M₁ i)] [Ξ  i, module R (M₁ i)] variables [module.finite R Mβ‚‚] [module.free R Mβ‚‚] variables [βˆ€ i, module.finite R (M₁ i)] [βˆ€ i, module.free R (M₁ i)] -- the induction requires us to show both at once private lemma free_and_finite : module.free R (multilinear_map R M₁ Mβ‚‚) ∧ module.finite R (multilinear_map R M₁ Mβ‚‚) := begin -- the `fin n` case is sufficient suffices : βˆ€ n (N : fin n β†’ Type*) [Ξ  i, add_comm_group (N i)], by exactI βˆ€ [Ξ  i, module R (N i)], by exactI βˆ€ [βˆ€ i, module.finite R (N i)] [βˆ€ i, module.free R (N i)], module.free R (multilinear_map R N Mβ‚‚) ∧ module.finite R (multilinear_map R N Mβ‚‚), { casesI nonempty_fintype ΞΉ, casesI this _ (M₁ ∘ (fintype.equiv_fin ΞΉ).symm), have e := dom_dom_congr_linear_equiv' R M₁ Mβ‚‚ (fintype.equiv_fin ΞΉ), exact ⟨module.free.of_equiv e.symm, module.finite.equiv e.symm⟩, }, introsI n N _ _ _ _, unfreezingI { induction n with n ih }, { exact ⟨module.free.of_equiv (const_linear_equiv_of_is_empty R N Mβ‚‚), module.finite.equiv (const_linear_equiv_of_is_empty R N Mβ‚‚)⟩ }, { suffices : module.free R (N 0 β†’β‚—[R] multilinear_map R (Ξ» (i : fin n), N i.succ) Mβ‚‚) ∧ module.finite R (N 0 β†’β‚—[R] multilinear_map R (Ξ» (i : fin n), N i.succ) Mβ‚‚), { casesI this, exact ⟨module.free.of_equiv (multilinear_curry_left_equiv R N Mβ‚‚), module.finite.equiv (multilinear_curry_left_equiv R N Mβ‚‚)⟩ }, casesI ih (Ξ» i, N i.succ), exact ⟨module.free.linear_map _ _ _, module.finite.linear_map _ _⟩ }, end instance _root_.module.finite.multilinear_map : module.finite R (multilinear_map R M₁ Mβ‚‚) := free_and_finite.2 instance _root_.module.free.multilinear_map : module.free R (multilinear_map R M₁ Mβ‚‚) := free_and_finite.1 end multilinear_map
ddd254b9945763f22e2cb83d1ab332306e9a0b92
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/group/units.lean
67e2461a0891796d27a8cfcfe1fecf23aba2c52e
[ "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
20,022
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, Jon Eugster -/ import algebra.group.basic import logic.unique import tactic.nontriviality /-! # Units (i.e., invertible elements) of a monoid > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An element of a `monoid` is a unit if it has a two-sided inverse. ## Main declarations * `units M`: the group of units (i.e., invertible elements) of a monoid. * `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid. For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`. ## Notation We provide `MΛ£` as notation for `units M`, resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics. -/ open function universe u variable {Ξ± : Type u} /-- Units of a `monoid`, bundled version. Notation: `Ξ±Λ£`. 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 Ξ±] := (val : Ξ±) (inv : Ξ±) (val_inv : val * inv = 1) (inv_val : inv * val = 1) postfix `Λ£`:1025 := units -- We don't provide notation for the additive version, because its use is somewhat rare. /-- 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 Ξ±] := (val : Ξ±) (neg : Ξ±) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive] units section has_elem @[to_additive] lemma unique_has_one {Ξ± : Type*} [unique Ξ±] [has_one Ξ±] : default = (1 : Ξ±) := unique.default_eq 1 end has_elem namespace units variables [monoid Ξ±] @[to_additive] instance : has_coe Ξ±Λ£ Ξ± := ⟨val⟩ @[to_additive] instance : has_inv Ξ±Λ£ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : Ξ±Λ£) : Ξ± := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : Ξ±Λ£) : Ξ± := ↑(u⁻¹) initialize_simps_projections units (val β†’ coe as_prefix, inv β†’ coe_inv as_prefix) initialize_simps_projections add_units (val β†’ coe as_prefix, neg β†’ coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : Ξ±) (b h₁ hβ‚‚) : ↑(units.mk a b h₁ hβ‚‚) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : Ξ±Λ£ β†’ Ξ±) | ⟨v, i₁, vi₁, ivβ‚βŸ© ⟨v', iβ‚‚, viβ‚‚, ivβ‚‚βŸ© e := by change v = v' at e; subst v'; congr; simpa only [ivβ‚‚, vi₁, one_mul, mul_one] using mul_assoc iβ‚‚ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : Ξ±Λ£} : (a : Ξ±) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : Ξ±Λ£} : a = b ↔ (a : Ξ±) = b := eq_iff.symm @[to_additive] instance [decidable_eq Ξ±] : decidable_eq Ξ±Λ£ := Ξ» a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : Ξ±Λ£) (y h₁ hβ‚‚) : mk (u : Ξ±) y h₁ hβ‚‚ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : Ξ±Λ£) (val : Ξ±) (hv : val = u) (inv : Ξ±) (hi : inv = ↑(u⁻¹)) : Ξ±Λ£ := { val := val, inv := inv, inv_val := hv.symm β–Έ hi.symm β–Έ u.inv_val, val_inv := hv.symm β–Έ hi.symm β–Έ u.val_inv } @[to_additive] lemma copy_eq (u : Ξ±Λ£) (val hv inv hi) : u.copy val hv inv hi = u := ext hv @[to_additive] instance : mul_one_class Ξ±Λ£ := { mul := Ξ» u₁ uβ‚‚, ⟨u₁.val * uβ‚‚.val, uβ‚‚.inv * u₁.inv, by rw [mul_assoc, ←mul_assoc uβ‚‚.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ←mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, one_mul := Ξ» u, ext $ one_mul u, mul_one := Ξ» u, ext $ mul_one u } /-- Units of a monoid form a group. -/ @[to_additive "Additive units of an additive monoid form an additive group."] instance : group Ξ±Λ£ := { mul := (*), one := 1, mul_assoc := Ξ» u₁ uβ‚‚ u₃, ext $ mul_assoc u₁ uβ‚‚ u₃, inv := has_inv.inv, mul_left_inv := Ξ» u, ext u.inv_val, ..units.mul_one_class } @[to_additive] instance {Ξ±} [comm_monoid Ξ±] : comm_group Ξ±Λ£ := { mul_comm := Ξ» u₁ uβ‚‚, ext $ mul_comm _ _, ..units.group } @[to_additive] instance : inhabited Ξ±Λ£ := ⟨1⟩ @[to_additive] instance [has_repr Ξ±] : has_repr Ξ±Λ£ := ⟨repr ∘ val⟩ variables (a b c : Ξ±Λ£) {u : Ξ±Λ£} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : Ξ±) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : Ξ±Λ£) : Ξ±) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : Ξ±Λ£} : (a : Ξ±) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : Ξ±) (h₁ hβ‚‚) : (mk x y h₁ hβ‚‚)⁻¹ = mk y x hβ‚‚ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : Ξ±) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : Ξ±Λ£) : Ξ±) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : Ξ±) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : Ξ±) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {a : Ξ±} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by rw [←h, u.inv_mul] @[to_additive] lemma mul_inv_of_eq {a : Ξ±} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by rw [←h, u.mul_inv] @[simp, to_additive] lemma mul_inv_cancel_left (a : Ξ±Λ£) (b : Ξ±) : (a:Ξ±) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : Ξ±Λ£) (b : Ξ±) : (↑a⁻¹:Ξ±) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : Ξ±) (b : Ξ±Λ£) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : Ξ±) (b : Ξ±Λ£) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[simp, to_additive] theorem mul_right_inj (a : Ξ±Λ£) {b c : Ξ±} : (a:Ξ±) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : Ξ±Λ£)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : Ξ±Λ£) {b c : Ξ±} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : Ξ±Λ£)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : Ξ±} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], Ξ» h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : Ξ±} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], Ξ» h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : Ξ±} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], Ξ» h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : Ξ±} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], Ξ» h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] protected lemma inv_eq_of_mul_eq_one_left {a : Ξ±} (h : a * u = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = 1 * ↑u⁻¹ : by rw one_mul ... = a : by rw [←h, mul_inv_cancel_right] @[to_additive] protected lemma inv_eq_of_mul_eq_one_right {a : Ξ±} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = a : by rw [←h, inv_mul_cancel_left] @[to_additive] protected lemma eq_inv_of_mul_eq_one_left {a : Ξ±} (h : ↑u * a = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_right h).symm @[to_additive] protected lemma eq_inv_of_mul_eq_one_right {a : Ξ±} (h : a * u = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_left h).symm @[simp, to_additive] lemma mul_inv_eq_one {a : Ξ±} : a * ↑u⁻¹ = 1 ↔ a = u := ⟨inv_inv u β–Έ units.eq_inv_of_mul_eq_one_right, Ξ» h, mul_inv_of_eq h.symm⟩ @[simp, to_additive] lemma inv_mul_eq_one {a : Ξ±} : ↑u⁻¹ * a = 1 ↔ ↑u = a := ⟨inv_inv u β–Έ units.inv_eq_of_mul_eq_one_right, inv_mul_of_eq⟩ @[to_additive] lemma mul_eq_one_iff_eq_inv {a : Ξ±} : a * u = 1 ↔ a = ↑u⁻¹ := by rw [←mul_inv_eq_one, inv_inv] @[to_additive] lemma mul_eq_one_iff_inv_eq {a : Ξ±} : ↑u * a = 1 ↔ ↑u⁻¹ = a := by rw [←inv_mul_eq_one, inv_inv] @[to_additive] lemma inv_unique {u₁ uβ‚‚ : Ξ±Λ£} (h : (↑u₁ : Ξ±) = ↑uβ‚‚) : (↑u₁⁻¹ : Ξ±) = ↑u₂⁻¹ := units.inv_eq_of_mul_eq_one_right $ by rw [h, uβ‚‚.mul_inv] @[simp, to_additive] lemma coe_inv {M : Type*} [division_monoid M] (u : units M) : ↑u⁻¹ = (u⁻¹ : M) := eq.symm $ inv_eq_of_mul_eq_one_right u.mul_inv end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid Ξ±] (a b : Ξ±) (hab : a * b = 1) : Ξ±Λ£ := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid Ξ±] {a b : Ξ±} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : Ξ±) = a := rfl section monoid variables [monoid Ξ±] {a b c : Ξ±} /-- 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 (a : Ξ±) (u) : Ξ± := a * (u⁻¹ : Ξ±Λ£) infix ` /β‚š `:70 := divp @[simp] theorem divp_self (u : Ξ±Λ£) : (u : Ξ±) /β‚š u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : Ξ±) : a /β‚š 1 = a := mul_one _ theorem divp_assoc (a b : Ξ±) (u : Ξ±Λ£) : a * b /β‚š u = a * (b /β‚š u) := mul_assoc _ _ _ /-- `field_simp` needs the reverse direction of `divp_assoc` to move all `/β‚š` to the right. -/ @[field_simps] lemma divp_assoc' (x y : Ξ±) (u : Ξ±Λ£) : x * (y /β‚š u) = (x * y) /β‚š u := (divp_assoc _ _ _).symm @[simp] theorem divp_inv (u : Ξ±Λ£) : a /β‚š u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : Ξ±) (u : Ξ±Λ£) : a /β‚š u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : Ξ±) (u : Ξ±Λ£) : (a * u) /β‚š u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : Ξ±Λ£) {a b : Ξ±} : a /β‚š u = b /β‚š u ↔ a = b := units.mul_left_inj _ @[field_simps] theorem divp_divp_eq_divp_mul (x : Ξ±) (u₁ uβ‚‚ : Ξ±Λ£) : (x /β‚š u₁) /β‚š uβ‚‚ = x /β‚š (uβ‚‚ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] @[field_simps] theorem divp_eq_iff_mul_eq {x : Ξ±} {u : Ξ±Λ£} {y : Ξ±} : x /β‚š u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ @[field_simps] theorem eq_divp_iff_mul_eq {x : Ξ±} {u : Ξ±Λ£} {y : Ξ±} : x = y /β‚š u ↔ x * u = y := by rw [eq_comm, divp_eq_iff_mul_eq] theorem divp_eq_one_iff_eq {a : Ξ±} {u : Ξ±Λ£} : a /β‚š u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : Ξ±Λ£) : 1 /β‚š u = ↑u⁻¹ := one_mul _ /-- Used for `field_simp` to deal with inverses of units. -/ @[field_simps] lemma inv_eq_one_divp (u : Ξ±Λ£) : ↑u⁻¹ = 1 /β‚š u := by rw one_divp /-- Used for `field_simp` to deal with inverses of units. This form of the lemma is essential since `field_simp` likes to use `inv_eq_one_div` to rewrite `↑u⁻¹ = ↑(1 / u)`. -/ @[field_simps] lemma inv_eq_one_divp' (u : Ξ±Λ£) : ((1 / u : Ξ±Λ£) : Ξ±) = 1 /β‚š u := by rw [one_div, one_divp] /-- `field_simp` moves division inside `Ξ±Λ£` to the right, and this lemma lifts the calculation to `Ξ±`. -/ @[field_simps] lemma coe_div_eq_divp (u₁ uβ‚‚ : Ξ±Λ£) : ↑(u₁ / uβ‚‚) = ↑u₁ /β‚š uβ‚‚ := by rw [divp, division_def, units.coe_mul] end monoid section comm_monoid variables [comm_monoid Ξ±] @[field_simps] theorem divp_mul_eq_mul_divp (x y : Ξ±) (u : Ξ±Λ£) : x /β‚š u * y = x * y /β‚š u := by simp_rw [divp, mul_assoc, mul_comm] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_eq_divp_iff {x y : Ξ±} {ux uy : Ξ±Λ£} : x /β‚š ux = y /β‚š uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, divp_mul_eq_mul_divp, divp_eq_iff_mul_eq] -- Theoretically redundant as `field_simp` lemma. @[field_simps] lemma divp_mul_divp (x y : Ξ±) (ux uy : Ξ±Λ£) : (x /β‚š ux) * (y /β‚š uy) = (x * y) /β‚š (ux * uy) := by rw [divp_mul_eq_mul_divp, divp_assoc', divp_divp_eq_divp_mul] end comm_monoid /-! # `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`. -/ section is_unit variables {M : Type*} {N : Type*} /-- 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 : MΛ£`, where `MΛ£` is a bundled version of `is_unit`. -/ @[to_additive "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := βˆƒ u : MΛ£, (u : M) = a @[nontriviality, to_additive] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ attribute [nontriviality] is_add_unit_of_subsingleton @[to_additive] instance [monoid M] : can_lift M MΛ£ coe is_unit := { prf := Ξ» _, id } @[to_additive] instance [monoid M] [subsingleton M] : unique MΛ£ := { default := 1, uniq := Ξ» a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : MΛ£) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : βˆƒ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : βˆƒ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ βˆƒ b, a * b = 1 := ⟨λ h, h.exists_right_inv, Ξ» ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ βˆƒ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x β†’ is_unit y β†’ is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } /-- Multiplication by a `u : MΛ£` on the right doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the right doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : MΛ£) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (Ξ» v, v.mul u.is_unit) /-- Multiplication by a `u : MΛ£` on the left doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."] theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : MΛ£) (a : M) : is_unit (↑u * a) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul], by rwa [←mul_assoc, units.inv_mul, one_mul] at this) u.is_unit.mul @[to_additive] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm namespace is_unit @[simp, to_additive] lemma mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, Ξ» h, is_unit.mul h.1 h.2⟩ section monoid variables [monoid M] {a b c : M} /-- The element of the group of units, corresponding to an element of a monoid which is a unit. When `Ξ±` is a `division_monoid`, use `is_unit.unit'` instead. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit. When `Ξ±` is a `subtraction_monoid`, use `is_add_unit.add_unit'` instead."] protected noncomputable def unit (h : is_unit a) : MΛ£ := (classical.some h).copy a (classical.some_spec h).symm _ rfl @[simp, to_additive] lemma unit_of_coe_units {a : MΛ£} (h : is_unit (a : M)) : h.unit = a := units.ext $ rfl @[simp, to_additive] lemma unit_spec (h : is_unit a) : ↑h.unit = a := rfl @[simp, to_additive] lemma coe_inv_mul (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ @[simp, to_additive] lemma mul_coe_inv (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := by convert h.unit.mul_inv /-- `is_unit x` is decidable if we can decide if `x` comes from `MΛ£`. -/ instance (x : M) [h : decidable (βˆƒ u : MΛ£, ↑u = x)] : decidable (is_unit x) := h @[to_additive] lemma mul_left_inj (h : is_unit a) : b * a = c * a ↔ b = c := let ⟨u, hu⟩ := h in hu β–Έ u.mul_left_inj @[to_additive] lemma mul_right_inj (h : is_unit a) : a * b = a * c ↔ b = c := let ⟨u, hu⟩ := h in hu β–Έ u.mul_right_inj @[to_additive] protected lemma mul_left_cancel (h : is_unit a) : a * b = a * c β†’ b = c := h.mul_right_inj.1 @[to_additive] protected lemma mul_right_cancel (h : is_unit b) : a * b = c * b β†’ a = c := h.mul_left_inj.1 @[to_additive] protected lemma mul_right_injective (h : is_unit a) : injective ((*) a) := Ξ» _ _, h.mul_left_cancel @[to_additive] protected lemma mul_left_injective (h : is_unit b) : injective (* b) := Ξ» _ _, h.mul_right_cancel end monoid variables [division_monoid M] {a : M} @[simp, to_additive] protected lemma inv_mul_cancel : is_unit a β†’ a⁻¹ * a = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.inv_mul] } @[simp, to_additive] protected lemma mul_inv_cancel : is_unit a β†’ a * a⁻¹ = 1 := by { rintro ⟨u, rfl⟩, rw [← units.coe_inv, units.mul_inv] } end is_unit -- namespace end is_unit -- section section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : βˆ€ (a : M), is_unit a) : group M := { inv := Ξ» a, ↑((h a).unit)⁻¹, mul_left_inv := Ξ» a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : βˆ€ (a : M), is_unit a) : comm_group M := { inv := Ξ» a, ↑((h a).unit)⁻¹, mul_left_inv := Ξ» a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
58a82c3beebc03771353102cf0244e81fdfe95ba
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/skeleton.lean
d708628898324ef901ee896525892e655701f772
[ "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
1,748
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.monoidal.functor import category_theory.monoidal.braided import category_theory.monoidal.transport import category_theory.skeletal /-! # The monoid on the skeleton of a monoidal category The skeleton of a monoidal category is a monoid. -/ namespace category_theory open monoidal_category universes v u variables {C : Type u} [category.{v} C] [monoidal_category C] /-- If `C` is monoidal and skeletal, it is a monoid. -/ def monoid_of_skeletal_monoidal (hC : skeletal C) : monoid C := { mul := Ξ» X Y, (X βŠ— Y : C), one := (πŸ™_ C : C), one_mul := Ξ» X, hC ⟨λ_ X⟩, mul_one := Ξ» X, hC ⟨ρ_ X⟩, mul_assoc := Ξ» X Y Z, hC ⟨α_ X Y Z⟩ } /-- If `C` is braided and skeletal, it is a commutative monoid. -/ def comm_monoid_of_skeletal_braided [braided_category C] (hC : skeletal C) : comm_monoid C := { mul_comm := Ξ» X Y, hC ⟨β_ X Y⟩, ..monoid_of_skeletal_monoidal hC } /-- The skeleton of a monoidal category has a monoidal structure itself, induced by the equivalence. -/ noncomputable instance : monoidal_category (skeleton C) := monoidal.transport (from_skeleton C).as_equivalence.symm /-- The skeleton of a monoidal category can be viewed as a monoid, where the multiplication is given by the tensor product, and satisfies the monoid axioms since it is a skeleton. -/ noncomputable instance : monoid (skeleton C) := monoid_of_skeletal_monoidal (skeleton_is_skeleton _).skel -- TODO: Transfer the braided structure to the skeleton of C along the equivalence, and show that -- the skeleton is a commutative monoid. end category_theory
d9be232f154f40464662c15c0f60aa6f56dc3d90
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/nested_begin.lean
44533be5d01df17a6539482b68be49b89872140a
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,272
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat β†’ Type := | vnil : vector A zero | vcons : Ξ  {n : nat}, A β†’ vector A n β†’ vector A (succ n) namespace vector definition no_confusion2 {A : Type} {n : nat} {P : Type} {v₁ vβ‚‚ : vector A n} : v₁ = vβ‚‚ β†’ vector.no_confusion_type P v₁ vβ‚‚ := assume H₁₂ : v₁ = vβ‚‚, begin show vector.no_confusion_type P v₁ vβ‚‚, from have aux : v₁ = v₁ β†’ vector.no_confusion_type P v₁ v₁, from take H₁₁, begin apply (vector.cases_on v₁), exact (assume h : P, h), intros (n, a, v, h), apply (h rfl), repeat (apply rfl), repeat (apply heq.refl) end, eq.rec_on H₁₂ aux H₁₂ end theorem vcons.inj₁ {A : Type} {n : nat} (a₁ aβ‚‚ : A) (v₁ vβ‚‚ : vector A n) : vcons a₁ v₁ = vcons aβ‚‚ vβ‚‚ β†’ a₁ = aβ‚‚ := begin intro h, apply (vector.no_confusion h), intros, assumption end theorem vcons.injβ‚‚ {A : Type} {n : nat} (a₁ aβ‚‚ : A) (v₁ vβ‚‚ : vector A n) : vcons a₁ v₁ = vcons aβ‚‚ vβ‚‚ β†’ v₁ == vβ‚‚ := begin intro h, apply (vector.no_confusion h), intros, eassumption end end vector
476f527fc033e22831508d8d032d38d526d27b66
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/group5.lean
9cb0f67c0fa2efda4cfd3f48f941bc13c4f37cae
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,000
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 -- algebra.group -- ============= -- Various structures with 1, *, inv, including groups. import logic.eq import data.unit data.sigma data.prod import algebra.function algebra.binary open eq namespace algebra structure has_mul [class] (A : Type) := (mul : A β†’ A β†’ A) structure has_one [class] (A : Type) := (one : A) structure has_inv [class] (A : Type) := (inv : A β†’ A) infixl `*` := has_mul.mul postfix `⁻¹` := has_inv.inv notation 1 := !has_one.one structure semigroup [class] (A : Type) extends has_mul A := (assoc : βˆ€ a b c, mul (mul a b) c = mul a (mul b c)) set_option pp.notation false -- set_option pp.implicit true -- set_option pp.coercions true print instances has_mul section variables {A : Type} [s : semigroup A] include s variables a b : A example : a * b = semigroup.mul a b := rfl theorem mul_assoc (a b c : A) : a * b * c = a * (b * c) := semigroup.assoc a b c end structure comm_semigroup [class] (A : Type) extends semigroup A := (comm : βˆ€a b, mul a b = mul b a) namespace comm_semigroup variables {A : Type} [s : comm_semigroup A] include s variables a b c : A theorem mul_comm : a * b = b * a := !comm_semigroup.comm theorem mul_left_comm : a * (b * c) = b * (a * c) := binary.left_comm mul_comm mul_assoc a b c end comm_semigroup structure monoid [class] (A : Type) extends semigroup A, has_one A := (right_id : βˆ€a, mul a one = a) (left_id : βˆ€a, mul one a = a) section variables {A : Type} [s : monoid A] variable a : A include s theorem mul_right_id : a * 1 = a := !monoid.right_id theorem mul_left_id : 1 * a = a := !monoid.left_id end structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] end algebra open algebra section examples theorem test1 {S : Semigroup} (a b c d : S) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : {symm !mul_assoc} ... = a * b * (c * d) : !mul_assoc theorem test2 {M : CommSemigroup} (a b : M) : a * b = a * b := rfl theorem test3 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : {symm !mul_assoc} ... = a * b * (c * d) : !mul_assoc -- for test4b to work, we need instances at the level of the bundled structures as well definition Monoid_Semigroup [coercion] [reducible] (M : Monoid) : Semigroup := Semigroup.mk (Monoid.carrier M) _ theorem test4 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := test1 a b c d theorem test5 {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test5a {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test5b {A : Type} {M : monoid A} (a b c : A) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test6 {M : CommMonoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc end examples
68a388ac6dc691711ef7bc942789a4a99285182e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/instances/complex.lean
75703c48bfa49c422f04193a06a7939e68594674
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
6,119
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Topology of the complex numbers. -/ import data.complex.basic topology.metric_space.basic topology.instances.real noncomputable theory open filter metric open_locale topological_space namespace complex -- TODO(Mario): these proofs are all copied from analysis/real. Generalize -- to normed fields instance : metric_space β„‚ := { dist := Ξ»x y, (x - y).abs, dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [sub_eq_zero], dist_comm := assume x y, complex.abs_sub _ _, dist_triangle := assume x y z, complex.abs_sub_le _ _ _ } theorem dist_eq (x y : β„‚) : dist x y = (x - y).abs := rfl theorem uniform_continuous_add : uniform_continuous (Ξ»p : β„‚ Γ— β„‚, p.1 + p.2) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, let ⟨δ, Ξ΄0, Hδ⟩ := rat_add_continuous_lemma abs Ξ΅0 in ⟨δ, Ξ΄0, Ξ» a b h, let ⟨h₁, hβ‚‚βŸ© := max_lt_iff.1 h in HΞ΄ h₁ hβ‚‚βŸ© theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg β„‚ _) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, ⟨_, Ξ΅0, Ξ» a b h, by rw dist_comm at h; simpa [dist_eq] using h⟩ instance : uniform_add_group β„‚ := uniform_add_group.mk' uniform_continuous_add uniform_continuous_neg instance : topological_add_group β„‚ := by apply_instance -- short-circuit type class inference lemma uniform_continuous_inv (s : set β„‚) {r : ℝ} (r0 : 0 < r) (H : βˆ€ x ∈ s, r ≀ abs x) : uniform_continuous (Ξ»p:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, let ⟨δ, Ξ΄0, Hδ⟩ := rat_inv_continuous_lemma abs Ξ΅0 r0 in ⟨δ, Ξ΄0, Ξ» a b h, HΞ΄ (H _ a.2) (H _ b.2) h⟩ lemma uniform_continuous_abs : uniform_continuous (abs : β„‚ β†’ ℝ) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, ⟨Ρ, Ξ΅0, Ξ» a b, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _)⟩ lemma continuous_abs : continuous (abs : β„‚ β†’ ℝ) := uniform_continuous_abs.continuous lemma tendsto_inv {r : β„‚} (r0 : r β‰  0) : tendsto (Ξ»q, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (Ξ» x h, le_of_lt h)) (mem_nhds_sets (continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma continuous_inv : continuous (Ξ»a:{r:β„‚ // r β‰  0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma continuous.inv {Ξ±} [topological_space Ξ±] {f : Ξ± β†’ β„‚} (h : βˆ€a, f a β‰  0) (hf : continuous f) : continuous (Ξ»a, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val β„‚ (Ξ»r, r β‰  0)) ∘ Ξ»a, ⟨f a, h a⟩), from continuous_inv.comp (continuous_subtype_mk _ hf) lemma uniform_continuous_mul_const {x : β„‚} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos Ξ΅0 y0, Ξ» a b h, _⟩, rw [dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' Ξ΅ (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma uniform_continuous_mul (s : set (β„‚ Γ— β„‚)) {r₁ rβ‚‚ : ℝ} (H : βˆ€ x ∈ s, abs (x : β„‚ Γ— β„‚).1 < r₁ ∧ abs x.2 < rβ‚‚) : uniform_continuous (Ξ»p:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ Ξ» Ξ΅ Ξ΅0, let ⟨δ, Ξ΄0, Hδ⟩ := rat_mul_continuous_lemma abs Ξ΅0 in ⟨δ, Ξ΄0, Ξ» a b h, let ⟨h₁, hβ‚‚βŸ© := max_lt_iff.1 h in HΞ΄ (H _ a.2).1 (H _ b.2).2 h₁ hβ‚‚βŸ© protected lemma continuous_mul : continuous (Ξ»p : β„‚ Γ— β„‚, p.1 * p.2) := continuous_iff_continuous_at.2 $ Ξ» ⟨a₁, aβ‚‚βŸ©, tendsto_of_uniform_continuous_subtype (uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs aβ‚‚ + 1}) (Ξ» x, id)) (mem_nhds_sets (is_open_prod (continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (continuous_abs _ $ is_open_gt' (abs aβ‚‚ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs aβ‚‚)⟩) local attribute [semireducible] real.le lemma uniform_continuous_re : uniform_continuous re := metric.uniform_continuous_iff.2 (Ξ» Ξ΅ Ξ΅0, ⟨Ρ, Ξ΅0, Ξ» _ _, lt_of_le_of_lt (abs_re_le_abs _)⟩) lemma continuous_re : continuous re := uniform_continuous_re.continuous lemma uniform_continuous_im : uniform_continuous im := metric.uniform_continuous_iff.2 (Ξ» Ξ΅ Ξ΅0, ⟨Ρ, Ξ΅0, Ξ» _ _, lt_of_le_of_lt (abs_im_le_abs _)⟩) lemma continuous_im : continuous im := uniform_continuous_im.continuous lemma uniform_continuous_of_real : uniform_continuous of_real := metric.uniform_continuous_iff.2 (Ξ» Ξ΅ Ξ΅0, ⟨Ρ, Ξ΅0, Ξ» _ _, by rw [real.dist_eq, complex.dist_eq, of_real_eq_coe, of_real_eq_coe, ← of_real_sub, abs_of_real]; exact id⟩) lemma continuous_of_real : continuous of_real := uniform_continuous_of_real.continuous instance : topological_ring β„‚ := { continuous_mul := complex.continuous_mul, ..complex.topological_add_group } instance : topological_semiring β„‚ := by apply_instance -- short-circuit type class inference /-- `β„‚` is homeomorphic to the real plane with `max` norm. -/ def real_prod_homeo : β„‚ β‰ƒβ‚œ (ℝ Γ— ℝ) := { to_equiv := real_prod_equiv, continuous_to_fun := continuous_re.prod_mk continuous_im, continuous_inv_fun := show continuous (Ξ» p : ℝ Γ— ℝ, complex.mk p.1 p.2), by simp only [mk_eq_add_mul_I]; exact (continuous_of_real.comp continuous_fst).add ((continuous_of_real.comp continuous_snd).mul continuous_const) } instance : proper_space β„‚ := ⟨λx r, begin refine real_prod_homeo.symm.compact_preimage.1 (compact_of_is_closed_subset ((proper_space.compact_ball x.re r).prod (proper_space.compact_ball x.im r)) (continuous_iff_is_closed.1 real_prod_homeo.symm.continuous _ is_closed_ball) _), exact Ξ» p h, ⟨ le_trans (abs_re_le_abs (⟨p.1, p.2⟩ - x)) h, le_trans (abs_im_le_abs (⟨p.1, p.2⟩ - x)) h⟩ end⟩ end complex
7667e44ebc934c992d91f95c1c179ed2028eac03
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/bernoulli_polynomials.lean
73b8263a760859f8e47a640b626c37ddba9b757f
[ "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
9,987
lean
/- Copyright (c) 2021 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan, David Loeffler -/ import data.polynomial.algebra_map import data.polynomial.derivative import data.nat.choose.cast import number_theory.bernoulli /-! # Bernoulli polynomials The [Bernoulli polynomials](https://en.wikipedia.org/wiki/Bernoulli_polynomials) are an important tool obtained from Bernoulli numbers. ## Mathematical overview The $n$-th Bernoulli polynomial is defined as $$ B_n(X) = βˆ‘_{k = 0}^n {n \choose k} (-1)^k B_k X^{n - k} $$ where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions, $$ \frac{t e^{tX} }{ e^t - 1} = βˆ‘_{n = 0}^{\infty} B_n(X) \frac{t^n}{n!} $$ ## Implementation detail Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers. ## Main theorems - `sum_bernoulli`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial coefficients up to `n` is `(n + 1) * X^n`. - `polynomial.bernoulli_generating_function`: The Bernoulli polynomials act as generating functions for the exponential. ## TODO - `bernoulli_eval_one_neg` : $$ B_n(1 - x) = (-1)^n B_n(x) $$ -/ noncomputable theory open_locale big_operators open_locale nat polynomial open nat finset namespace polynomial /-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/ def bernoulli (n : β„•) : β„š[X] := βˆ‘ i in range (n + 1), polynomial.monomial (n - i) ((_root_.bernoulli i) * (choose n i)) lemma bernoulli_def (n : β„•) : bernoulli n = βˆ‘ i in range (n + 1), polynomial.monomial i ((_root_.bernoulli (n - i)) * (choose n i)) := begin rw [←sum_range_reflect, add_succ_sub_one, add_zero, bernoulli], apply sum_congr rfl, rintros x hx, rw mem_range_succ_iff at hx, rw [choose_symm hx, tsub_tsub_cancel_of_le hx], end /- ### examples -/ section examples @[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli] @[simp] lemma bernoulli_eval_zero (n : β„•) : (bernoulli n).eval 0 = _root_.bernoulli n := begin rw [bernoulli, eval_finset_sum, sum_range_succ], have : βˆ‘ (x : β„•) in range n, _root_.bernoulli x * (n.choose x) * 0 ^ (n - x) = 0, { apply sum_eq_zero (Ξ» x hx, _), have h : 0 < n - x := tsub_pos_of_lt (mem_range.1 hx), simp [h] }, simp [this], end @[simp] lemma bernoulli_eval_one (n : β„•) : (bernoulli n).eval 1 = _root_.bernoulli' n := begin simp only [bernoulli, eval_finset_sum], simp only [←succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self, (_root_.bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, eval_C, eval_monomial], by_cases h : n = 1, { norm_num [h], }, { simp [h], exact bernoulli_eq_bernoulli'_of_ne_one h, } end end examples lemma derivative_bernoulli_add_one (k : β„•) : (bernoulli (k + 1)).derivative = (k + 1) * bernoulli k := begin simp_rw [bernoulli, derivative_sum, derivative_monomial, nat.sub_sub, nat.add_sub_add_right], -- LHS sum has an extra term, but the coefficient is zero: rw [range_add_one, sum_insert not_mem_range_self, tsub_self, cast_zero, mul_zero, map_zero, zero_add, mul_sum], -- the rest of the sum is termwise equal: refine sum_congr (by refl) (Ξ» m hm, _), conv_rhs { rw [←nat.cast_one, ←nat.cast_add, ←C_eq_nat_cast, C_mul_monomial, mul_comm], }, rw [mul_assoc, mul_assoc, ←nat.cast_mul, ←nat.cast_mul], congr' 3, rw [(choose_mul_succ_eq k m).symm, mul_comm], end lemma derivative_bernoulli (k : β„•) : (bernoulli k).derivative = k * bernoulli (k - 1) := begin cases k, { rw [nat.cast_zero, zero_mul, bernoulli_zero, derivative_one], }, { exact_mod_cast derivative_bernoulli_add_one k, } end @[simp] theorem sum_bernoulli (n : β„•) : βˆ‘ k in range (n + 1), ((n + 1).choose k : β„š) β€’ bernoulli k = monomial n (n + 1 : β„š) := begin simp_rw [bernoulli_def, finset.smul_sum, finset.range_eq_Ico, ←finset.sum_Ico_Ico_comm, finset.sum_Ico_eq_sum_range], simp only [cast_succ, add_tsub_cancel_left, tsub_zero, zero_add, linear_map.map_add], simp_rw [smul_monomial, mul_comm (_root_.bernoulli _) _, smul_eq_mul, ←mul_assoc], conv_lhs { apply_congr, skip, conv { apply_congr, skip, rw [← nat.cast_mul, choose_mul ((le_tsub_iff_left $ mem_range_le H).1 $ mem_range_le H_1) (le.intro rfl), nat.cast_mul, add_comm x x_1, add_tsub_cancel_right, mul_assoc, mul_comm, ←smul_eq_mul, ←smul_monomial] }, rw [←sum_smul], }, rw [sum_range_succ_comm], simp only [add_right_eq_self, cast_succ, mul_one, cast_one, cast_add, add_tsub_cancel_left, choose_succ_self_right, one_smul, _root_.bernoulli_zero, sum_singleton, zero_add, linear_map.map_add, range_one], apply sum_eq_zero (Ξ» x hx, _), have f : βˆ€ x ∈ range n, Β¬ n + 1 - x = 1, { rintros x H, rw [mem_range] at H, rw [eq_comm], exact ne_of_lt (nat.lt_of_lt_of_le one_lt_two (le_tsub_of_add_le_left (succ_le_succ H))) }, rw [sum_bernoulli], have g : (ite (n + 1 - x = 1) (1 : β„š) 0) = 0, { simp only [ite_eq_right_iff, one_ne_zero], intro h₁, exact (f x hx) h₁, }, rw [g, zero_smul], end /-- Another version of `polynomial.sum_bernoulli`. -/ lemma bernoulli_eq_sub_sum (n : β„•) : (n.succ : β„š) β€’ bernoulli n = monomial n (n.succ : β„š) - βˆ‘ k in finset.range n, ((n + 1).choose k : β„š) β€’ bernoulli k := by rw [nat.cast_succ, ← sum_bernoulli n, sum_range_succ, add_sub_cancel', choose_succ_self_right, nat.cast_succ] /-- Another version of `bernoulli.sum_range_pow`. -/ lemma sum_range_pow_eq_bernoulli_sub (n p : β„•) : (p + 1 : β„š) * βˆ‘ k in range n, (k : β„š) ^ p = (bernoulli p.succ).eval n - (_root_.bernoulli p.succ) := begin rw [sum_range_pow, bernoulli_def, eval_finset_sum, ←sum_div, mul_div_cancel' _ _], { simp_rw [eval_monomial], symmetry, rw [←sum_flip _, sum_range_succ], simp only [tsub_self, tsub_zero, choose_zero_right, cast_one, mul_one, pow_zero, add_tsub_cancel_right], apply sum_congr rfl (Ξ» x hx, _), apply congr_arg2 _ (congr_arg2 _ _ _) rfl, { rw nat.sub_sub_self (mem_range_le hx), }, { rw ←choose_symm (mem_range_le hx), }, }, { norm_cast, apply succ_ne_zero _, }, end /-- Rearrangement of `polynomial.sum_range_pow_eq_bernoulli_sub`. -/ lemma bernoulli_succ_eval (n p : β„•) : (bernoulli p.succ).eval n = _root_.bernoulli (p.succ) + (p + 1 : β„š) * βˆ‘ k in range n, (k : β„š) ^ p := by { apply eq_add_of_sub_eq', rw sum_range_pow_eq_bernoulli_sub, } lemma bernoulli_eval_one_add (n : β„•) (x : β„š) : (bernoulli n).eval (1 + x) = (bernoulli n).eval x + n * x^(n - 1) := begin apply nat.strong_induction_on n (Ξ» d hd, _), have nz : ((d.succ : β„•): β„š) β‰  0, { norm_cast, exact d.succ_ne_zero, }, apply (mul_right_inj' nz).1, rw [← smul_eq_mul, ←eval_smul, bernoulli_eq_sub_sum, mul_add, ←smul_eq_mul, ←eval_smul, bernoulli_eq_sub_sum, eval_sub, eval_finset_sum], conv_lhs { congr, skip, apply_congr, skip, rw [eval_smul, hd x_1 (mem_range.1 H)], }, rw [eval_sub, eval_finset_sum], simp_rw [eval_smul, smul_add], rw [sum_add_distrib, sub_add, sub_eq_sub_iff_sub_eq_sub, _root_.add_sub_sub_cancel], conv_rhs { congr, skip, congr, rw [succ_eq_add_one, ←choose_succ_self_right d], }, rw [nat.cast_succ, ← smul_eq_mul, ←sum_range_succ _ d, eval_monomial_one_add_sub], simp_rw [smul_eq_mul], end open power_series variables {A : Type*} [comm_ring A] [algebra β„š A] -- TODO: define exponential generating functions, and use them here -- This name should probably be updated afterwards /-- The theorem that `βˆ‘ Bβ‚™(t)X^n/n!)(e^X-1)=Xe^{tX}` -/ theorem bernoulli_generating_function (t : A) : mk (Ξ» n, aeval t ((1 / n! : β„š) β€’ bernoulli n)) * (exp A - 1) = power_series.X * rescale t (exp A) := begin -- check equality of power series by checking coefficients of X^n ext n, -- n = 0 case solved by `simp` cases n, { simp }, -- n β‰₯ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as -- last term plus sum to n+1 rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, power_series.coeff_mul, nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ], -- last term is zero so kill with `add_zero` simp only [ring_hom.map_sub, tsub_self, constant_coeff_one, constant_coeff_exp, coeff_zero_eq_constant_coeff, mul_zero, sub_self, add_zero], -- Let's multiply both sides by (n+1)! (OK because it's a unit) have hnp1 : is_unit ((n+1)! : β„š) := is_unit.mk0 _ (by exact_mod_cast factorial_ne_zero (n+1)), rw ←(hnp1.map (algebra_map β„š A)).mul_right_inj, -- do trivial rearrangements to make RHS (n+1)*t^n rw [mul_left_comm, ←ring_hom.map_mul], change _ = t^n * algebra_map β„š A (((n+1)*n! : β„•)*(1/n!)), rw [cast_mul, mul_assoc, mul_one_div_cancel (show (n! : β„š) β‰  0, from cast_ne_zero.2 (factorial_ne_zero n)), mul_one, mul_comm (t^n), ← aeval_monomial, cast_add, cast_one], -- But this is the RHS of `sum_bernoulli_poly` rw [← sum_bernoulli, finset.mul_sum, alg_hom.map_sum], -- and now we have to prove a sum is a sum, but all the terms are equal. apply finset.sum_congr rfl, -- The rest is just trivialities, hampered by the fact that we're coercing -- factorials and binomial coefficients between β„• and β„š and A. intros i hi, -- deal with coefficients of e^X-1 simp only [nat.cast_choose β„š (mem_range_le hi), coeff_mk, if_neg (mem_range_sub_ne_zero hi), one_div, alg_hom.map_smul, power_series.coeff_one, coeff_exp, sub_zero, linear_map.map_sub, algebra.smul_mul_assoc, algebra.smul_def, mul_right_comm _ ((aeval t) _), ←mul_assoc, ← ring_hom.map_mul, succ_eq_add_one, ← polynomial.C_eq_algebra_map, polynomial.aeval_mul, polynomial.aeval_C], -- finally cancel the Bernoulli polynomial and the algebra_map congr', apply congr_arg, rw [mul_assoc, div_eq_mul_inv, ← mul_inv], end end polynomial
17c71ba97f8c1d0e2d9d4b9cd87bc940d334809f
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/EXAMS/key-in-class-quiz-bi-or.lean
98c8b5bc635d00cb9bb0ec81ef7b5071ddcc1786
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
3,280
lean
/- Prove P ∨ Q ↔ Q ∨ P. -/ theorem or_commutes : βˆ€ P Q: Prop, P ∨ Q ↔ Q ∨ P := begin /- Introduce the assumptions that P and Q are arbitrary propositions. -/ assume P Q: Prop, /- To prove a bi-implication, we prove the implications in each direction. That is, we break the overall goal into subgoals, one for the forward implication and one for its converse (in the other direction). -/ apply iff.intro, -- now we prove the forward implication assume pq : P ∨ Q, show Q ∨ P, from begin /- The key proof technique for reasoning from a proof of a disjunction, P ∨ Q, is to consider two possible cases for this proof, that either P is true or Q is, and to show that the goal is true in either case. This shows that no matter why P ∨ Q is true, the goal follows. So, the proof strategy is first to assumes that P ∨ Q is true because P is true, which is to say you assume you have a proof of P, and then show that the goal follows. Then you assume P ∨ Q is true because Q is true, and you show that given an assumed proof of Q, the goal follows. The goal thus follows in either case. The tactic that we use in Lean to reason by cases from a disjunction is called "cases." As arguments you give it (1) the name of the disjunction to reason from, and (2) names to use for the assumed proofs of P and Q in the respective cases (after keyword "with"). So here we go. Make sure you have the Lean Messages window open so that you can see how "cases" changes your tactic state. Note that it introduces two new subgoals. In the first, there is an assumed proof, p : P. In the second, there is an an assumed proof q : Q. -/ cases pq with p q, -- now prove each case separately -- proof for case where P is true show Q ∨ P, from or.intro_right Q p, -- proof for case where Q is true show Q ∨ P, from or.intro_left P q, end, -- and now we prove the converse assume qp : Q ∨ P, show P ∨ Q, from begin cases qp with q p, show P ∨ Q, from or.intro_right P q, show P ∨ Q, from or.intro_left Q p, end, end /- Homework: Prove, βˆ€ P Q: Prop, Β¬ P ∧ Β¬ Q ↔ Β¬ (P ∨ Q) -/ theorem aDemorganLaw : βˆ€ P Q: Prop, Β¬ P ∧ Β¬ Q ↔ Β¬ (P ∨ Q) := begin assume P Q : Prop, apply iff.intro, -- forward assume npnq, show Β¬(P ∨ Q), from begin assume poq, -- proof by cases cases poq with p q, -- case where P is true show false, from npnq.left p, -- case where Q is true show false, from npnq.right q, end, -- converse assume poq, show Β¬P ∧ Β¬Q, from begin -- proof by and introduction apply and.intro, -- left conjunct assume p, show false, from poq (or.intro_left Q p), -- right conjunct assume q, show false, from poq (or.intro_right P q) end, -- QED end
9d06a24891acf3a84f6e9f5194d51baa103ddce3
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/set_theory/cofinality.lean
555e4ed2ac144ea0995b449968071658fbf12aba
[ "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
22,027
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import set_theory.cardinal_ordinal /-! # Cofinality on ordinals, regular cardinals -/ noncomputable theory open function cardinal set open_locale classical universes u v w variables {Ξ± : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} namespace order /-- Cofinality of a reflexive order `β‰Ό`. This is the smallest cardinality of a subset `S : set Ξ±` such that `βˆ€ a, βˆƒ b ∈ S, a β‰Ό b`. -/ def cof (r : Ξ± β†’ Ξ± β†’ Prop) [is_refl Ξ± r] : cardinal := @cardinal.min {S : set Ξ± // βˆ€ a, βˆƒ b ∈ S, r a b} ⟨⟨set.univ, Ξ» a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (Ξ» S, mk S) lemma cof_le (r : Ξ± β†’ Ξ± β†’ Prop) [is_refl Ξ± r] {S : set Ξ±} (h : βˆ€a, βˆƒ(b ∈ S), r a b) : order.cof r ≀ mk S := le_trans (cardinal.min_le _ ⟨S, h⟩) (le_refl _) lemma le_cof {r : Ξ± β†’ Ξ± β†’ Prop} [is_refl Ξ± r] (c : cardinal) : c ≀ order.cof r ↔ βˆ€ {S : set Ξ±} (h : βˆ€a, βˆƒ(b ∈ S), r a b) , c ≀ mk S := by { rw [order.cof, cardinal.le_min], exact ⟨λ H S h, H ⟨S, h⟩, Ξ» H ⟨S, h⟩, H h ⟩ } end order theorem order_iso.cof.aux {Ξ± : Type u} {Ξ² : Type v} {r s} [is_refl Ξ± r] [is_refl Ξ² s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) ≀ cardinal.lift.{v (max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp [(∘)], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, Ξ» a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, f.ord', h, -coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, Ξ» ⟨x, hβ‚βŸ© ⟨y, hβ‚‚βŸ© h₃, by congr; injection h₃ with h'; exact f.to_equiv.injective h'⟩⟩ } end theorem order_iso.cof {Ξ± : Type u} {Ξ² : Type v} {r s} [is_refl Ξ± r] [is_refl Ξ² s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) = cardinal.lift.{v (max u v)} (order.cof s) := le_antisymm (order_iso.cof.aux f) (order_iso.cof.aux f.symm) def strict_order.cof (r : Ξ± β†’ Ξ± β†’ Prop) [h : is_irrefl Ξ± r] : cardinal := @order.cof Ξ± (Ξ» x y, Β¬ r y x) ⟨h.1⟩ namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `βˆ€ a, βˆƒ b ∈ S, Β¬(b > a)`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (Ξ» ⟨α, r, _⟩, by exactI strict_order.cof r) begin rintros ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, rw ← cardinal.lift_inj, apply order_iso.cof ⟨f, _⟩, simp [hf] end lemma cof_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : (type r).cof = strict_order.cof r := rfl theorem le_cof_type [is_well_order Ξ± r] {c} : c ≀ cof (type r) ↔ βˆ€ S : set Ξ±, (βˆ€ a, βˆƒ b ∈ S, Β¬ r b a) β†’ c ≀ mk S := by dsimp [cof, strict_order.cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order Ξ± r] (S : set Ξ±) (h : βˆ€ a, βˆƒ b ∈ S, Β¬ r b a) : cof (type r) ≀ mk S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order Ξ± r] (S : set Ξ±) (hl : mk S < cof (type r)) : βˆƒ a, βˆ€ b ∈ S, r b a := not_forall_not.1 $ Ξ» h, not_le_of_lt hl $ cof_type_le S (Ξ» a, not_ball.1 (h a)) theorem cof_eq (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : βˆƒ S : set Ξ±, (βˆ€ a, βˆƒ b ∈ S, Β¬ r b a) ∧ mk S = cof (type r) := begin have : βˆƒ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : βˆƒ S : set Ξ±, (βˆ€ a, βˆƒ b ∈ S, Β¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set Ξ± := {a | βˆƒ aS : a ∈ S, βˆ€ b : S, s b ⟨_, aS⟩ β†’ r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨order_embedding.of_monotone (Ξ» a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (Ξ» a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (Ξ» hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | Β¬ r b a}.nonempty := let ⟨b, bS, ba⟩ := hS a in ⟨⟨b, bS⟩, ba⟩, let b := (is_well_order.wf).min _ this, have ba : Β¬r b a := (is_well_order.wf).min_mem _ this, refine ⟨b, ⟨b.2, Ξ» c, not_imp_not.1 $ Ξ» h, _⟩, ba⟩, rw [show βˆ€b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf).not_lt_min _ this (is_order_connected.neg_trans h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI Ξ± r _, cases lift_type r with _ e, rw e, apply le_antisymm, { unfreezingI { refine le_cof_type.2 (Ξ» S H, _) }, have : (mk (ulift.up ⁻¹' S)).lift ≀ mk S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, Ξ» ⟨⟨x, hβ‚βŸ©βŸ© ⟨⟨y, hβ‚‚βŸ©βŸ© e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact Ξ» a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : mk (ulift.down ⁻¹' S) ≀ (mk S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, Ξ» ⟨⟨x⟩, hβ‚βŸ© ⟨⟨y⟩, hβ‚‚βŸ© e, by simp at e; congr; injections⟩⟩, rw e' at this, unfreezingI { refine le_trans (cof_type_le _ _) this }, exact Ξ» ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≀ card o := induction_on o $ Ξ» Ξ± r _, begin resetI, have : mk (@set.univ Ξ±) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (Ξ» a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≀ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ Ξ» Ξ± r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $ Ξ» ⟨a⟩, let ⟨b, h, _⟩ := hl a in ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z), Ξ» e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (Ξ» Ξ± r _, _), change cof (type _) ≀ _, rw [← (_ : mk _ = 1)], apply cof_type_le, { refine Ξ» a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using Ξ» h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ βˆƒ a, o = succ a := ⟨induction_on o $ Ξ» Ξ± r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.of_monotone _ (Ξ» x y, _)) (Ξ» x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact Ξ» _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ βˆƒ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, Ξ» ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b β‰  0 β†’ cof (a + b) = cof b := induction_on a $ Ξ» Ξ± r _, induction_on b $ Ξ» Ξ² s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (Ξ» c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (βˆ…:set Ξ±) S} (Ξ» a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact Ξ» a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact Ξ» a b, match a, b with ⟨sum.inr a, hβ‚βŸ©, ⟨sum.inr b, hβ‚‚βŸ©, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (Ξ» a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact Ξ» ⟨a, h⟩, ⟨_, h⟩ }, { exact Ξ» ⟨a, hβ‚βŸ© ⟨b, hβ‚‚βŸ© h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord = cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ Ξ» Ξ± r _, by exactI let ⟨S, hS, eβ‚βŸ© := ord_cof_eq r, ⟨T, hT, eβ‚‚βŸ© := cof_eq (subrel r S) in begin rw e₁ at eβ‚‚, rw ← eβ‚‚, refine le_trans (cof_type_le {a | βˆƒ h, (subtype.mk a h : S) ∈ T} (Ξ» a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ }, { exact Ξ» ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact Ξ» ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : cardinal.omega ≀ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (Ξ» h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = cardinal.omega := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (h : is_limit (type r)) : βˆƒ S : set Ξ±, (βˆ€ a, βˆƒ b ∈ S, r a b) ∧ mk S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, Ξ» a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ΞΉ} (f : ΞΉ β†’ ordinal) (H : βˆ€ i, f i < sup f) : cof (sup f) ≀ (mk ΞΉ).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI Ξ± r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (Ξ» i, enum r _ (H i))) _) ⟨embedding.of_surjective _ _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, have h : βˆ€ (x : ΞΉ), r (enum r (f x) _) a, { simpa using h }, simpa only [typein_enum] using le_of_lt ((typein_lt_typein r).2 (h i)) }, { exact Ξ» i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ΞΉ} (f : ΞΉ β†’ ordinal) (H : βˆ€ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≀ mk ΞΉ := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : βˆ€ (f : Ξ  a < o, ordinal), (βˆ€ i h, f i h < bsup o f) β†’ cof (bsup o f) ≀ o.card.lift := induction_on o $ Ξ» Ξ± r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : βˆ€ (f : Ξ  a < o, ordinal), (βˆ€ i h, f i h < bsup.{u u} o f) β†’ cof (bsup.{u u} o f) ≀ o.card := induction_on o $ Ξ» Ξ± r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (Ξ» c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (Ξ» h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (Ξ» Ξ± e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := Ξ» a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end theorem sup_lt_ord {ΞΉ} (f : ΞΉ β†’ ordinal) {c : ordinal} (H1 : cardinal.mk ΞΉ < c.cof) (H2 : βˆ€ i, f i < c) : sup.{u u} f < c := begin apply lt_of_le_of_ne, { rw [sup_le], exact Ξ» i, le_of_lt (H2 i) }, rintro h, apply not_le_of_lt H1, simpa [sup_ord, H2, h] using cof_sup_le.{u} f end theorem sup_lt {ΞΉ} (f : ΞΉ β†’ cardinal) {c : cardinal} (H1 : cardinal.mk ΞΉ < c.ord.cof) (H2 : βˆ€ i, f i < c) : cardinal.sup.{u u} f < c := by { rw [←ord_lt_ord, ←sup_ord], apply sup_lt_ord _ H1, intro i, rw ord_lt_ord, apply H2 } /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_sUnion (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] {s : set (set Ξ±)} (h₁ : unbounded r $ ⋃₀ s) (hβ‚‚ : mk s < strict_order.cof r) : βˆƒ(x ∈ s), unbounded r x := begin by_contra h, simp only [not_exists, exists_prop, not_and, not_unbounded_iff] at h, apply not_le_of_lt hβ‚‚, let f : s β†’ Ξ± := Ξ» x : s, wo.wf.sup x (h x.1 x.2), let t : set Ξ± := range f, have : mk t ≀ mk s, exact mk_range_le, refine le_trans _ this, have : unbounded r t, { intro x, rcases h₁ x with ⟨y, ⟨c, hc, hy⟩, hxy⟩, refine ⟨f ⟨c, hc⟩, mem_range_self _, _⟩, intro hxz, apply hxy, refine trans (wo.wf.lt_sup _ hy) hxz }, exact cardinal.min_le _ (subtype.mk t this) end /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_Union {Ξ± Ξ² : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] (s : Ξ² β†’ set Ξ±) (h₁ : unbounded r $ ⋃x, s x) (hβ‚‚ : mk Ξ² < strict_order.cof r) : βˆƒx : Ξ², unbounded r (s x) := begin rw [← sUnion_range] at h₁, have : mk β†₯(range (Ξ» (i : Ξ²), s i)) < strict_order.cof r := lt_of_le_of_lt mk_range_le hβ‚‚, rcases unbounded_of_unbounded_sUnion r h₁ this with ⟨_, ⟨x, rfl⟩, u⟩, exact ⟨x, u⟩ end /-- The infinite pigeonhole principle-/ theorem infinite_pigeonhole {Ξ² Ξ± : Type u} (f : Ξ² β†’ Ξ±) (h₁ : cardinal.omega ≀ mk Ξ²) (hβ‚‚ : mk Ξ± < (mk Ξ²).ord.cof) : βˆƒa : Ξ±, mk (f ⁻¹' {a}) = mk Ξ² := begin have : Β¬βˆ€a, mk (f ⁻¹' {a}) < mk Ξ², { intro h, apply not_lt_of_ge (ge_of_eq $ mk_univ), rw [←@preimage_univ _ _ f, ←Union_of_singleton, preimage_Union], apply lt_of_le_of_lt mk_Union_le_sum_mk, apply lt_of_le_of_lt (sum_le_sup _), apply mul_lt_of_lt h₁ (lt_of_lt_of_le hβ‚‚ $ cof_ord_le _), exact sup_lt _ hβ‚‚ h }, rw [not_forall] at this, cases this with x h, use x, apply le_antisymm _ (le_of_not_gt h), rw [le_mk_iff_exists_set], exact ⟨_, rfl⟩ end /-- pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {Ξ² Ξ± : Type u} (f : Ξ² β†’ Ξ±) (ΞΈ : cardinal) (hΞΈ : ΞΈ ≀ mk Ξ²) (h₁ : cardinal.omega ≀ ΞΈ) (hβ‚‚ : mk Ξ± < ΞΈ.ord.cof) : βˆƒa : Ξ±, ΞΈ ≀ mk (f ⁻¹' {a}) := begin rcases le_mk_iff_exists_set.1 hΞΈ with ⟨s, rfl⟩, cases infinite_pigeonhole (f ∘ subtype.val : s β†’ Ξ±) h₁ hβ‚‚ with a ha, use a, rw [←ha, @preimage_comp _ _ _ subtype.val f], apply mk_preimage_of_injective _ _ subtype.val_injective end theorem infinite_pigeonhole_set {Ξ² Ξ± : Type u} {s : set Ξ²} (f : s β†’ Ξ±) (ΞΈ : cardinal) (hΞΈ : ΞΈ ≀ mk s) (h₁ : cardinal.omega ≀ ΞΈ) (hβ‚‚ : mk Ξ± < ΞΈ.ord.cof) : βˆƒ(a : Ξ±) (t : set Ξ²) (h : t βŠ† s), ΞΈ ≀ mk t ∧ βˆ€{{x}} (hx : x ∈ t), f ⟨x, h hx⟩ = a := begin cases infinite_pigeonhole_card f ΞΈ hΞΈ h₁ hβ‚‚ with a ha, refine ⟨a, {x | βˆƒ(h : x ∈ s), f ⟨x, h⟩ = a}, _, _, _⟩, { rintro x ⟨hx, hx'⟩, exact hx }, { refine le_trans ha _, apply ge_of_eq, apply quotient.sound, constructor, refine equiv.trans _ (equiv.subtype_subtype_equiv_subtype_exists _ _).symm, simp only [set_coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_set_of_eq] }, rintro x ⟨hx, hx'⟩, exact hx' end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `Ο‰` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c β‰  0 ∧ βˆ€ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `Ο‰` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c β‰  0 ∧ βˆ€ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, Ξ» x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := omega ≀ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular : is_regular omega := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : omega ≀ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with Ξ± Ξ±e, simp at Ξ±e, rcases ord_eq Ξ± with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← Ξ±e, re] at this ⊒, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (mul_le_mul_right c), rw [mul_eq_self h, ← succ_le, ← Ξ±e, ← sum_const], refine le_trans _ (sum_le_sum (Ξ» x:S, card (typein r x)) _ _), { simp [typein, sum_mk (Ξ» x:S, {a//r a x})], refine ⟨embedding.of_surjective _ _⟩, { exact Ξ» x, x.2.1 }, { exact Ξ» a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← Ξ±e, re], apply typein_lt_type } end⟩ theorem sup_lt_ord_of_is_regular {ΞΉ} (f : ΞΉ β†’ ordinal) {c} (hc : is_regular c) (H1 : cardinal.mk ΞΉ < c) (H2 : βˆ€ i, f i < c.ord) : ordinal.sup.{u u} f < c.ord := by { apply sup_lt_ord _ _ H2, rw [hc.2], exact H1 } theorem sup_lt_of_is_regular {ΞΉ} (f : ΞΉ β†’ cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ΞΉ < c) (H2 : βˆ€ i, f i < c) : sup.{u u} f < c := by { apply sup_lt _ _ H2, rwa [hc.2] } theorem sum_lt_of_is_regular {ΞΉ} (f : ΞΉ β†’ cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ΞΉ < c) (H2 : βˆ€ i, f i < c) : sum.{u u} f < c := lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $ sup_lt_of_is_regular f hc H1 H2 /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : omega < c) (hβ‚‚ : c ≀ c.ord.cof) (h₃ : βˆ€ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) hβ‚‚βŸ©, ne_of_gt (lt_trans omega_pos h₁), hβ‚ƒβŸ© /- Lean's foundations prove the existence of Ο‰ many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' omega) (by simp) (Ξ» c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : omega ≀ c β†’ c < c ^ cof c.ord := quotient.induction_on c $ Ξ» Ξ± h, begin rcases ord_eq Ξ± with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊒, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (Ξ» a:S, mk {x // r x a}) (Ξ» _, mk Ξ±) (Ξ» i, _), { simp [Se.symm] at this ⊒, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _ _⟩, { exact Ξ» x, x.2.1 }, { exact Ξ» a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : omega ≀ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b β‰  0 := ne_of_gt (lt_trans zero_lt_one b1), apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
549d53b7c744a1408f150dd2b6d98d6fd947b60b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1361.lean
a87d1e75920ea0fb80260e11d46cafde9e92350a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,223
lean
namespace Ex1 inductive Multiset (Ξ±: Type): Type def Finset (Ξ± : Type) := @Subtype (Multiset Ξ±) (Ξ» _ => True) def Finset.insert (a : Ξ±): Finset Ξ± β†’ Finset Ξ± := sorry def Finset.empty : Finset Ξ± := sorry structure Foo (G: Fin 0) (m: Nat) where n: Nat f: Fin m inductive Bar {G: Fin 0} : {m: Nat} β†’ Finset (Foo G m) β†’ Type where | insert : Bar (Finset.insert (Foo.mk n f) Ξ“) | empty : Bar Finset.empty example {G: Fin 0} : {n: Nat} β†’ {Ξ“: Finset <| Foo G n} β†’ Bar Ξ“ β†’ Nat | Nat.zero, _, _ => 1 | Nat.succ _, _, Bar.insert => 2 | Nat.succ _, _, _ => 3 end Ex1 namespace Ex2 inductive Multiset (Ξ±: Type _): Type _ def Finset (Ξ± : Type _) := @Subtype (Multiset Ξ±) (Ξ» _ => True) def Finset.insert [DecidableEq Ξ±](a : Ξ±): Finset Ξ± β†’ Finset Ξ± := sorry def Finset.empty : Finset Ξ± := sorry structure Foo (G: Fin 0) (m: Nat) where n: Nat f: Fin m deriving DecidableEq inductive Bar {G: Fin 0}: {m: Nat} β†’ Finset (Foo G m) β†’ Type _ | insert: Bar (Finset.insert (Foo.mk n f) Ξ“) | empty: Bar Finset.empty example {G: Fin 0} : βˆ€ {n: Nat} {Ξ“: Finset $ Foo G n} (p: Bar Ξ“), Nat | 0, _, _ => 0 | _+1, _, Bar.insert => 0 | _+1, _, _ => 0 end Ex2
c50efe4d92bdcd3c5da9305c6bcf4573bc83d11c
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/equiv/mul_add.lean
c8c00a666e307c48c551cbd3eb6cd30b17c97a44
[ "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
21,568
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Callum Sutton, Yury Kudryashov -/ import algebra.group.hom import algebra.group.type_tags import algebra.group.units_hom import algebra.group_with_zero /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {G : Type*} {H : Type*} /-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive inverse from a bijection which preserves addition."] def mul_hom.inverse [has_mul M] [has_mul N] (f : mul_hom M N) (g : N β†’ M) (h₁ : function.left_inverse g f) (hβ‚‚ : function.right_inverse g f) : mul_hom N M := { to_fun := g, map_mul' := Ξ» x y, calc g (x * y) = g (f (g x) * f (g y)) : by rw [hβ‚‚ x, hβ‚‚ y] ... = g (f (g x * g y)) : by rw f.map_mul ... = g x * g y : h₁ _, } set_option old_structure_cmd true /-- add_equiv Ξ± Ξ² is the type of an equiv Ξ± ≃ Ξ² which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv Ξ± Ξ²` is the type of an equiv `Ξ± ≃ Ξ²` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : βˆ€ x y, f (x * y) = f x * f y := f.map_mul' /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : βˆ€ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := Ξ» _ _, rfl, ..equiv.refl _} instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul, .. h.to_equiv.symm} /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive add_equiv.simps.inv_fun "See Note custom simps projection"] def simps.inv_fun (e : M ≃* N) : N β†’ M := e.symm initialize_simps_projections add_equiv (to_fun β†’ apply, inv_fun β†’ symm_apply) initialize_simps_projections mul_equiv (to_fun β†’ apply, inv_fun β†’ symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M β†’ N) (g h₁ hβ‚‚ h₃) : ⇑(mul_equiv.mk f g h₁ hβ‚‚ h₃) = f := rfl @[simp, to_additive] lemma symm_symm : βˆ€ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, hβ‚‚, hβ‚ƒβŸ© := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) β†’ (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M β†’ N) (g h₁ hβ‚‚ h₃) : (mul_equiv.mk f g h₁ hβ‚‚ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ hβ‚‚ h₃).symm} := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := Ξ» x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : βˆ€ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : βˆ€ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp, to_additive] theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp, to_additive] theorem coe_refl : ⇑(refl M) = id := rfl @[to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem coe_trans (e₁ : M ≃* N) (eβ‚‚ : N ≃* P) : ⇑(e₁.trans eβ‚‚) = eβ‚‚ ∘ e₁ := rfl @[to_additive] theorem trans_apply (e₁ : M ≃* N) (eβ‚‚ : N ≃* P) (m : M) : e₁.trans eβ‚‚ m = eβ‚‚ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : βˆ€ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ βˆ€ x, f x = g x := ⟨λ h x, h β–Έ rfl, ext⟩ @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ hβ‚‚ h₃) : (⟨e, e', h₁, hβ‚‚, hβ‚ƒβŸ© : M ≃* N) = e := ext $ Ξ» _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ hβ‚‚ h₃) : (mul_equiv.mk f ⇑e h₁ hβ‚‚ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ Ξ» x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} : Ξ  {x x' : M}, x = x' β†’ f x = f x' | _ _ rfl := rfl @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h β–Έ rfl /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := Ξ» _ _, subsingleton.elim _ _, ..equiv_of_unique_of_unique } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique_of_unique , uniq := Ξ» _, ext $ Ξ» x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/ @[simp, to_additive] lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one β–Έ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x β‰  1 ↔ x β‰  1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [mul_one_class M] [mul_one_class N] (f : M β†’* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M β†’* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] : function.injective (to_monoid_hom : (M ≃* N) β†’ M β†’* N) := Ξ» f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[simps apply, to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive."] def arrow_congr {M N P Q : Type*} [mul_one_class P] [mul_one_class Q] (f : M ≃ N) (g : P ≃* Q) : (M β†’ P) ≃* (N β†’ Q) := { to_fun := Ξ» h n, g (h (f.symm n)), inv_fun := Ξ» k m, g.symm (k (f m)), left_inv := Ξ» h, by { ext, simp, }, right_inv := Ξ» k, by { ext, simp, }, map_mul' := Ξ» h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[simps apply, to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid."] def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M β†’* P) ≃* (N β†’* Q) := { to_fun := Ξ» h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := Ξ» k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := Ξ» h, by { ext, simp, }, right_inv := Ξ» k, by { ext, simp, }, map_mul' := Ξ» h k, by { ext, simp, }, } /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x end mul_equiv -- We don't use `to_additive` to generate definition because it fails to tell Lean about -- equational lemmas /-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms. -/ def add_monoid_hom.to_add_equiv [add_zero_class M] [add_zero_class N] (f : M β†’+ N) (g : N β†’+ M) (h₁ : g.comp f = add_monoid_hom.id _) (hβ‚‚ : f.comp g = add_monoid_hom.id _) : M ≃+ N := { to_fun := f, inv_fun := g, left_inv := add_monoid_hom.congr_fun h₁, right_inv := add_monoid_hom.congr_fun hβ‚‚, map_add' := f.map_add } /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive] def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M β†’* N) (g : N β†’* M) (h₁ : g.comp f = monoid_hom.id _) (hβ‚‚ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun hβ‚‚, map_mul' := f.map_mul } @[simp, to_additive] lemma monoid_hom.coe_to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M β†’* N) (g : N β†’* M) (h₁ hβ‚‚) : ⇑(f.to_mul_equiv g h₁ hβ‚‚) = f := rfl /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y instance add_equiv.inhabited {M : Type*} [has_add M] : inhabited (M ≃+ M) := ⟨add_equiv.refl M⟩ /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := Ξ» x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := Ξ» x, rfl, right_inv := Ξ» u, units.ext rfl, map_mul' := Ξ» x y, units.ext rfl } protected lemma group.is_unit {G} [group G] (x : G) : is_unit x := (to_units x).is_unit namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := Ξ» u, ext $ h.left_inv u, right_inv := Ξ» u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type."] def mul_left (u : units M) : equiv.perm M := { to_fun := Ξ»x, u * x, inv_fun := Ξ»x, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma coe_mul_left (u : units M) : ⇑u.mul_left = (*) u := rfl @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ Ξ» x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type."] def mul_right (u : units M) : equiv.perm M := { to_fun := Ξ»x, x * u, inv_fun := Ξ»x, x * ↑u⁻¹, left_inv := Ξ» x, mul_inv_cancel_right x u, right_inv := Ξ» x, inv_mul_cancel_right x u } @[simp, to_additive] lemma coe_mul_right (u : units M) : ⇑u.mul_right = Ξ» x : M, x * u := rfl @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ Ξ» x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G β†’ G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ Ξ» x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = Ξ» x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ Ξ» x, rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G β†’ G) = Ξ» x, x * a⁻¹ := rfl attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type."] protected def inv : perm G := { to_fun := Ξ»a, a⁻¹, inv_fun := Ξ»a, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma coe_inv : ⇑(equiv.inv G) = has_inv.inv := rfl @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ protected def mul_left' (a : G) (ha : a β‰  0) : perm G := { to_fun := Ξ» x, a * x, inv_fun := Ξ» x, a⁻¹ * x, left_inv := Ξ» x, by { dsimp, rw [← mul_assoc, inv_mul_cancel ha, one_mul] }, right_inv := Ξ» x, by { dsimp, rw [← mul_assoc, mul_inv_cancel ha, one_mul] } } @[simp] lemma coe_mul_left' (a : G) (ha : a β‰  0) : ⇑(equiv.mul_left' a ha) = (*) a := rfl @[simp] lemma mul_left'_symm_apply (a : G) (ha : a β‰  0) : ((equiv.mul_left' a ha).symm : G β†’ G) = (*) a⁻¹ := rfl /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ protected def mul_right' (a : G) (ha : a β‰  0) : perm G := { to_fun := Ξ» x, x * a, inv_fun := Ξ» x, x * a⁻¹, left_inv := Ξ» x, by { dsimp, rw [mul_assoc, mul_inv_cancel ha, mul_one] }, right_inv := Ξ» x, by { dsimp, rw [mul_assoc, inv_mul_cancel ha, mul_one] } } @[simp] lemma coe_mul_right' (a : G) (ha : a β‰  0) : ⇑(equiv.mul_right' a ha) = Ξ» x, x * a := rfl @[simp] lemma mul_right'_symm_apply (a : G) (ha : a β‰  0) : ((equiv.mul_right' a ha).symm : G β†’ G) = Ξ» x, x * a⁻¹ := rfl end group_with_zero end equiv section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := Ξ» f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := Ξ» f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := Ξ» x, by { ext, refl, }, right_inv := Ξ» x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := Ξ» f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := Ξ» f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := Ξ» x, by { ext, refl, }, right_inv := Ξ» x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := Ξ» f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := Ξ» f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := Ξ» x, by { ext, refl, }, right_inv := Ξ» x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := Ξ» f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := Ξ» f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := Ξ» x, by { ext, refl, }, right_inv := Ξ» x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
29a6af4afa84affe415842c8a047cd2f3c557d05
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/pr1.lean
439c0650a1d919110a9e9f5d67e7051c2ae547ad
[ "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
112
lean
(* import("tactic.lua") *) theorem T (C A B : Bool) : C -> A -> B -> A. exact. done. print environment 1.
8958c59f82777627bd564fc247aa871e0cc8cf3f
9467cef9baa3ce9e7357f85743477488d73a6128
/graphs.hlean
bebc2c6d13bb50108c9314dedb994ce59830ab4f
[]
no_license
EgbertRijke/HoTT_Lean
5982de03e9bce4ce6f5fe0caa78ef938505681dd
a28a6bf25f7dafdcd3d2181fd6148fd0720f0847
refs/heads/master
1,610,309,632,029
1,422,251,273,000
1,422,251,273,000
29,821,165
0
0
null
null
null
null
UTF-8
Lean
false
false
3,920
hlean
open sigma eq namespace graphs -- We begin by defining the fundamental structure of the graph model -- The context in the graph model are the graphs themselves structure ctx := ( vertex : Type) ( edge : vertex β†’ vertex β†’ Type) -- The families in the graph model are families of graphs structure fam (G : ctx) := ( vertex : ctx.vertex G β†’ Type) ( edge : Ξ {i j : ctx.vertex G}, ctx.edge G i j β†’ vertex i β†’ vertex j β†’ Type) -- Global terms of families are matching families of terms structure tm {G : ctx} (A : fam G) := ( vertex : Ξ (i : ctx.vertex G), fam.vertex A i) ( edge : Ξ {i j : ctx.vertex G}, Ξ (e : ctx.edge G i j), fam.edge A e (vertex i) (vertex j)) section extension -- The graph model is an extension algebra variable {G : ctx} -- Extension in the graph model is interpetred using Sigma (by lack of something better) definition ctxext (A : fam G) : ctx := ctx.mk ( Ξ£ (i : ctx.vertex G), fam.vertex A i) ( Ξ» p q, Ξ£ (e : ctx.edge G (pr1 p) (pr1 q)), fam.edge A e (pr2 p) (pr2 q)) -- There is also family extension, which turns out to be equivalent to the dependent -- pair graph definition famext (A : fam G) (P : fam (ctxext A)) : fam G := fam.mk ( Ξ» i, Ξ£ (x : fam.vertex A i), fam.vertex P ⟨i,x⟩) ( Ξ» i j e p q, Ξ£ (f : fam.edge A e (pr1 p) (pr1 q)), fam.edge P ⟨e,f⟩ (pr2 p) (pr2 q)) end extension namespace wk -- The graph model is a weakening algebra variable {G : ctx} variable (A : fam G) definition ctx (B : fam G) : fam (ctxext A) := fam.mk ( Ξ» p, fam.vertex B (pr1 p)) ( Ξ» p q e, fam.edge B (pr1 e)) variable {B : fam G} definition fam (Q : fam (ctxext B)) : fam (ctxext (wk.ctx A B)) := fam.mk ( Ξ» p, fam.vertex Q ⟨pr1 (pr1 p),pr2 p⟩) ( Ξ» p q e, fam.edge Q ⟨(pr1 (pr1 e)),pr2 e⟩) variable {Q : graphs.fam (ctxext B)} definition tm (g : graphs.tm Q) : tm (wk.fam A Q) := tm.mk ( Ξ» p, tm.vertex g (⟨pr1 (pr1 p),pr2 p⟩)) ( Ξ» p q e, tm.edge g (⟨pr1 (pr1 e),pr2 e⟩)) end wk namespace proj -- The graph model is a projection algebra variables {G : ctx} {A : fam G} definition idm : tm (wk.ctx A A) := tm.mk ( Ξ» p, pr2 p) ( Ξ» p q e, pr2 e) end proj namespace subst -- The graph model is a substitution algebra variables {G : ctx} {A : fam G} (x : tm A) definition ctx (P : fam (ctxext A)) : fam G := fam.mk ( Ξ» i, fam.vertex P ⟨i, tm.vertex x i⟩) ( Ξ» i j e, fam.edge P ⟨e, tm.edge x e⟩) definition fam {P : fam (ctxext A)} (Q : fam (ctxext P)) : fam (ctxext (subst.ctx x P)) := fam.mk ( Ξ» p, fam.vertex Q ⟨⟨pr1 p, tm.vertex x (pr1 p)⟩, pr2 p⟩) ( Ξ» p q e, fam.edge Q ⟨⟨pr1 e, tm.edge x (pr1 e)⟩, pr2 e⟩) definition tm0 {P : graphs.fam (ctxext A)} (f : tm P) : tm (subst.ctx x P) := tm.mk ( Ξ» i, tm.vertex f ⟨i, tm.vertex x i⟩) ( Ξ» i j e, tm.edge f ⟨e, tm.edge x e⟩) definition tm {P : graphs.fam (ctxext A)} {Q : graphs.fam (ctxext P)} (g : tm Q) : tm (subst.fam x Q) := tm.mk ( Ξ» p, tm.vertex g ⟨⟨pr1 p, tm.vertex x (pr1 p)⟩, pr2 p⟩) ( Ξ» p q e, tm.edge g ⟨⟨pr1 e, tm.edge x (pr1 e)⟩, pr2 e⟩) end subst namespace sigma -- Sigma graphs variables {G : ctx} {A : fam G} -- Using the structure of the graph model, we can define a structure consisting of those graphs which satisfy the rules for dependent pair types. structure ax (P : fam (ctxext A)) := ( intr : fam G) ( cons : tm (wk.ctx P (wk.ctx A intr))) ( ind : Ξ  {Q : fam (ctxext intr)}, tm (subst.ctx cons (wk.fam P (wk.fam A Q))) β†’ tm Q) ( comp : Ξ  {Q : fam (ctxext intr)} (s : tm (subst.ctx cons (wk.fam P (wk.fam A Q)))), subst.tm0 cons (wk.tm P (wk.tm A (ind s))) = s) end sigma section Types_as_graphs -- Types as graphs. definition Delta (A : Type) : ctx := ctx.mk A (Ξ» x y, x = y) end Types_as_graphs end graphs
1c68445ecee9115bba991783ae675c6f1095c2cf
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/subst1.lean
8b2d822a039da9715776c40ee3dbdf77f63277e6
[ "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
672
lean
new_frontend set_option trace.Meta.Tactic.subst true theorem tst1 (x y z : Nat) : y = z β†’ x = x β†’ x = y β†’ x = z := begin intros h1 h2 h3; subst x; assumption end theorem tst2 (x y z : Nat) : y = z β†’ x = z + y β†’ x = z + z := begin intros h1 h2; subst h1; subst h2; exact rfl end def BV (n : Nat) : Type := Unit theorem tst3 (n m : Nat) (v : BV n) (w : BV m) (h1 : n = m) (h2 : forall (v1 v2 : BV n), v1 = v2) : v = cast (congrArg BV h1) w := begin subst h1; apply h2 end theorem tst4 (n m : Nat) (v : BV n) (w : BV m) (h1 : n = m) (h2 : forall (v1 v2 : BV n), v1 = v2) : v = cast (congrArg BV h1.symm) w := begin subst n; apply h2 end
65c873e8b84f2384ad071a76a0c0ae7f1bdf11b4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/CommandExtOverlap.lean
62ffc698dbd0a8936d4bd104a7a0636c6c657bca
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
319
lean
syntax (name := mycheck) "#check" sepBy(term, ",") : command open Lean macro_rules (kind := mycheck) | `(#check $es,*) => let cmds := es.getElems.map $ fun e => mkNode `Lean.Parser.Command.check #[mkAtom "#check", e] pure $ mkNullNode cmds #check true #check true, true #check true, 1, 3, fun (x : Nat) => x + 1
8c2726f6ae2131b9d60caca072acdf884eb33bea
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/proofs/dc_neg.lean
212f98ea47289ca762ad426a3638706493ed6195
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
2,317
lean
import hilbert.wr.dc_neg import hilbert.wr.proofs.dc namespace clfrags namespace hilbert namespace wr namespace dc_neg theorem dcn₁_dc {a b c d e f : Prop} (h₁ : dc e f (dc c d (dc b a (neg a)))) : dc e f (dc c d b) := have hβ‚‚ : dc (dc e f c) (dc e f d) (dc b a (neg a)), from dc.dc₆' h₁, have h₃ : dc (dc e f c) (dc e f d) b, from dcn₁ hβ‚‚, show dc e f (dc c d b), from dc.dc₇' h₃ theorem dcnβ‚‚_dc {a b c d e f : Prop} (h₁ : dc e f (dc c d b)) : dc e f (dc c d (dc b a (neg a))) := have hβ‚‚ : dc (dc e f c) (dc e f d) b, from dc.dc₆' h₁, have h₃ : dc (dc e f c) (dc e f d) (dc b a (neg a)), from dcnβ‚‚ hβ‚‚, show dc e f (dc c d (dc b a (neg a))), from dc.dc₇' h₃ theorem n₁ {a b : Prop} (h₁ : a) (hβ‚‚ : neg a) : b := have hβ‚‚ : dc a (neg a) b, from dc.dc₁ h₁ hβ‚‚, have h₃ : dc (dc a (neg a) b) a b, from dc.dc₁ hβ‚‚ h₁, have hβ‚„ : dc a b (dc a (neg a) b), from dc.dcβ‚…' (dc.dcβ‚„' h₃), have hβ‚… : dc a b (dc b a (neg a)), from dc.dcβ‚„ (dc.dcβ‚… hβ‚„), have h₆ : dc a b b, from dcn₁ hβ‚…, show b, from dc.dcβ‚‚ h₆ theorem dcn₃ {a b : Prop} (h₁ : b) : dc b a (neg a) := have hβ‚‚ : dc a b b, from dc.dc₃ h₁, have h₃ : dc a b (dc b a (neg a)), from dcnβ‚‚ hβ‚‚, have hβ‚„ : dc (dc a b b) (dc a b a) (neg a), from dc.dc₆' h₃, have hβ‚… : dc (neg a) (dc a b b) (dc a b a), from dc.dcβ‚„' (dc.dcβ‚…' hβ‚„), have h₆ : dc (neg a) (dc a b b) (dc b a a), from dc.dcβ‚… (dc.dcβ‚„ hβ‚…), have h₇ : dc (neg a) (dc a b b) a, from dc.dcβ‚‚_dc h₆, have hβ‚ˆ : dc (neg a) a (dc a b b), from dc.dcβ‚…' h₇, have h₉ : dc (neg a) a b, from dc.dcβ‚‚_dc hβ‚ˆ, show dc b a (neg a), from dc.dcβ‚…' (dc.dcβ‚„' (dc.dcβ‚…' h₉)) end dc_neg end wr end hilbert end clfrags
a9d5f3f86e92ee020111061316fb4789b4032a8b
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/analysis/filter.lean
bb90047a333c300b910fa4aba4f0069661312f98
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
11,824
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Computational realization of filters (experimental). -/ import order.filter open set filter /-- A `cfilter Ξ± Οƒ` is a realization of a filter (base) on `Ξ±`, represented by a type `Οƒ` together with operations for the top element and the binary inf operation. -/ structure cfilter (Ξ± Οƒ : Type*) [partial_order Ξ±] := (f : Οƒ β†’ Ξ±) (pt : Οƒ) (inf : Οƒ β†’ Οƒ β†’ Οƒ) (inf_le_left : βˆ€ a b : Οƒ, f (inf a b) ≀ f a) (inf_le_right : βˆ€ a b : Οƒ, f (inf a b) ≀ f b) variables {Ξ± : Type*} {Ξ² : Type*} {Οƒ : Type*} {Ο„ : Type*} namespace cfilter section variables [partial_order Ξ±] (F : cfilter Ξ± Οƒ) instance : has_coe_to_fun (cfilter Ξ± Οƒ) := ⟨_, cfilter.f⟩ @[simp] theorem coe_mk (f pt inf h₁ hβ‚‚ a) : (@cfilter.mk Ξ± Οƒ _ f pt inf h₁ hβ‚‚) a = f a := rfl /-- Map a cfilter to an equivalent representation type. -/ def of_equiv (E : Οƒ ≃ Ο„) : cfilter Ξ± Οƒ β†’ cfilter Ξ± Ο„ | ⟨f, p, g, h₁, hβ‚‚βŸ© := { f := Ξ» a, f (E.symm a), pt := E p, inf := Ξ» a b, E (g (E.symm a) (E.symm b)), inf_le_left := Ξ» a b, by simpa using h₁ (E.symm a) (E.symm b), inf_le_right := Ξ» a b, by simpa using hβ‚‚ (E.symm a) (E.symm b) } @[simp] theorem of_equiv_val (E : Οƒ ≃ Ο„) (F : cfilter Ξ± Οƒ) (a : Ο„) : F.of_equiv E a = F (E.symm a) := by cases F; refl end /-- The filter represented by a `cfilter` is the collection of supersets of elements of the filter base. -/ def to_filter (F : cfilter (set Ξ±) Οƒ) : filter Ξ± := { sets := {a | βˆƒ b, F b βŠ† a}, univ_sets := ⟨F.pt, subset_univ _⟩, sets_of_superset := Ξ» x y ⟨b, h⟩ s, ⟨b, subset.trans h s⟩, inter_sets := Ξ» x y ⟨a, hβ‚βŸ© ⟨b, hβ‚‚βŸ©, ⟨F.inf a b, subset_inter (subset.trans (F.inf_le_left _ _) h₁) (subset.trans (F.inf_le_right _ _) hβ‚‚)⟩ } @[simp] theorem mem_to_filter_sets (F : cfilter (set Ξ±) Οƒ) {a : set Ξ±} : a ∈ F.to_filter ↔ βˆƒ b, F b βŠ† a := iff.rfl end cfilter /-- A realizer for filter `f` is a cfilter which generates `f`. -/ structure filter.realizer (f : filter Ξ±) := (Οƒ : Type*) (F : cfilter (set Ξ±) Οƒ) (eq : F.to_filter = f) protected def cfilter.to_realizer (F : cfilter (set Ξ±) Οƒ) : F.to_filter.realizer := βŸ¨Οƒ, F, rfl⟩ namespace filter.realizer theorem mem_sets {f : filter Ξ±} (F : f.realizer) {a : set Ξ±} : a ∈ f ↔ βˆƒ b, F.F b βŠ† a := by cases F; subst f; simp -- Used because it has better definitional equalities than the eq.rec proof def of_eq {f g : filter Ξ±} (e : f = g) (F : f.realizer) : g.realizer := ⟨F.Οƒ, F.F, F.eq.trans e⟩ /-- A filter realizes itself. -/ def of_filter (f : filter Ξ±) : f.realizer := ⟨f.sets, { f := subtype.val, pt := ⟨univ, univ_mem_sets⟩, inf := Ξ» ⟨x, hβ‚βŸ© ⟨y, hβ‚‚βŸ©, ⟨_, inter_mem_sets h₁ hβ‚‚βŸ©, inf_le_left := Ξ» ⟨x, hβ‚βŸ© ⟨y, hβ‚‚βŸ©, inter_subset_left x y, inf_le_right := Ξ» ⟨x, hβ‚βŸ© ⟨y, hβ‚‚βŸ©, inter_subset_right x y }, filter_eq $ set.ext $ Ξ» x, set_coe.exists.trans exists_sets_subset_iff⟩ /-- Transfer a filter realizer to another realizer on a different base type. -/ def of_equiv {f : filter Ξ±} (F : f.realizer) (E : F.Οƒ ≃ Ο„) : f.realizer := βŸ¨Ο„, F.F.of_equiv E, by refine eq.trans _ F.eq; exact filter_eq (set.ext $ Ξ» x, ⟨λ ⟨s, h⟩, ⟨E.symm s, by simpa using h⟩, Ξ» ⟨t, h⟩, ⟨E t, by simp [h]⟩⟩)⟩ @[simp] theorem of_equiv_Οƒ {f : filter Ξ±} (F : f.realizer) (E : F.Οƒ ≃ Ο„) : (F.of_equiv E).Οƒ = Ο„ := rfl @[simp] theorem of_equiv_F {f : filter Ξ±} (F : f.realizer) (E : F.Οƒ ≃ Ο„) (s : Ο„) : (F.of_equiv E).F s = F.F (E.symm s) := by delta of_equiv; simp /-- `unit` is a realizer for the principal filter -/ protected def principal (s : set Ξ±) : (principal s).realizer := ⟨unit, { f := Ξ» _, s, pt := (), inf := Ξ» _ _, (), inf_le_left := Ξ» _ _, le_refl _, inf_le_right := Ξ» _ _, le_refl _ }, filter_eq $ set.ext $ Ξ» x, ⟨λ ⟨_, s⟩, s, Ξ» h, ⟨(), h⟩⟩⟩ @[simp] theorem principal_Οƒ (s : set Ξ±) : (realizer.principal s).Οƒ = unit := rfl @[simp] theorem principal_F (s : set Ξ±) (u : unit) : (realizer.principal s).F u = s := rfl /-- `unit` is a realizer for the top filter -/ protected def top : (⊀ : filter Ξ±).realizer := (realizer.principal _).of_eq principal_univ @[simp] theorem top_Οƒ : (@realizer.top Ξ±).Οƒ = unit := rfl @[simp] theorem top_F (u : unit) : (@realizer.top Ξ±).F u = univ := rfl /-- `unit` is a realizer for the bottom filter -/ protected def bot : (βŠ₯ : filter Ξ±).realizer := (realizer.principal _).of_eq principal_empty @[simp] theorem bot_Οƒ : (@realizer.bot Ξ±).Οƒ = unit := rfl @[simp] theorem bot_F (u : unit) : (@realizer.bot Ξ±).F u = βˆ… := rfl /-- Construct a realizer for `map m f` given a realizer for `f` -/ protected def map (m : Ξ± β†’ Ξ²) {f : filter Ξ±} (F : f.realizer) : (map m f).realizer := ⟨F.Οƒ, { f := Ξ» s, image m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := Ξ» a b, image_subset _ (F.F.inf_le_left _ _), inf_le_right := Ξ» a b, image_subset _ (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ Ξ» x, by simp [cfilter.to_filter]; rw F.mem_sets; exact exists_congr (Ξ» s, image_subset_iff)⟩ @[simp] theorem map_Οƒ (m : Ξ± β†’ Ξ²) {f : filter Ξ±} (F : f.realizer) : (F.map m).Οƒ = F.Οƒ := rfl @[simp] theorem map_F (m : Ξ± β†’ Ξ²) {f : filter Ξ±} (F : f.realizer) (s) : (F.map m).F s = image m (F.F s) := rfl /-- Construct a realizer for `comap m f` given a realizer for `f` -/ protected def comap (m : Ξ± β†’ Ξ²) {f : filter Ξ²} (F : f.realizer) : (comap m f).realizer := ⟨F.Οƒ, { f := Ξ» s, preimage m (F.F s), pt := F.F.pt, inf := F.F.inf, inf_le_left := Ξ» a b, preimage_mono (F.F.inf_le_left _ _), inf_le_right := Ξ» a b, preimage_mono (F.F.inf_le_right _ _) }, filter_eq $ set.ext $ Ξ» x, by cases F; subst f; simp [cfilter.to_filter, mem_comap_sets]; exact ⟨λ ⟨s, h⟩, ⟨_, ⟨s, subset.refl _⟩, h⟩, Ξ» ⟨y, ⟨s, h⟩, hβ‚‚βŸ©, ⟨s, subset.trans (preimage_mono h) hβ‚‚βŸ©βŸ©βŸ© /-- Construct a realizer for the sup of two filters -/ protected def sup {f g : filter Ξ±} (F : f.realizer) (G : g.realizer) : (f βŠ” g).realizer := ⟨F.Οƒ Γ— G.Οƒ, { f := Ξ» ⟨s, t⟩, F.F s βˆͺ G.F t, pt := (F.F.pt, G.F.pt), inf := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ Ξ» x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨⟨s, subset.trans (subset_union_left _ _) h⟩, ⟨t, subset.trans (subset_union_right _ _) h⟩⟩, Ξ» ⟨⟨s, hβ‚βŸ©, ⟨t, hβ‚‚βŸ©βŸ©, ⟨s, t, union_subset h₁ hβ‚‚βŸ©βŸ©βŸ© /-- Construct a realizer for the inf of two filters -/ protected def inf {f g : filter Ξ±} (F : f.realizer) (G : g.realizer) : (f βŠ“ g).realizer := ⟨F.Οƒ Γ— G.Οƒ, { f := Ξ» ⟨s, t⟩, F.F s ∩ G.F t, pt := (F.F.pt, G.F.pt), inf := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, (F.F.inf a b, G.F.inf a' b'), inf_le_left := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _), inf_le_right := Ξ» ⟨a, a'⟩ ⟨b, b'⟩, inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) }, filter_eq $ set.ext $ Ξ» x, by cases F; cases G; substs f g; simp [cfilter.to_filter]; exact ⟨λ ⟨s, t, h⟩, ⟨_, ⟨s, subset.refl _⟩, _, ⟨t, subset.refl _⟩, h⟩, Ξ» ⟨y, ⟨s, hβ‚βŸ©, z, ⟨t, hβ‚‚βŸ©, h⟩, ⟨s, t, subset.trans (inter_subset_inter h₁ hβ‚‚) h⟩⟩⟩ /-- Construct a realizer for the cofinite filter -/ protected def cofinite [decidable_eq Ξ±] : (@cofinite Ξ±).realizer := ⟨finset Ξ±, { f := Ξ» s, {a | a βˆ‰ s}, pt := βˆ…, inf := (βˆͺ), inf_le_left := Ξ» s t a, mt (finset.mem_union_left _), inf_le_right := Ξ» s t a, mt (finset.mem_union_right _) }, filter_eq $ set.ext $ Ξ» x, by simp [cfilter.to_filter]; exactI ⟨λ ⟨s, h⟩, finite_subset (finite_mem_finset s) (compl_subset_comm.1 h), Ξ» ⟨fs⟩, ⟨(-x).to_finset, Ξ» a (h : a βˆ‰ (-x).to_finset), classical.by_contradiction $ Ξ» h', h (mem_to_finset.2 h')⟩⟩⟩ /-- Construct a realizer for filter bind -/ protected def bind {f : filter Ξ±} {m : Ξ± β†’ filter Ξ²} (F : f.realizer) (G : βˆ€ i, (m i).realizer) : (f.bind m).realizer := ⟨Σ s : F.Οƒ, Ξ  i ∈ F.F s, (G i).Οƒ, { f := Ξ» ⟨s, f⟩, ⋃ i ∈ F.F s, (G i).F (f i H), pt := ⟨F.F.pt, Ξ» i H, (G i).F.pt⟩, inf := Ξ» ⟨a, f⟩ ⟨b, f'⟩, ⟨F.F.inf a b, Ξ» i h, (G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩, inf_le_left := Ξ» ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : Ξ±) (H : i ∈ F.F (F.F.inf a b)), _) β†’ x ∈ ⋃ i (H : i ∈ F.F a), ((G i).F) (f i H), by simp; exact Ξ» i h₁ hβ‚‚, ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ hβ‚‚βŸ©, inf_le_right := Ξ» ⟨a, f⟩ ⟨b, f'⟩ x, show (x ∈ ⋃ (i : Ξ±) (H : i ∈ F.F (F.F.inf a b)), _) β†’ x ∈ ⋃ i (H : i ∈ F.F b), ((G i).F) (f' i H), by simp; exact Ξ» i h₁ hβ‚‚, ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ hβ‚‚βŸ© }, filter_eq $ set.ext $ Ξ» x, by cases F with _ F _; subst f; simp [cfilter.to_filter, mem_bind_sets]; exact ⟨λ ⟨s, f, h⟩, ⟨F s, ⟨s, subset.refl _⟩, Ξ» i H, (G i).mem_sets.2 ⟨f i H, Ξ» a h', h ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, h'⟩⟩⟩, Ξ» ⟨y, ⟨s, h⟩, f⟩, let ⟨f', h'⟩ := classical.axiom_of_choice (Ξ» i:F s, (G i).mem_sets.1 (f i (h i.2))) in ⟨s, Ξ» i h, f' ⟨i, h⟩, Ξ» a ⟨_, ⟨i, rfl⟩, _, ⟨H, rfl⟩, m⟩, h' ⟨_, H⟩ m⟩⟩⟩ /-- Construct a realizer for indexed supremum -/ protected def Sup {f : Ξ± β†’ filter Ξ²} (F : βˆ€ i, (f i).realizer) : (⨆ i, f i).realizer := let F' : (⨆ i, f i).realizer := ((realizer.bind realizer.top F).of_eq $ filter_eq $ set.ext $ by simp [filter.bind, eq_univ_iff_forall, supr_sets_eq]) in F'.of_equiv $ show (Ξ£ u:unit, Ξ  (i : Ξ±), true β†’ (F i).Οƒ) ≃ Ξ  i, (F i).Οƒ, from ⟨λ⟨_,f⟩ i, f i ⟨⟩, Ξ» f, ⟨(), Ξ» i _, f i⟩, Ξ» ⟨⟨⟩, f⟩, by dsimp; congr; simp, Ξ» f, rfl⟩ /-- Construct a realizer for the product of filters -/ protected def prod {f g : filter Ξ±} (F : f.realizer) (G : g.realizer) : (f.prod g).realizer := (F.comap _).inf (G.comap _) theorem le_iff {f g : filter Ξ±} (F : f.realizer) (G : g.realizer) : f ≀ g ↔ βˆ€ b : G.Οƒ, βˆƒ a : F.Οƒ, F.F a ≀ G.F b := ⟨λ H t, F.mem_sets.1 (H (G.mem_sets.2 ⟨t, subset.refl _⟩)), Ξ» H x h, F.mem_sets.2 $ let ⟨s, hβ‚βŸ© := G.mem_sets.1 h, ⟨t, hβ‚‚βŸ© := H s in ⟨t, subset.trans hβ‚‚ hβ‚βŸ©βŸ© theorem tendsto_iff (f : Ξ± β†’ Ξ²) {l₁ : filter Ξ±} {lβ‚‚ : filter Ξ²} (L₁ : l₁.realizer) (Lβ‚‚ : lβ‚‚.realizer) : tendsto f l₁ lβ‚‚ ↔ βˆ€ b, βˆƒ a, βˆ€ x ∈ L₁.F a, f x ∈ Lβ‚‚.F b := (le_iff (L₁.map f) Lβ‚‚).trans $ forall_congr $ Ξ» b, exists_congr $ Ξ» a, image_subset_iff theorem ne_bot_iff {f : filter Ξ±} (F : f.realizer) : f β‰  βŠ₯ ↔ βˆ€ a : F.Οƒ, F.F a β‰  βˆ… := by haveI := classical.prop_decidable; rw [not_iff_comm, ← lattice.le_bot_iff, F.le_iff realizer.bot]; simp [not_forall]; exact ⟨λ ⟨x, e⟩ _, ⟨x, le_of_eq e⟩, Ξ» h, let ⟨x, h⟩ := h () in ⟨x, lattice.le_bot_iff.1 h⟩⟩ end filter.realizer
3d99fb187071e7674da32dfe3586334edce18a5f
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Elab/PreDefinition/Basic.lean
53e67e9522362460dbe6b0bd0143fad2e277941b
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,850
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.SCC import Lean.Meta.AbstractNestedProofs import Lean.Elab.Term import Lean.Elab.DefView import Lean.Elab.PreDefinition.MkInhabitant namespace Lean.Elab open Meta open Term /- A (potentially recursive) definition. The elaborator converts it into Kernel definitions using many different strategies. -/ structure PreDefinition where ref : Syntax kind : DefKind lparams : List Name modifiers : Modifiers declName : Name type : Expr value : Expr deriving Inhabited def instantiateMVarsAtPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← instantiateMVars preDef.type), value := (← instantiateMVars preDef.value) } private def levelMVarToParamExpr (e : Expr) : StateRefT Nat TermElabM Expr := do let nextIdx ← get let (e, nextIdx) ← levelMVarToParam e nextIdx; set nextIdx; pure e private def levelMVarToParamPreDeclsAux (preDefs : Array PreDefinition) : StateRefT Nat TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← levelMVarToParamExpr preDef.type), value := (← levelMVarToParamExpr preDef.value) } def levelMVarToParamPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := (levelMVarToParamPreDeclsAux preDefs).run' 1 private def getLevelParamsPreDecls (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (List Name) := do let mut s : CollectLevelParams.State := {} for preDef in preDefs do s := collectLevelParams s preDef.type s := collectLevelParams s preDef.value match sortDeclLevelParams scopeLevelNames allUserLevelNames s.params with | Except.error msg => throwError msg | Except.ok levelParams => pure levelParams private def shareCommon (preDefs : Array PreDefinition) : Array PreDefinition := let result : Std.ShareCommonM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← Std.withShareCommon preDef.type), value := (← Std.withShareCommon preDef.value) } result.run def fixLevelParams (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (Array PreDefinition) := do let preDefs := shareCommon preDefs let lparams ← getLevelParamsPreDecls preDefs scopeLevelNames allUserLevelNames let us := lparams.map mkLevelParam let fixExpr (e : Expr) : Expr := e.replace fun c => match c with | Expr.const declName _ _ => if preDefs.any fun preDef => preDef.declName == declName then some $ Lean.mkConst declName us else none | _ => none pure $ preDefs.map fun preDef => { preDef with type := fixExpr preDef.type, value := fixExpr preDef.value, lparams := lparams } def applyAttributesOf (preDefs : Array PreDefinition) (applicationTime : AttributeApplicationTime) : TermElabM Unit := do for preDef in preDefs do applyAttributesAt preDef.declName preDef.modifiers.attrs applicationTime def abstractNestedProofs (preDef : PreDefinition) : MetaM PreDefinition := if preDef.kind.isTheorem || preDef.kind.isExample then pure preDef else do let value ← Meta.abstractNestedProofs preDef.declName preDef.value pure { preDef with value := value } /- Auxiliary method for (temporarily) adding pre definition as an axiom -/ def addAsAxiom (preDef : PreDefinition) : MetaM Unit := do withRef preDef.ref do addDecl <| Declaration.axiomDecl { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, isUnsafe := preDef.modifiers.isUnsafe } private def addNonRecAux (preDef : PreDefinition) (compile : Bool) : TermElabM Unit := withRef preDef.ref do let preDef ← abstractNestedProofs preDef let env ← getEnv let decl := match preDef.kind with | DefKind.Β«exampleΒ» => unreachable! | DefKind.Β«theoremΒ» => Declaration.thmDecl { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, value := preDef.value } | DefKind.Β«opaqueΒ» => Declaration.opaqueDecl { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, value := preDef.value, isUnsafe := preDef.modifiers.isUnsafe } | DefKind.Β«abbrevΒ» => Declaration.defnDecl { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, value := preDef.value, hints := ReducibilityHints.Β«abbrevΒ», safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } | DefKind.Β«defΒ» => Declaration.defnDecl { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, value := preDef.value, hints := ReducibilityHints.regular (getMaxHeight env preDef.value + 1), safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } addDecl decl applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking if compile && !preDef.kind.isTheorem then compileDecl decl applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation def addAndCompileNonRec (preDef : PreDefinition) : TermElabM Unit := do addNonRecAux preDef true def addNonRec (preDef : PreDefinition) : TermElabM Unit := do addNonRecAux preDef false def addAndCompileUnsafe (preDefs : Array PreDefinition) (safety := DefinitionSafety.unsafe) : TermElabM Unit := withRef preDefs[0].ref do let decl := Declaration.mutualDefnDecl $ preDefs.toList.map fun preDef => { name := preDef.declName, lparams := preDef.lparams, type := preDef.type, value := preDef.value, safety := safety, hints := ReducibilityHints.opaque } addDecl decl applyAttributesOf preDefs AttributeApplicationTime.afterTypeChecking compileDecl decl applyAttributesOf preDefs AttributeApplicationTime.afterCompilation pure () def addAndCompilePartialRec (preDefs : Array PreDefinition) : TermElabM Unit := do addAndCompileUnsafe (safety := DefinitionSafety.partial) <| preDefs.map fun preDef => { preDef with declName := Compiler.mkUnsafeRecName preDef.declName, value := preDef.value.replace fun e => match e with | Expr.const declName us _ => if preDefs.any fun preDef => preDef.declName == declName then some $ mkConst (Compiler.mkUnsafeRecName declName) us else none | _ => none, modifiers := {} } end Lean.Elab
7f32e9ea3fdadcc940dbeabce2abd04170be3dd8
f4bff2062c030df03d65e8b69c88f79b63a359d8
/world_plans/supinf_experiments.lean
71165e70cbf9784d00407f198ac79e2d3385d05e
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,395
lean
import data.real.basic -- Lean has a good API for reals so I'm happy to use them. import algebra.pointwise -- for addition on set ℝ import for_mathlib.add_comm_monoid local attribute [instance] set.add_comm_monoid /- Goal : prove the following theorem. Sup(X+Y)=Sup(X)+Sup(Y). Goal after that: state and prove Richard Thomas' problem sheet question. -/ /-- This should be part of a controlled natural language, not a Lean definition -/ class bounded_above (X : set ℝ) : Prop := (is_bounded_above : bounded (≀) X) local attribute [instance] set.add_comm_monoid instance (X Y : Type*) : nonempty X β†’ nonempty Y β†’ nonempty (X Γ— Y) | ⟨x⟩ ⟨y⟩ := ⟨(x, y)⟩ --set_option pp.notation false #check βˆ€ (X : Type) (P : X β†’ Prop), {x : X | P x} /-- version of set_of without universes and {}s -/ def set_of' (X : Type) (P : X β†’ Prop) := {x : X | P x} #check set_of' #print set_of' /-- version of subtype without universes and {} -/ def subtype' (X : Type) (P : X β†’ Prop) := {x : X // P x} #check subtype' #check set_of' #check @set_of example : set_of' = @set_of := rfl #check subtype' -- question: relationship between subtype' and set_of' --set_option pp.notation false #check set_of' #print set_of #check subtype' #print subtype /- /- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/ structure subtype {Ξ± : Sort u} (p : Ξ± β†’ Prop) := (val : Ξ±) (property : p val) -/ #print set_of variables (R : Type) (P : R β†’ Prop) #check (@subtype.val R P : subtype P β†’ R) #check (@subtype.property R P : βˆ€ (c : subtype P), P (c.val)) #check set_of' R P -- set_of must be notation. example : set_of' R P = P := rfl #check subtype' R P #print prefix subtype def subtype'.val : subtype P β†’ R := subtype.val def subtype'.property : βˆ€ (c : subtype P), P (c.val) := subtype.property #check @coe_sort #check has_coe_to_sort example : @id _ = @set_of R := rfl -- set_of is the identity function example : set_of' R = id := rfl example : set R ≃ (R β†’ Prop) := { to_fun := id, inv_fun := set_of, -- id also works left_inv := Ξ» _, rfl, right_inv := Ξ» _, rfl } #check subtype' R theorem real.add_nonempty (X Y : set ℝ) : nonempty X β†’ nonempty Y β†’ nonempty (subtype' ℝ ((X + Y) : set ℝ)) | ⟨x⟩ ⟨y⟩ := ⟨⟨x.val + y.val, ⟨x.val, x.property, y.val, y.2, rfl⟩⟩⟩ --set_option pp.notation false -- coe_sort is β†₯ #check real.add_nonempty #print has_coe_to_sort /- class has_coe_to_sort (a : Sort u) : Type (max u (v+1)) := (S : Sort v) (coe : a β†’ S) -/ example : has_coe_to_sort (set ℝ) := by apply_instance -- set.has_coe_to_sort #print set.has_coe_to_sort #check set.has_coe_to_sort.coe -- : set X β†’ has_coe_to_sort.S (set X) #check set.has_coe_to_sort.S --: set ℝ β†’ Type #check (subtype' ℝ : (ℝ β†’ Prop) β†’ Type) example : subtype' R P = set.has_coe_to_sort.S := sorry --#check @coe_sort : #exit theorem real.Sup_add -- or is it real.Sup.add? (X : set ℝ) (h1X : nonempty X) (h2X : bounded_above X) (Y : set ℝ) (h1Y : nonempty Y) (h2Y : bounded_above Y) : real.Sup {z : ℝ | βˆƒ (x ∈ X) (y ∈ Y), z = x + y} = real.Sup X + real.Sup Y := begin apply le_antisymm, { rw real.Sup_le, sorry }, { sorry } end /- Question: should there be an "add top and bottom" type? Question: should instance : has_add (set ℝ) exist? -/ /- /-- It's zero if the sup doesn't exist -/ def Sup (S : set ℝ) : ℝ theorem Sup_le (S : set ℝ) (h₁ : βˆƒ x, x ∈ S) (hβ‚‚ : βˆƒ x, βˆ€ y ∈ S, y ≀ x) {y} : Sup S ≀ y ↔ βˆ€ z ∈ S, z ≀ y theorem lt_Sup (S : set ℝ) (h₁ : βˆƒ x, x ∈ S) (hβ‚‚ : βˆƒ x, βˆ€ y ∈ S, y ≀ x) {y} : y < Sup S ↔ βˆƒ z ∈ S, y < z theorem le_Sup (S : set ℝ) (hβ‚‚ : βˆƒ x, βˆ€ y ∈ S, y ≀ x) {x} (xS : x ∈ S) : x ≀ Sup S theorem Sup_le_ub (S : set ℝ) (h₁ : βˆƒ x, x ∈ S) {ub} (hβ‚‚ : βˆ€ y ∈ S, y ≀ ub) : Sup S ≀ ub lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := -/ /-- The type $$[-∞,+∞]$$ -/ def ereal : Type := with_bot (with_top ℝ) --def is_ub (X : set ℝ) (b : ℝ) := βˆ€ x ∈ X, x ≀ b --def is_lub (X : set ℝ) (l : ℝ) := is_ub X l ∧ /- theorem exists_sup (S : set ℝ) : (βˆƒ x, x ∈ S) β†’ (βˆƒ x, βˆ€ y ∈ S, y ≀ x) β†’ βˆƒ x, βˆ€ y, x ≀ y ↔ βˆ€ z ∈ S, z ≀ y -/
71866a55ec10f82cf6f0bbe380048f0759544761
d5ecf6c46a2f605470a4a7724909dc4b9e7350e0
/group_theory/subgroup.lean
dd2edc80c1f7e2060f2f66edff348b238fe11e6a
[ "Apache-2.0" ]
permissive
MonoidMusician/mathlib
41f79df478987a636b735c338396813d2e8e44c4
72234ef1a050eea3a2197c23aeb345fc13c08ff3
refs/heads/master
1,583,672,205,771
1,522,892,143,000
1,522,892,143,000
128,144,032
0
0
Apache-2.0
1,522,892,144,000
1,522,890,892,000
Lean
UTF-8
Lean
false
false
9,719
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl -/ import data.finset algebra.big_operators data.equiv data.set data.nat.basic set_theory.cardinal open set function finset universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {s : set Ξ±} {a a₁ aβ‚‚ : Ξ±} namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq Ξ±] {f : β„€ β†’ Ξ±} {a : Ξ±} {n : β„•} (hn : 0 < n) (h : βˆ€i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (Ξ»i, f i) := suffices (βˆƒi, f (i % n) = a) ↔ βˆƒi, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : β„€), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≀ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset variables [group Ξ±] /-- A subset of a group closed under the group operations. -/ structure is_subgroup (s : set Ξ±) : Prop := (one_mem : (1:Ξ±) ∈ s) (mul_inv_mem : βˆ€a∈s, βˆ€b∈s, a * b⁻¹ ∈ s) def cosets (s : set Ξ±) : set (set Ξ±) := range (Ξ»a, (*) a '' s) namespace is_subgroup lemma inv_mem (hs : is_subgroup s) (h : a ∈ s) : a⁻¹ ∈ s := have 1 * a⁻¹ ∈ s, from hs.mul_inv_mem _ hs.one_mem _ h, by simpa lemma inv_mem_iff (hs : is_subgroup s) : a⁻¹ ∈ s ↔ a ∈ s := iff.intro (assume h, have a⁻¹⁻¹ ∈ s, from hs.inv_mem h, by simpa) hs.inv_mem lemma mul_mem (hs : is_subgroup s) (h₁ : a₁ ∈ s) (hβ‚‚ : aβ‚‚ ∈ s) : a₁ * aβ‚‚ ∈ s := have a₁ * a₂⁻¹⁻¹ ∈ s, from hs.mul_inv_mem _ h₁ _ (hs.inv_mem hβ‚‚), by simpa lemma mul_image (hs : is_subgroup s) (a : Ξ±) (ha : a ∈ s) : (*) a '' s = s := ext $ assume a', iff.intro (assume ⟨a'', ha'', eq⟩, eq β–Έ hs.mul_mem ha ha'') (assume ha', ⟨a⁻¹ * a', hs.mul_mem (hs.inv_mem ha) ha', by simp⟩) lemma injective_mul {a : Ξ±} : injective ((*) a) := assume a₁ aβ‚‚ h, have a⁻¹ * a * a₁ = a⁻¹ * a * aβ‚‚, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this lemma subgroup_mem_cosets (hs : is_subgroup s) : s ∈ cosets s := ⟨1, hs.mul_image _ hs.one_mem⟩ lemma cosets_disjoint (hs : is_subgroup s) : βˆ€{s₁ sβ‚‚ : set Ξ±}, s₁ ∈ cosets s β†’ sβ‚‚ ∈ cosets s β†’ βˆ€{a}, a ∈ s₁ β†’ a ∈ sβ‚‚ β†’ s₁ = sβ‚‚ | _ _ ⟨b₁, rfl⟩ ⟨bβ‚‚, rfl⟩ a ⟨c₁, hc₁, eqβ‚βŸ© ⟨cβ‚‚, hcβ‚‚, eqβ‚‚βŸ© := have b_eq : b₁ = bβ‚‚ * cβ‚‚ * c₁⁻¹, by rw [eq_mul_inv_iff_mul_eq, eq₁, eqβ‚‚], have hc : cβ‚‚ * c₁⁻¹ ∈ s, from hs.mul_mem hcβ‚‚ (hs.inv_mem hc₁), calc (*) b₁ '' s = (*) bβ‚‚ '' ((*) (cβ‚‚ * c₁⁻¹) '' s) : by rw [←image_comp, (∘), b_eq]; apply image_congr _; simp [mul_assoc] ... = (*) bβ‚‚ '' s : by rw [hs.mul_image _ hc] lemma pairwise_cosets_disjoint (hs : is_subgroup s) : pairwise_on (cosets s) disjoint := assume s₁ h₁ sβ‚‚ hβ‚‚ ne, eq_empty_iff_forall_not_mem.mpr $ assume a ⟨ha₁, haβ‚‚βŸ©, ne $ hs.cosets_disjoint h₁ hβ‚‚ ha₁ haβ‚‚ lemma cosets_equiv_subgroup (hs : is_subgroup s) : βˆ€{t : set Ξ±}, t ∈ cosets s β†’ nonempty (t ≃ s) | _ ⟨a, rfl⟩ := ⟨(equiv.set.image ((*) a) s injective_mul).symm⟩ lemma Union_cosets_eq_univ (hs : is_subgroup s) : ⋃₀ cosets s = univ := eq_univ_of_forall $ assume a, ⟨(*) a '' s, mem_range_self _, ⟨1, hs.one_mem, mul_one _⟩⟩ lemma group_equiv_cosets_times_subgroup (hs : is_subgroup s) : nonempty (Ξ± ≃ (cosets s Γ— s)) := ⟨calc Ξ± ≃ (@set.univ Ξ±) : (equiv.set.univ Ξ±).symm ... ≃ (⋃t∈cosets s, t) : by rw [←hs.Union_cosets_eq_univ]; simp ... ≃ (Ξ£t:cosets s, t) : equiv.set.bUnion_eq_sigma_of_disjoint hs.pairwise_cosets_disjoint ... ≃ (Ξ£t:cosets s, s) : equiv.sigma_congr_right $ λ⟨t, ht⟩, classical.choice $ hs.cosets_equiv_subgroup ht ... ≃ (cosets s Γ— s) : equiv.sigma_equiv_prod _ _⟩ end is_subgroup lemma is_subgroup_range_gpow : is_subgroup (range $ (^) a) := ⟨⟨0, rfl⟩, assume a ⟨i, ha⟩ b ⟨j, hb⟩, ⟨i - j, by simp [gpow_add, gpow_neg, ha.symm, hb.symm]⟩⟩ section finite_group variables [fintype Ξ±] [decidable_eq Ξ±] lemma exists_gpow_eq_one (a : Ξ±) : βˆƒiβ‰ 0, a ^ (i:β„€) = 1 := have Β¬ injective (Ξ»i, a ^ i), from not_injective_int_fintype, let ⟨i, j, a_eq, ne⟩ := show βˆƒ(i j : β„€), a ^ i = a ^ j ∧ i β‰  j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ local infixr `^m`:73 := @has_pow.pow Ξ± β„• monoid.has_pow lemma exists_pow_eq_one (a : Ξ±) : βˆƒiβ‰ 0, a ^m i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, by simp [int.of_nat_eq_coe, *] at *, eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end /-- `order_of a` is the order of the element, i.e. the `n β‰₯ 1`, s.t. `a ^ n = 1` -/ def order_of (a : Ξ±) : β„• := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : Ξ±) : a ^m order_of a = 1 := let ⟨h₁, hβ‚‚βŸ© := nat.find_spec (exists_pow_eq_one a) in hβ‚‚ lemma order_of_ne_zero (a : Ξ±) : order_of a β‰  0 := let ⟨h₁, hβ‚‚βŸ© := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : β„•} (a : Ξ±) (h : n ≀ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^m n = a ^m m) : n = m := decidable.by_contradiction $ assume ne : n β‰  m, have h₁ : m - n β‰  0, by simp [nat.sub_eq_iff_eq_add h, ne.symm], have hβ‚‚ : a ^m (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≀ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, hβ‚‚βŸ©, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : β„•} (a : Ξ±) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^m n = a ^m m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≀ fintype.card Ξ± := finset.card_le_of_inj_on ((^m) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : β„•} : a ^m n = a ^m (n % order_of a) := calc a ^m n = a ^m (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^m (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : β„€} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_range_gpow_iff_mem_range_order_of {a a' : Ξ±} : a' ∈ range ((^) a) ↔ a' ∈ (finset.range (order_of a)).image ((^m) a) := finset.mem_range_iff_mem_finset_range_of_mod_eq (nat.pos_iff_ne_zero.mpr (order_of_ne_zero a)) (assume i, gpow_eq_mod_order_of.symm) instance decidable_range_gpow : decidable_pred (range ((^) a)) := assume a', decidable_of_iff (a' ∈ (finset.range (order_of a)).image ((^m) a)) mem_range_gpow_iff_mem_range_order_of.symm section local attribute [instance] set_fintype lemma order_eq_card_range_gpow : order_of a = fintype.card (range ((^) a)) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact Ξ»n hn, ⟨gpow a n, mem_range_self n⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ nat.pos_iff_ne_zero.mpr $ order_of_ne_zero a, have 0 ≀ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end section classical local attribute [instance] classical.prop_decidable -- TODO: use cardinal theory, or introduce `card : set Ξ± β†’ β„•` lemma order_of_dvd_card_univ : order_of a ∣ fintype.card Ξ± := let s := range $ gpow a in have hs : is_subgroup s, from is_subgroup_range_gpow, let ⟨equiv⟩ := hs.group_equiv_cosets_times_subgroup in have ft_prod : fintype (cosets s Γ— s), from fintype.of_equiv Ξ± equiv, have ft_s : fintype s, from @fintype.fintype_prod_right _ _ _ ft_prod ⟨⟨s, hs.subgroup_mem_cosets⟩⟩, have ft_cosets : fintype (cosets s), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, hs.one_mem⟩⟩, have ft : fintype (cosets s Γ— s), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card Ξ± = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card Ξ± = @fintype.card _ ft_prod : (@fintype.card_eq _ _ _ ft_prod).2 hs.group_equiv_cosets_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eqβ‚‚ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_range_gpow ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (cosets s) ft_cosets) $ by rw [eq₁, eqβ‚‚, mul_comm] end classical end end finite_group
08625635ad603c2728f76d513c36bb0a8fbd269d
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/data/complex/is_R_or_C.lean
5c23343e3a11934acbcb25c28c1c41dcc240671b
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,262
lean
/- Copyright (c) 2020 FrΓ©dΓ©ric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: FrΓ©dΓ©ric Dupuis -/ import analysis.normed_space.basic import analysis.complex.basic /-! # `is_R_or_C`: a typeclass for ℝ or β„‚ This file defines the typeclass `is_R_or_C` intended to have only two instances: ℝ and β„‚. It is meant for definitions and theorems which hold for both the real and the complex case, and in particular when the real case follows directly from the complex case by setting `re` to `id`, `im` to zero and so on. Its API follows closely that of β„‚. Possible applications include defining inner products and Hilbert spaces for both the real and complex case. One would produce the definitions and proof for an arbitrary field of this typeclass, which basically amounts to doing the complex case, and the two cases then fall out immediately from the two instances of the class. ## Implementation notes The coercion from reals into an `is_R_or_C` field is done by registering `algebra_map ℝ K` as a `has_coe_t`. For this to work, we must proceed carefully to avoid problems involving circular coercions in the case `K=ℝ`; in particular, we cannot use the plain `has_coe` and must set priorities carefully. This problem was already solved for `β„•`, and we copy the solution detailed in `data/nat/cast`. See also Note [coercion into rings] for more details. In addition, several lemmas need to be set at priority 900 to make sure that they do not override their counterparts in `complex.lean` (which causes linter errors). -/ open_locale big_operators section local notation `π“š` := algebra_map ℝ _ /-- This typeclass captures properties shared by ℝ and β„‚, with an API that closely matches that of β„‚. -/ class is_R_or_C (K : Type*) extends nondiscrete_normed_field K, normed_algebra ℝ K, complete_space K := (re : K β†’+ ℝ) (im : K β†’+ ℝ) (conj : K β†’+* K) (I : K) -- Meant to be set to 0 for K=ℝ (I_re_ax : re I = 0) (I_mul_I_ax : I = 0 ∨ I * I = -1) (re_add_im_ax : βˆ€ (z : K), π“š (re z) + π“š (im z) * I = z) (of_real_re_ax : βˆ€ r : ℝ, re (π“š r) = r) (of_real_im_ax : βˆ€ r : ℝ, im (π“š r) = 0) (mul_re_ax : βˆ€ z w : K, re (z * w) = re z * re w - im z * im w) (mul_im_ax : βˆ€ z w : K, im (z * w) = re z * im w + im z * re w) (conj_re_ax : βˆ€ z : K, re (conj z) = re z) (conj_im_ax : βˆ€ z : K, im (conj z) = -(im z)) (conj_I_ax : conj I = -I) (norm_sq_eq_def_ax : βˆ€ (z : K), βˆ₯zβˆ₯^2 = (re z) * (re z) + (im z) * (im z)) (mul_im_I_ax : βˆ€ (z : K), (im z) * im I = im z) (inv_def_ax : βˆ€ (z : K), z⁻¹ = conj z * π“š ((βˆ₯zβˆ₯^2)⁻¹)) (div_I_ax : βˆ€ (z : K), z / I = -(z * I)) end namespace is_R_or_C variables {K : Type*} [is_R_or_C K] local postfix `†`:100 := @is_R_or_C.conj K _ /- The priority must be set at 900 to ensure that coercions are tried in the right order. See Note [coercion into rings], or `data/nat/cast.lean` for more details. -/ @[priority 900] noncomputable instance algebra_map_coe : has_coe_t ℝ K := ⟨algebra_map ℝ K⟩ lemma of_real_alg (x : ℝ) : (x : K) = x β€’ (1 : K) := algebra.algebra_map_eq_smul_one x lemma algebra_map_eq_of_real : ⇑(algebra_map ℝ K) = coe := rfl @[simp] lemma re_add_im (z : K) : ((re z) : K) + (im z) * I = z := is_R_or_C.re_add_im_ax z @[simp, norm_cast] lemma of_real_re : βˆ€ r : ℝ, re (r : K) = r := is_R_or_C.of_real_re_ax @[simp, norm_cast] lemma of_real_im : βˆ€ r : ℝ, im (r : K) = 0 := is_R_or_C.of_real_im_ax @[simp] lemma mul_re : βˆ€ z w : K, re (z * w) = re z * re w - im z * im w := is_R_or_C.mul_re_ax @[simp] lemma mul_im : βˆ€ z w : K, im (z * w) = re z * im w + im z * re w := is_R_or_C.mul_im_ax theorem inv_def (z : K) : z⁻¹ = conj z * ((βˆ₯zβˆ₯^2)⁻¹:ℝ) := is_R_or_C.inv_def_ax z theorem ext_iff : βˆ€ {z w : K}, z = w ↔ re z = re w ∧ im z = im w := Ξ» z w, { mp := by { rintro rfl, cc }, mpr := by { rintro ⟨h₁,hβ‚‚βŸ©, rw [←re_add_im z, ←re_add_im w, h₁, hβ‚‚] } } theorem ext : βˆ€ {z w : K}, re z = re w β†’ im z = im w β†’ z = w := by { simp_rw ext_iff, cc } @[simp, norm_cast, priority 900] lemma of_real_zero : ((0 : ℝ) : K) = 0 := by rw [of_real_alg, zero_smul] @[simp] lemma zero_re' : re (0 : K) = (0 : ℝ) := re.map_zero @[simp, norm_cast, priority 900] lemma of_real_one : ((1 : ℝ) : K) = 1 := by rw [of_real_alg, one_smul] @[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re] @[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_inj {z w : ℝ} : (z : K) = (w : K) ↔ z = w := { mp := Ξ» h, by { convert congr_arg re h; simp only [of_real_re] }, mpr := Ξ» h, by rw h } @[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0] @[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) := by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re] @[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0] @[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) := by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im] @[simp, priority 900] theorem of_real_eq_zero {z : ℝ} : (z : K) = 0 ↔ z = 0 := by rw [←of_real_zero]; exact of_real_inj @[simp, norm_cast, priority 900] lemma of_real_add ⦃r s : ℝ⦄ : ((r + s : ℝ) : K) = r + s := by { apply (@is_R_or_C.ext_iff K _ ((r + s : ℝ) : K) (r + s)).mpr, simp } @[simp, norm_cast, priority 900] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : K) = bit0 (r : K) := ext_iff.2 $ by simp [bit0] @[simp, norm_cast, priority 900] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : K) = bit1 (r : K) := ext_iff.2 $ by simp [bit1] /- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/ lemma two_ne_zero : (2 : K) β‰  0 := begin intro h, rw [(show (2 : K) = ((2 : ℝ) : K), by norm_num), ←of_real_zero, of_real_inj] at h, linarith, end @[simp, norm_cast, priority 900] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : K) = -r := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : K) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : K) : re (↑r * z) = r * re z := by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero] lemma smul_re (r : ℝ) (z : K) : re (↑r * z) = r * (re z) := by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re] lemma smul_im (r : ℝ) (z : K) : im (↑r * z) = r * (im z) := by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im] lemma smul_re' : βˆ€ (r : ℝ) (z : K), re (r β€’ z) = r * (re z) := Ξ» r z, by { rw algebra.smul_def, apply smul_re } lemma smul_im' : βˆ€ (r : ℝ) (z : K), im (r β€’ z) = r * (im z) := Ξ» r z, by { rw algebra.smul_def, apply smul_im } /-- The real part in a `is_R_or_C` field, as a linear map. -/ noncomputable def re_lm : K β†’β‚—[ℝ] ℝ := { map_smul' := smul_re', .. re } @[simp] lemma re_lm_coe : (re_lm : K β†’ ℝ) = re := rfl /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ @[simp] lemma I_re : re (I : K) = 0 := I_re_ax @[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z @[simp] lemma I_im' (z : K) : im (I : K) * im z = im z := by rw [mul_comm, I_im _] lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax @[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z @[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z @[simp] lemma conj_of_real (r : ℝ) : conj (r : K) = (r : K) := by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] } @[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff] @[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff] lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 := ring_hom.map_eq_zero conj lemma eq_conj_iff_real {z : K} : conj z = z ↔ βˆƒ r : ℝ, z = (r : K) := begin split, { intro h, suffices : im z = 0, { use (re z), rw ← add_zero (coe _), convert (re_add_im z).symm, simp [this] }, contrapose! h, rw ← re_add_im z, simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax], rw [add_left_cancel_iff, ext_iff], simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] }, { rintros ⟨r, rfl⟩, apply conj_of_real } end variables (K) /-- Conjugation as a ring equivalence. This is used to convert the inner product into a sesquilinear product. -/ def conj_to_ring_equiv : K ≃+* Kα΅’α΅– := { to_fun := opposite.op ∘ conj, inv_fun := conj ∘ opposite.unop, left_inv := Ξ» x, by simp only [conj_conj, function.comp_app, opposite.unop_op], right_inv := Ξ» x, by simp only [conj_conj, opposite.op_unop, function.comp_app], map_mul' := Ξ» x y, by simp [mul_comm], map_add' := Ξ» x y, by simp } variables {K} @[simp] lemma ring_equiv_apply {x : K} : (conj_to_ring_equiv K x).unop = x† := rfl lemma eq_conj_iff_re {z : K} : conj z = z ↔ ((re z) : K) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, Ξ» h, ⟨_, h.symm⟩⟩ /-- The norm squared function. -/ def norm_sq : monoid_with_zero_hom K ℝ := { to_fun := Ξ» z, re z * re z + im z * im z, map_zero' := by simp, map_one' := by simp, map_mul' := Ξ» z w, by { simp, ring } } lemma norm_sq_eq_def {z : K} : βˆ₯zβˆ₯^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z lemma norm_sq_eq_def' (z : K) : norm_sq z = βˆ₯zβˆ₯^2 := by { rw norm_sq_eq_def, refl } @[simp] lemma norm_sq_of_real (r : ℝ) : βˆ₯(r : K)βˆ₯^2 = r * r := by simp [norm_sq_eq_def] lemma norm_sq_zero : norm_sq (0 : K) = 0 := norm_sq.map_zero lemma norm_sq_one : norm_sq (1 : K) = 1 := norm_sq.map_one lemma norm_sq_nonneg (z : K) : 0 ≀ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 := by { rw [norm_sq_eq_def'], simp [pow_two] } @[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z β‰  0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z := by simp [norm_sq_eq_def'] @[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : K) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) := by simp [norm_sq, pow_two]; ring lemma re_sq_le_norm_sq (z : K) : re z * re z ≀ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : K) : im z * im z ≀ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : K) : z * conj z = ((norm_sq z) : K) := by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : K) : z + conj z = 2 * (re z) := by simp [ext_iff, two_mul] /-- The pseudo-coercion `of_real` as a `ring_hom`. -/ noncomputable def of_real_hom : ℝ β†’+* K := algebra_map ℝ K /-- The coercion from reals as a `ring_hom`. -/ noncomputable def coe_hom : ℝ β†’+* K := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp, norm_cast, priority 900] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : K) = r - s := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_pow (r : ℝ) (n : β„•) : ((r ^ n : ℝ) : K) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : K) : z - conj z = (2 * im z) * I := by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax] lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) := by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg] lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = βˆ₯zβˆ₯ := begin have hβ‚‚ : βˆ₯zβˆ₯ = real.sqrt (βˆ₯zβˆ₯^2) := (real.sqrt_sqr (norm_nonneg z)).symm, rw [hβ‚‚], exact congr_arg real.sqrt (norm_sq_eq_def' z) end /-! ### Inversion -/ @[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp, norm_cast, priority 900] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : K) = r⁻¹ := begin rw ext_iff, by_cases r = 0, { simp [h] }, { simp; field_simp [h, norm_sq] }, end protected lemma inv_zero : (0⁻¹ : K) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : K} (h : z β‰  0) : z * z⁻¹ = 1 := by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def', mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast, priority 900] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : K) = r / s := (@is_R_or_C.coe_hom K _).map_div r s lemma div_re_of_real {z : K} {r : ℝ} : re (z / r) = re z / r := begin by_cases h : r = 0, { simp [h, of_real_zero] }, { change r β‰  0 at h, rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv], simp [norm_sq, div_mul_eq_div_mul_one_div, div_self h] } end @[simp, norm_cast, priority 900] lemma of_real_fpow (r : ℝ) (n : β„€) : ((r ^ n : ℝ) : K) = r ^ n := (@is_R_or_C.coe_hom K _).map_fpow r n lemma I_mul_I_of_nonzero : (I : K) β‰  0 β†’ (I : K) * I = -1 := by { have := I_mul_I_ax, tauto } @[simp] lemma div_I (z : K) : z / I = -(z * I) := begin by_cases h : (I : K) = 0, { simp [h] }, { field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] } end @[simp] lemma inv_I : (I : K)⁻¹ = -I := by { by_cases h : (I : K) = 0; field_simp [h] } @[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := (@norm_sq K _).map_inv' z @[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w := (@norm_sq K _).map_div z w lemma norm_conj {z : K} : βˆ₯conj zβˆ₯ = βˆ₯zβˆ₯ := by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj] lemma conj_inv {z : K} : conj (z⁻¹) = (conj z)⁻¹ := by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real] lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) := by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv] /-! ### Cast lemmas -/ @[simp, norm_cast, priority 900] theorem of_real_nat_cast (n : β„•) : ((n : ℝ) : K) = n := of_real_hom.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : β„•) : re (n : K) = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : β„•) : im (n : K) = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_int_cast (n : β„€) : ((n : ℝ) : K) = n := of_real_hom.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : β„€) : re (n : K) = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : β„€) : im (n : K) = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_rat_cast (n : β„š) : ((n : ℝ) : K) = n := (@is_R_or_C.of_real_hom K _).map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : β„š) : re (q : K) = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : β„š) : im (q : K) = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ -- TODO: I think this can be instance, because it is a `Prop` /-- ℝ and β„‚ are both of characteristic zero. Note: This is not registered as an instance to avoid having multiple instances on ℝ and β„‚. -/ lemma char_zero_R_or_C : char_zero K := char_zero_of_inj_zero $ Ξ» n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : K) : ↑(re z) = (z + conj z) / 2 := begin haveI : char_zero K := char_zero_R_or_C, rw [add_conj, mul_div_cancel_left ((re z):K) two_ne_zero'], end /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs local notation `absK` := @abs K _ @[simp, norm_cast] lemma abs_of_real (r : ℝ) : absK r = abs' r := by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma norm_eq_abs (z : K) : βˆ₯zβˆ₯ = absK z := by simp [abs, norm_sq_eq_def'] lemma abs_of_nonneg {r : ℝ} (h : 0 ≀ r) : absK r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : β„•) : absK n = n := by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) } lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : absK 0 = 0 := by simp [abs] @[simp] lemma abs_one : absK 1 = 1 := by simp [abs] @[simp] lemma abs_two : absK 2 = 2 := calc absK 2 = absK (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : K) : 0 ≀ absK z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : K} : abs z β‰  0 ↔ z β‰  0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : K) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : K) : abs' (re z) ≀ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : K) : abs' (im z) ≀ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : K) : re z ≀ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : K) : im z ≀ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : K) : abs (z + w) ≀ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value absK := { abv_nonneg := abs_nonneg, abv_eq_zero := Ξ» _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z β‰  0 := abv_pos abs @[simp] lemma abs_neg : βˆ€ z : K, abs (-z) = abs z := abv_neg abs lemma abs_sub : βˆ€ z w : K, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : βˆ€ a b c : K, abs (a - c) ≀ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : βˆ€ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : βˆ€ z w : K, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : βˆ€ z w : K, abs' (abs z - abs w) ≀ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≀ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } end lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≀ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } end @[simp, norm_cast] lemma abs_cast_nat (n : β„•) : abs (n : K) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) := by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs] lemma abs_sqr_re_add_conj (x : K) : (abs (x + x†))^2 = (re (x + x†))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma abs_sqr_re_add_conj' (x : K) : (abs (x† + x))^2 = (re (x† + x))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma conj_mul_eq_norm_sq_left (x : K) : x† * x = ((norm_sq x) : K) := begin rw ext_iff, refine ⟨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_⟩, simp [of_real_im, mul_im, conj_im, conj_re, mul_comm], end /-- The real part in a `is_R_or_C` field, as a continuous linear map. -/ noncomputable def re_clm : K β†’L[ℝ] ℝ := re_lm.mk_continuous 1 $ by { simp only [norm_eq_abs, re_lm_coe, one_mul], exact abs_re_le_abs } @[simp] lemma norm_re_clm : βˆ₯(re_clm : K β†’L[ℝ] ℝ)βˆ₯ = 1 := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _), convert continuous_linear_map.ratio_le_op_norm _ (1 : K), simp, end @[simp, norm_cast] lemma re_clm_coe : ((re_clm : K β†’L[ℝ] ℝ) : K β†’β‚—[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply : ((re_clm : K β†’L[ℝ] ℝ) : K β†’ ℝ) = re := rfl /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, re (f n)) := Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, im (f n)) := Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : β„• β†’ K} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := Ξ» Ξ΅ Ξ΅0, let ⟨i, hi⟩ := hf Ξ΅ Ξ΅0 in ⟨i, Ξ» j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ @[simp, norm_cast, priority 900] lemma of_real_prod {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β†’ ℝ) : ((∏ i in s, f i : ℝ) : K) = ∏ i in s, (f i : K) := ring_hom.map_prod _ _ _ @[simp, norm_cast, priority 900] lemma of_real_sum {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β†’ ℝ) : ((βˆ‘ i in s, f i : ℝ) : K) = βˆ‘ i in s, (f i : K) := ring_hom.map_sum _ _ _ @[simp, norm_cast] lemma of_real_finsupp_sum {Ξ± M : Type*} [has_zero M] (f : Ξ± β†’β‚€ M) (g : Ξ± β†’ M β†’ ℝ) : ((f.sum (Ξ» a b, g a b) : ℝ) : K) = f.sum (Ξ» a b, ((g a b) : K)) := ring_hom.map_finsupp_sum _ f g @[simp, norm_cast] lemma of_real_finsupp_prod {Ξ± M : Type*} [has_zero M] (f : Ξ± β†’β‚€ M) (g : Ξ± β†’ M β†’ ℝ) : ((f.prod (Ξ» a b, g a b) : ℝ) : K) = f.prod (Ξ» a b, ((g a b) : K)) := ring_hom.map_finsupp_prod _ f g end is_R_or_C namespace finite_dimensional variables {K : Type*} [is_R_or_C K] open_locale classical open is_R_or_C /-- This instance generates a type-class problem with a metavariable `?m` that should satisfy `is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `β„‚`, this does not cause problems. -/ library_note "is_R_or_C instance" /-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/ @[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K := finite_dimensional.iff_fg.mpr ⟨{1, I}, begin rw eq_top_iff, intros a _, rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert], refine ⟨re a, (im a) β€’ I, _, _⟩, { rw submodule.mem_span_singleton, use im a }, simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real] end⟩ /-- Over an `is_R_or_C` field, we can register the properness of finite-dimensional normed spaces as an instance. -/ @[priority 900, nolint dangerous_instance] instance proper_is_R_or_C -- note [is_R_or_C instance] {E : Type*} [normed_group E] [normed_space K E] [finite_dimensional K E] : proper_space E := begin letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E, letI : is_scalar_tower ℝ K E := restrict_scalars.is_scalar_tower _ _ _, letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E, apply_instance end end finite_dimensional section instances noncomputable instance real.is_R_or_C : is_R_or_C ℝ := { re := add_monoid_hom.id ℝ, im := 0, conj := ring_hom.id ℝ, I := 0, I_re_ax := by simp only [add_monoid_hom.map_zero], I_mul_I_ax := or.intro_left _ rfl, re_add_im_ax := Ξ» z, by unfold_coes; simp [add_zero, id.def, mul_zero], of_real_re_ax := Ξ» r, by simp only [add_monoid_hom.id_apply, algebra.id.map_eq_self], of_real_im_ax := Ξ» r, by simp only [add_monoid_hom.zero_apply], mul_re_ax := Ξ» z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_ax := Ξ» z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply], conj_re_ax := Ξ» z, by simp only [ring_hom.id_apply], conj_im_ax := Ξ» z, by simp only [neg_zero, add_monoid_hom.zero_apply], conj_I_ax := by simp only [ring_hom.map_zero, neg_zero], norm_sq_eq_def_ax := Ξ» z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_I_ax := Ξ» z, by simp only [mul_zero, add_monoid_hom.zero_apply], inv_def_ax := begin intro z, unfold_coes, have H : z β‰  0 β†’ 1 / z = z / (z * z) := Ξ» h, calc 1 / z = 1 * (1 / z) : (one_mul (1 / z)).symm ... = (z / z) * (1 / z) : congr_arg (Ξ» x, x * (1 / z)) (div_self h).symm ... = z / (z * z) : by field_simp, rcases lt_trichotomy z 0 with hlt|heq|hgt, { field_simp [norm, abs, max_eq_right_of_lt (show z < -z, by linarith), pow_two, mul_inv', ←H (ne_of_lt hlt)] }, { simp [heq] }, { field_simp [norm, abs, max_eq_left_of_lt (show -z < z, by linarith), pow_two, mul_inv', ←H (ne_of_gt hgt)] }, end, div_I_ax := Ξ» z, by simp only [div_zero, mul_zero, neg_zero]} noncomputable instance complex.is_R_or_C : is_R_or_C β„‚ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, 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, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := Ξ» z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], 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 } end instances namespace is_R_or_C section cleanup_lemmas local notation `reR` := @is_R_or_C.re ℝ _ local notation `imR` := @is_R_or_C.im ℝ _ local notation `conjR` := @is_R_or_C.conj ℝ _ local notation `IR` := @is_R_or_C.I ℝ _ local notation `absR` := @is_R_or_C.abs ℝ _ local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _ local notation `reC` := @is_R_or_C.re β„‚ _ local notation `imC` := @is_R_or_C.im β„‚ _ local notation `conjC` := @is_R_or_C.conj β„‚ _ 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_real {x : ℝ} : reR x = x := rfl @[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl @[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl @[simp] lemma I_to_real : IR = 0 := rfl @[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq] @[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x := by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs] @[simp] lemma coe_real_eq_id : @coe ℝ ℝ _ = id := rfl @[simp] lemma re_to_complex {x : β„‚} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : β„‚} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : β„‚} : conjC x = x.conj := 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 cleanup_lemmas end is_R_or_C
4beae984afddae7e8fd49337339ec7b6920469d5
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Elab/PreDefinition/Structural.lean
d3876530c862e473104f6823f4b6ca98bd1b2ad4
[ "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
22,884
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.ForEachExpr import Lean.Meta.RecursorInfo import Lean.Meta.Match.Match import Lean.Elab.PreDefinition.Basic namespace Lean.Elab namespace Structural open Meta private def getFixedPrefix (declName : Name) (xs : Array Expr) (value : Expr) : MetaM Nat := do let numFixedRef ← IO.mkRef xs.size forEachExpr' value fun e => do if e.isAppOf declName then let args := e.getAppArgs numFixedRef.modify fun numFixed => if args.size < numFixed then args.size else numFixed for arg in args, x in xs do /- We should not use structural equality here. For example, given the definition ``` def V.map {Ξ± Ξ²} f x x_1 := @V.map.match_1.{1} Ξ± (fun x x_2 => V Ξ² x) x x_1 (fun x x_2 => @V.mk₁ Ξ² x (f Bool.true x_2)) (fun e => @V.mkβ‚‚ Ξ² (V.map (fun b => Ξ± b) (fun b => Ξ² b) f Bool.false e)) ``` The first three arguments at `V.map (fun b => Ξ± b) (fun b => Ξ² b) f Bool.false e` are "fixed" modulo definitional equality. -/ if !(← withReducible <| isDefEq arg x) then -- We continue searching if e's arguments are not a prefix of `xs` return true return false else return true numFixedRef.get structure RecArgInfo where /- `fixedParams ++ ys` are the arguments of the function we are trying to justify termination using structural recursion. -/ fixedParams : Array Expr ys : Array Expr -- recursion arguments pos : Nat -- position in `ys` of the argument we are recursing on indicesPos : Array Nat -- position in `ys` of the inductive datatype indices we are recursing on indName : Name -- inductive datatype name of the argument we are recursing on indLevels : List Level -- inductice datatype universe levels of the argument we are recursing on indParams : Array Expr -- inductive datatype parameters of the argument we are recursing on indIndices : Array Expr -- inductive datatype indices of the argument we are recursing on, it is equal to `indicesPos.map fun i => ys.get! i` reflexive : Bool -- true if we are recursing over a reflexive inductive datatype private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr Γ— Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr Γ— Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed {Ξ±} : MetaM Ξ± := throwError "structural recursion cannot be used" structure State where /- When compiling structural recursion we use the `brecOn` recursor automatically built by the `inductive` command. For an inductive datatype `C`, it has the form `C.brecOn As motive is c F` where `As` are the inductive datatype parameters, `is` are the inductive datatype indices, `c : C As is`, and `F : (js) β†’ (d : C As js) β†’ C.below d β†’ motive d` The `C.below d` is used to eliminate recursive applications. We refine its type when we process a nested dependent pattern matcher using `MatcherApp.addArg`. See `replaceRecApps` for additional details. We store the names of the matcher where we used `MatcherApp.addArg` at `matcherBelowDep`. We use this information to generate the auxiliary `_sunfold` definition needed by the smart unfolding technique used at WHNF. -/ matcherBelowDep : NameSet := {} abbrev M := StateRefT State MetaM instance {Ξ±} : Inhabited (M Ξ±) where default := throwError "failed" private def run {Ξ±} (x : M Ξ±) (s : State := {}) : MetaM (Ξ± Γ— State) := StateRefT'.run x s private def orelse' {Ξ±} (x y : M Ξ±) : M Ξ± := do let saveState ← get orelseMergeErrors x (do set saveState; y) private partial def findRecArg {Ξ±} (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo β†’ M Ξ±) : M Ξ± := let rec loop (i : Nat) : M Ξ± := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => loop (i+1)) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then loop (i+1) else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then loop (i+1) else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.numParams let indIndices := indArgs.extract indInfo.numParams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (loop (i+1)) else if !indIndices.allDiff then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (loop (i+1)) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match ← hasBadIndexDep? ys indIndices with | some (index, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (loop (i+1)) | none => match ← hasBadParamDep? ys indParams with | some (indParam, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (loop (i+1)) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (loop (i+1)) else throwStructuralFailed loop numFixed private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome private def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then Meta.forEachExpr e fun e => do if e.isAppOf recFnName then throwError "unexpected occurrence of recursive application{indentExpr e}" pure e else pure e private def throwToBelowFailed {Ξ±} : MetaM Ξ± := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr β†’ Expr β†’ Expr β†’ MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural] "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict {Ξ±} (below : Expr) (numIndParams : Nat) (k : Expr β†’ Expr β†’ MetaM Ξ±) : MetaM Ξ± := do let belowType ← inferType below trace[Elab.definition.structural] "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] let C ← mkFreshUserName `C withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat β†’ List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below /-- Return true iff `e` contains an application `recFnName .. t ..` where the term `t` is the argument we are trying to recurse on, and it contains loose bound variables. We use this test to decide whether we should process a matcher-application as a regular applicaton or not. That is, whether we should push the `below` argument should be affected by the matcher or not. If `e` does not contain an application of the form `recFnName .. t ..`, then we know the recursion doesn't depend on any pattern variable in this matcher. -/ private def recArgHasLooseBVarsAt (recFnName : Name) (recArgInfo : RecArgInfo) (e : Expr) : Bool := let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos let app? := e.find? fun e => e.isAppOf recFnName && e.getAppNumArgs > recArgPos && (e.getArg! recArgPos).hasLooseBVars app?.isSome private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr := let rec loop : Expr β†’ Expr β†’ M Expr | below, e@(Expr.lam n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | below, e@(Expr.forallE n d b c) => do withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | below, Expr.letE n type val body _ => do withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) | below, Expr.mdata d e _ => do pure $ mkMData d (← loop below e) | below, Expr.proj n i e _ => do pure $ mkProj n i (← loop below e) | below, e@(Expr.app _ _ _) => do let processApp (e : Expr) : M Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] -- For reflexive type, we may have nested recursive applications in recArg let recArg ← loop below recArg let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg pure $ mkAppN f fArgs else pure $ mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ trace[Elab.definition.structural] "below before matcherApp.addArg: {below} : {← inferType below}" let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) modify fun s => { s with matcherBelowDep := s.matcherBelowDep.insert matcherApp.matcherName } let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural] "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | _, e => ensureNoRecFn recFnName e loop below e private def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y trace[Elab.definition.structural] "fixedParams: {recArgInfo.fixedParams}, otherArgs: {otherArgs}" let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural] "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural] "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural] "brecOn {brecOn}" trace[Elab.definition.structural] "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F trace[Elab.definition.structural] "FType: {FType}" let FType ← instantiateForall FType recArgInfo.indIndices let FType ← instantiateForall FType #[major] forallBoundedTelescope FType (some 1) fun below _ => do let below := below[0] let valueNew ← replaceRecApps recFnName recArgInfo below value let Farg ← mkLambdaFVars (recArgInfo.indIndices ++ #[major, below] ++ otherArgs) valueNew let brecOn := mkApp brecOn Farg pure $ mkAppN brecOn otherArgs private def elimRecursion (preDef : PreDefinition) : M PreDefinition := withoutModifyingEnv do lambdaTelescope preDef.value fun xs value => do addAsAxiom preDef trace[Elab.definition.structural] "{preDef.declName} {xs} :=\n{value}" let numFixed ← getFixedPrefix preDef.declName xs value trace[Elab.definition.structural] "numFixed: {numFixed}" findRecArg numFixed xs fun recArgInfo => do -- when (recArgInfo.indName == `Nat) throwStructuralFailed -- HACK to skip Nat argument let valueNew ← mkBRecOn preDef.declName recArgInfo value let valueNew ← mkLambdaFVars xs valueNew trace[Elab.definition.structural] "result: {valueNew}" -- Recursive applications may still occur in expressions that were not visited by replaceRecApps (e.g., in types) let valueNew ← ensureNoRecFn preDef.declName valueNew pure { preDef with value := valueNew } partial def addSmartUnfoldingDefAux (preDef : PreDefinition) (matcherBelowDep : NameSet) : MetaM PreDefinition := do let recFnName := preDef.declName let isMarkedMatcherName (n : Name) : Bool := matcherBelowDep.contains n let isMarkedMatcherConst (e : Expr) : Bool := e.isConst && isMarkedMatcherName e.constName! let isMarkedMatcherApp (e : Expr) : Bool := isMarkedMatcherConst e.getAppFn let containsMarkedMatcher (e : Expr) : Bool := e.find? isMarkedMatcherConst |>.isSome let rec visit (e : Expr) : MetaM Expr := do match e with | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b) | Expr.letE n type val body _ => withLetDecl n type (← visit val) fun x => do mkLetFVars #[x] (← visit (body.instantiate1 x)) | Expr.mdata d b _ => return mkMData d (← visit b) | Expr.proj n i s _ => return mkProj n i (← visit s) | Expr.app .. => let processApp (e : Expr) : MetaM Expr := e.withApp fun f args => do return mkAppN (← visit f) (← args.mapM visit) match isMarkedMatcherApp e, (← matchMatcherApp? e) with | true, some matcherApp => let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" if containsMarkedMatcher altBody then -- continue mkLambdaFVars xs (← visit altBody) else -- add idRhs marker let altBody ← mkLambdaFVars xs[numParams:xs.size] altBody let altBody ← mkIdRhs altBody mkLambdaFVars xs[0:numParams] altBody pure { matcherApp with alts := altsNew }.toExpr | _, _ => processApp e | _ => pure e return { preDef with declName := mkSmartUnfoldingNameFor preDef.declName, value := (← visit preDef.value), modifiers := {} } partial def addSmartUnfoldingDef (preDef : PreDefinition) (state : State) : TermElabM Unit := do if (← isProp preDef.type) then return () else let preDefSUnfold ← addSmartUnfoldingDefAux preDef state.matcherBelowDep addNonRec preDefSUnfold def structuralRecursion (preDefs : Array PreDefinition) : TermElabM Unit := if preDefs.size != 1 then throwError "structural recursion does not handle mutually recursive functions" else do let (preDefNonRec, state) ← run $ elimRecursion preDefs[0] mapError (addNonRec preDefNonRec) (fun msg => m!"structural recursion failed, produced type incorrect term{indentD msg}") addAndCompilePartialRec preDefs addSmartUnfoldingDef preDefs[0] state builtin_initialize registerTraceClass `Elab.definition.structural end Structural export Structural (structuralRecursion) end Lean.Elab
8176cb4c01bf97b41d29356c6c3531b95f29307c
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/data/nat/basic.lean
6bccb466cb877f1a0027d7eb8fcdf04dc86b2c4e
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,626
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.order data.option universe u namespace nat variables {m n k : β„•} theorem pred_sub (n m : β„•) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl theorem pos_iff_ne_zero : n > 0 ↔ n β‰  0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n β‰  0 := pos_iff_ne_zero protected theorem le_sub_add (n m : β„•) : n ≀ n - m + m := or.elim (le_total n m) (assume : n ≀ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≀ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : β„•) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ Ξ» k h₁ hβ‚‚, by rw ← nat.sub_add_cancel hβ‚‚; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : β„•) : n - m + min n m = n := (le_total n m).elim (Ξ» h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (Ξ» h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : β„•} (h : n β‰₯ m) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_min (n m : β„•) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] protected theorem lt_of_sub_pos (h : n - m > 0) : m < n := lt_of_not_ge (assume : m β‰₯ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k β†’ m < n := le_imp_le_iff_lt_imp_lt.1 (Ξ» h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k β†’ k < n := le_imp_le_iff_lt_imp_lt.1 (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : m > 0) (hβ‚‚ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos hβ‚‚] ... = pred m - pred n : by rw succ_sub_succ ... ≀ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≀ n) : m ≀ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≀ n) : m ≀ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≀ m β†’ n ≀ m + k := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≀ m β†’ n ≀ k + m := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m β†’ n < m + k := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m β†’ n < k + m := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≀ k + m β†’ n - k ≀ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≀ m + k β†’ n - k ≀ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≀ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, Ξ» h₁, have succ k ≀ n + m, from succ_le_of_lt h₁, have succ (k - n) ≀ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≀ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≀ k) : n ≀ k - m ↔ m + n ≀ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≀ k) : m ≀ k - n ↔ m + n ≀ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt (H : m ≀ k) : n < k - m ↔ m + n < k := ⟨λ h, by have := nat.add_le_add_left h m; rwa [nat.add_sub_cancel' H] at this, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt (H : n ≀ k) : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt H, add_comm] theorem sub_le_left_iff_le_add (H : n ≀ m) : m - n ≀ k ↔ m ≀ n + k := le_iff_le_iff_lt_iff_lt.2 (nat.lt_sub_left_iff_add_lt H) theorem sub_le_right_iff_le_add (H : k ≀ m) : m - k ≀ n ↔ m ≀ n + k := by rw [nat.sub_le_left_iff_le_add H, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≀ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≀ m) : m - n ≀ m - k ↔ k ≀ n := ⟨λ h, have k + (m - k) - n ≀ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≀ m) : m - k < n - k ↔ m < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≀ m) : m - n < m - k ↔ k < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff (h₁ : n ≀ m) (hβ‚‚ : k ≀ m) : m - n ≀ k ↔ m - k ≀ n := (nat.sub_le_left_iff_le_add h₁).trans (nat.sub_le_right_iff_le_add hβ‚‚).symm protected theorem sub_lt_iff (h₁ : n ≀ m) (hβ‚‚ : k ≀ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add hβ‚‚).symm lemma lt_pred_of_succ_lt {n m : β„•} : succ n < m β†’ n < pred m := @nat.lt_sub_right_of_add_lt n m 1 protected theorem mul_ne_zero {n m : β„•} (n0 : n β‰  0) (m0 : m β‰  0) : n * m β‰  0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : β„•} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : β„•} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] attribute [simp] nat.div_self protected theorem div_le_div_right {n m : β„•} (h : n ≀ m) {k : β„•} : n / k ≀ m / k := (nat.eq_zero_or_pos k).elim (Ξ» k0, by simp [k0]) $ Ξ» hk, (nat.le_div_iff_mul_le _ _ hk).2 $ le_trans (nat.div_mul_le_self _ _) h protected theorem eq_mul_of_div_eq_right {a b c : β„•} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : β„•} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : β„•} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : β„•} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : β„•} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : β„•} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, eβ‚‚βŸ©, e₁ β–Έ eβ‚‚ β–Έ ⟨mod_add_div _ _, mod_lt _ h⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, h₁ β–Έ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, hβ‚‚]⟩ protected theorem mul_right_inj {a b c : β„•} (ha : a > 0) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, Ξ» e, e β–Έ rfl⟩ protected theorem mul_left_inj {a b c : β„•} (ha : a > 0) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, Ξ» e, e β–Έ rfl⟩ @[simp] protected theorem dvd_one {n : β„•} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, Ξ» e, e.symm β–Έ dvd_refl _⟩ protected theorem mul_dvd_mul_iff_left {a b c : β„•} (ha : a > 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ Ξ» d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : β„•} (hc : c > 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ Ξ» d, by rw [mul_right_comm, nat.mul_right_inj hc] @[simp] theorem mod_mod (a n : β„•) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (Ξ» n0, by simp [n0]) (Ξ» npos, mod_eq_of_lt (mod_lt _ npos)) theorem add_pos_left {m : β„•} (h : m > 0) (n : β„•) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... β‰₯ 0 : zero_le n theorem add_pos_right (m : β„•) {n : β„•} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : β„•) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end theorem succ_le_succ_iff {m n : β„•} : succ m ≀ succ n ↔ m ≀ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem lt_succ_iff {m n : β„•} : m < succ n ↔ m ≀ n := succ_le_succ_iff lemma lt_succ_iff_lt_or_eq {n i : β„•} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : β„•} : i ≀ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h β–Έ le_refl i⟩ theorem le_add_one_iff {i j : β„•} : i ≀ j + 1 ↔ (i ≀ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : β„•} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Ξ  k < n, Prop) : βˆ€ [H : βˆ€ n h, decidable (P n h)], decidable (βˆ€ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (Ξ» n, dec_trivial) }, cases IH (Ξ» k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (Ξ» k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (Ξ» e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (Ξ» hn, hn _ _) p) } end instance decidable_forall_fin {n : β„•} (P : fin n β†’ Prop) [H : decidable_pred P] : decidable (βˆ€ i, P i) := decidable_of_iff (βˆ€ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, Ξ» a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : β„•) (P : Ξ  k ≀ n, Prop) [H : βˆ€ n h, decidable (P n h)] : decidable (βˆ€ n h, P n h) := decidable_of_iff (βˆ€ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), Ξ» a k h, a k _⟩ instance decidable_lo_hi (lo hi : β„•) (P : β„• β†’ Prop) [H : decidable_pred P] : decidable (βˆ€x, lo ≀ x β†’ x < hi β†’ P x) := decidable_of_iff (βˆ€ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, Ξ»al x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : β„•) (P : β„• β†’ Prop) [H : decidable_pred P] : decidable (βˆ€x, lo ≀ x β†’ x ≀ hi β†’ P x) := decidable_of_iff (βˆ€x, lo ≀ x β†’ x < hi + 1 β†’ P x) $ ball_congr $ Ξ» x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : β„•} (h : n ≀ m) : bit0 n ≀ bit0 m := add_le_add h h protected theorem bit1_le {n m : β„•} (h : n ≀ m) : bit1 n ≀ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : βˆ€ (b : bool) {n m : β„•}, n ≀ m β†’ bit b n ≀ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n β‰  0) : bit b n β‰  0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : βˆ€ (b) {m n : β„•}, m ≀ n β†’ bit0 m ≀ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : βˆ€ (b) {m n : β„•}, m ≀ n β†’ bit b m ≀ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : βˆ€ (b) {n m : β„•}, n < m β†’ bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : β„•} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : β„• β†’ option β„• | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : β„•) : β„• β†’ option β„• | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : β„•) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : β„•) : βˆ€ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : β„•} : βˆ€ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : βˆ€ {n : β„•}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : β„•} : βˆ€ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some] theorem psub_eq_none (m n : β„•) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (Ξ» h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≀ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≀ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ @[simp] lemma one_pow : βˆ€ n : β„•, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : β„•) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_two (a : β„•) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : β„•) {m n : β„•} (h : m ≀ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : β„•} (h : a ∣ b) : βˆ€ n:β„•, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : β„•) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : β„•) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : β„•} (hp : p > 0) : βˆ€ n : β„•, p ^ n > 0 | 0 := by simpa using zero_lt_one | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : β„•) {m n : β„•} (h : m ≀ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : β„•} (h : p > 1) (n : β„•) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : β„•} (h : p > 1) : βˆ€ n : β„•, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≀ p ^ (n+1) : pow_lt_pow_succ h _ lemma not_pos_pow_dvd : βˆ€ {p k : β„•} (hp : p > 1) (hk : k > 1), Β¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 > 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : β„•) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- iterate -/ section variables {Ξ± : Sort*} (op : Ξ± β†’ Ξ±) @[simp] theorem iterate_zero (a : Ξ±) : op^[0] a = a := rfl @[simp] theorem iterate_succ (n : β„•) (a : Ξ±) : op^[succ n] a = (op^[n]) (op a) := rfl theorem iterate_add : βˆ€ (m n : β„•) (a : Ξ±), op^[m + n] a = (op^[m]) (op^[n] a) | m 0 a := rfl | m (succ n) a := iterate_add m n _ theorem iterate_succ' (n : β„•) (a : Ξ±) : op^[succ n] a = op (op^[n] a) := by rw [← one_add, iterate_add]; refl end /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m β‰  0) (n) : shiftl' b m n β‰  0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : βˆ€ {n} (h : n β‰  0), shiftl' tt m n β‰  0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n β‰  0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n β‰  0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n β‰  0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊒, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊒, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ Ξ» hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m β‰  0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : β„•) : n < 2^size n := begin rw [← one_shiftl], have : βˆ€ {n}, n = 0 β†’ n < shiftl 1 (size n) := Ξ» n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : β„•} : size m ≀ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply le_imp_le_iff_lt_imp_lt.1 (Ξ» h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : β„•} : m < size n ↔ 2^m ≀ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : β„•} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : β„•} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : β„•} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : β„•} (h : m ≀ n) : size m ≀ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat β†’ nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : βˆ€ n, fact n > 0 | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : β„•) : fact n β‰  0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≀ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : βˆ€ {m n}, m > 0 β†’ m ≀ n β†’ m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≀ n) : fact m ≀ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) section find_greatest /-- `find_greatest P b` is the largest `i ≀ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : β„• β†’ Prop) [decidable_pred P] : β„• β†’ β„• | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : β„• β†’ Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : βˆ€{b}, P b β†’ nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : Β¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : βˆ€{b m}, m ≀ b β†’ P m β†’ P (nat.find_greatest P b) ∧ m ≀ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≀ 0, from this β–Έ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m β‰  b + 1 := assume this, h $ this β–Έ hP, have : m ≀ b := (le_of_not_gt $ assume h : b + 1 ≀ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≀ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (βˆƒm, m ≀ b ∧ P m) β†’ P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : βˆ€ {b}, nat.find_greatest P b ≀ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≀ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≀ b) (hm : P m) : m ≀ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : β„• β†’ Prop} [decidable_pred P] {b} : (βˆƒ m, m ≀ b ∧ P m) β†’ βˆ€ k, nat.find_greatest P b < k ∧ k ≀ b β†’ Β¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : β„•} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : a > 0, from nat.pos_of_ne_zero ha, have h1 : βˆƒ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show βˆƒ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : β„•} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : βˆƒ d, b / c = a * d, from h, have h2 : βˆƒ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show βˆƒ d, b = c * a * d, from ⟨d, by cc⟩ lemma nat.div_mul_div {a b c d : β„•} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : βˆƒ x, a = b * x, from hab, have exi2 : βˆƒ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have b > 0, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have d > 0, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_div_of_le_of_pow_div {p m n k : β„•} (hmn : m ≀ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv end div end nat
c0440c6057baa2b47579825ad98512918cfff61a
4fa161becb8ce7378a709f5992a594764699e268
/src/category_theory/monoidal/of_has_finite_products.lean
0b452942e816bc5b345b3351aa2de20c39000177
[ "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
4,834
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.category import category_theory.limits.shapes.binary_products import category_theory.limits.types /-! # The natural monoidal structure on any category with finite (co)products. A category with a monoidal structure provided in this way is sometimes called a (co)cartesian category, although this is also sometimes used to mean a finitely complete category. (See <https://ncatlab.org/nlab/show/cartesian+category>.) As this works with either products or coproducts, and sometimes we want to think of a different monoidal structure entirely, we don't set up either construct as an instance. ## Implementation For the sake of nicer definitional properties, we rely on `has_terminal` and `has_binary_products` instead of `has_finite_products`, so that if a particular category provides customised instances of these we pick those up instead. -/ universes v u namespace category_theory open category_theory.limits variables (C : Type u) [category.{v} C] section local attribute [tidy] tactic.case_bash /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_has_finite_products [has_terminal.{v} C] [has_binary_products.{v} C] : monoidal_category C := { tensor_unit := ⊀_ C, tensor_obj := Ξ» X Y, X β¨― Y, tensor_hom := Ξ» _ _ _ _ f g, limits.prod.map f g, associator := prod.associator, left_unitor := prod.left_unitor, right_unitor := prod.right_unitor, pentagon' := prod.pentagon, triangle' := prod.triangle, associator_naturality' := @prod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_products variables [has_terminal.{v} C] [has_binary_products.{v} C] local attribute [instance] monoidal_of_has_finite_products @[simp] lemma tensor_obj (X Y : C) : X βŠ— Y = (X β¨― Y) := rfl @[simp] lemma tensor_hom {W X Y Z : C} (f : W ⟢ X) (g : Y ⟢ Z) : f βŠ— g = limits.prod.map f g := rfl @[simp] lemma left_unitor_hom (X : C) : (Ξ»_ X).hom = limits.prod.snd := rfl @[simp] lemma left_unitor_inv (X : C) : (Ξ»_ X).inv = prod.lift (terminal.from X) (πŸ™ _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = limits.prod.fst := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = prod.lift (πŸ™ _) (terminal.from X) := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (Ξ±_ X Y Z).hom = prod.lift (limits.prod.fst ≫ limits.prod.fst) (prod.lift (limits.prod.fst ≫ limits.prod.snd) limits.prod.snd) := rfl end monoidal_of_has_finite_products section local attribute [tidy] tactic.case_bash /-- A category with an initial object and binary coproducts has a natural monoidal structure. -/ def monoidal_of_has_finite_coproducts [has_initial.{v} C] [has_binary_coproducts.{v} C] : monoidal_category C := { tensor_unit := βŠ₯_ C, tensor_obj := Ξ» X Y, X β¨Ώ Y, tensor_hom := Ξ» _ _ _ _ f g, limits.coprod.map f g, associator := coprod.associator, left_unitor := coprod.left_unitor, right_unitor := coprod.right_unitor, pentagon' := coprod.pentagon, triangle' := coprod.triangle, associator_naturality' := @coprod.associator_naturality _ _ _, } end namespace monoidal_of_has_finite_coproducts variables [has_initial.{v} C] [has_binary_coproducts.{v} C] local attribute [instance] monoidal_of_has_finite_coproducts @[simp] lemma tensor_obj (X Y : C) : X βŠ— Y = (X β¨Ώ Y) := rfl @[simp] lemma tensor_hom {W X Y Z : C} (f : W ⟢ X) (g : Y ⟢ Z) : f βŠ— g = limits.coprod.map f g := rfl @[simp] lemma left_unitor_hom (X : C) : (Ξ»_ X).hom = coprod.desc (initial.to X) (πŸ™ _) := rfl @[simp] lemma right_unitor_hom (X : C) : (ρ_ X).hom = coprod.desc (πŸ™ _) (initial.to X) := rfl @[simp] lemma left_unitor_inv (X : C) : (Ξ»_ X).inv = limits.coprod.inr := rfl @[simp] lemma right_unitor_inv (X : C) : (ρ_ X).inv = limits.coprod.inl := rfl -- We don't mark this as a simp lemma, even though in many particular -- categories the right hand side will simplify significantly further. -- For now, we'll plan to create specialised simp lemmas in each particular category. lemma associator_hom (X Y Z : C) : (Ξ±_ X Y Z).hom = coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr) := rfl end monoidal_of_has_finite_coproducts end category_theory -- TODO in fact, a category with finite products is braided, and symmetric, -- and we should say that here, once braided categories arrive in mathlib.
7c95c272f846690afe04b8c2aae00c1fa47e794c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/binomial.lean
8622c5122e3ba58b6ea05387c5c0f3c199a35253
[ "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
676
lean
import Init.Data.BinomialHeap abbrev Heap := BinomialHeap Nat (fun a b => a < b) def mkHeap (n m : Nat) : Heap := let hs : List Heap := n.fold (fun i hs => let h : Heap := BinomialHeap.empty; let h : Heap := m.fold (fun j h => let v := n*m - j*n - i; h.insert v) h; h :: hs) []; hs.foldl (fun h₁ hβ‚‚ => h₁.merge hβ‚‚) BinomialHeap.empty partial def display : Nat β†’ Heap β†’ IO Unit | prev, h => if h.isEmpty then pure () else do let m := h.head; unless (prev < m) (IO.println ("failed " ++ toString prev ++ " " ++ toString m)); display m h.tail def main : IO Unit := do let h := mkHeap 20 20; display 0 h; IO.println h.toList.length
6e273f292ad8576d9bf68cd45bdc851b8e561c32
6b7c9c6393bac7cb1c64582a1c62597e24f5bb80
/src/tactic/gptf/basic.lean
251c26c833f050af5981f4a3654af14aabd97d54
[ "Apache-2.0" ]
permissive
alreadydone/lean-gptf
56a7d9cbd9400af72fb143d60c8774b8cfbc09cb
b4ab1eb2da0178f3dcdc49771d9fed6b50e35d98
refs/heads/master
1,679,371,993,063
1,614,479,778,000
1,614,479,778,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,486
lean
/- Copyright (c) 2021 Jesse Michael Han. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Jesse Michael Han, Ed Ayers Core logic of the `gptf` tactic -/ import system.io import tactic import tactic.gptf.utils.util import basic.control meta structure ModelAPI (input_format : Type := json) : Type := (query : input_format β†’ io json) /- for testing -/ meta def dummy_api {Ξ±} : ModelAPI Ξ± := ⟨λ _, pure $ json.of_string "[DummyAPI] FAILURE"⟩ meta structure BFSNode : Type := (state : tactic_state) (score : β„€ := 0) (tactics : list string := []) (depth : β„• := 0) meta def BFSNode.to_json : BFSNode β†’ json | ⟨state, score, tacs, depth⟩ := json.object $ [ ("state", json.of_string $ (format.to_string ∘ has_to_format.to_format) state) , ("score", json.of_int score) , ("tactics", json.array $ json.of_string <$> tacs) , ("depth", json.of_int depth) ] meta instance : has_to_tactic_json BFSNode := ⟨pure ∘ BFSNode.to_json⟩ meta instance : has_to_format BFSNode := ⟨has_to_format.to_format ∘ BFSNode.to_json⟩ namespace BFSNode meta def of_current_state (score : β„€ := 0) (tacs : list string := []) : tactic BFSNode := do { ts ← tactic.read, pure $ ⟨ts, score, tacs, 0⟩ } end BFSNode section run_all_beam_candidates meta def get_tac_and_capture_result (next_candidate : string) (timeout : β„• := 5000) : tactic (tactic_result _) := do { tac ← do { env ← tactic.get_env, eval_trace format!"[get_tac_and_capture_result] PARSING TACTIC: {next_candidate}", tac ← parse_itactic next_candidate, eval_trace format!"[get_tac_and_capture_result] PARSE SUCCESSFUL", tactic.set_env env, pure tac }, eval_trace format!"[get_tac_and_capture_result] TRYING TACTIC: {next_candidate}", result ← tactic.capture' (tactic.try_for_time timeout $ tactic.try_for 200000 tac), -- if `tac` fails, exception is captured here eval_trace format!"[get_tac_and_capture_result] RESULT: {result}", pure result } /-- This takes a 'next_candidate' object and then if the tactic result is a success then it will update the candidate name to reflect the result it returned. -/ -- private meta def candidate_modify : (string) β†’ tactic_result string β†’ (tactic_result unit) Γ— (string) := -- Ξ» s r, ⟨r.map (Ξ» _, ()), s <| r.get⟩ meta def try_get_tac_and_capture_result (tac_string : string) (timeout : β„• := 5000) : tactic ((tactic_result unit) Γ— string) := do { result_with_string ← get_tac_and_capture_result tac_string timeout <|> do { let msg : format := format!"[try_get_tac_and_capture_result] parse_itactic failed on {tac_string}", eval_trace msg, interaction_monad.mk_exception msg none <$> tactic.read }, let candidate_modify : string β†’ tactic_result string β†’ ((tactic_result unit) Γ— string) := Ξ» s r, ⟨r.map $ (Ξ» _, ()), s <| r.get⟩, pure $ candidate_modify tac_string result_with_string } /- TODO(jesse): since this is now used only for the interactive frontend, replace the inner loop with a `run_async <$> ...` -/ meta def run_all_beam_candidates (get_candidates : json β†’ tactic (list (string Γ— native.float))) (msg : json) : tactic (list (tactic_result unit Γ— string Γ— native.float) Γ— list string) := do { -- let try_candidate_state := (list (string Γ— native.float) Γ— (list $ option $ tactic_result unit Γ— string Γ— native.float)), -- let stop : option (tactic_result unit Γ— string Γ— native.float) β†’ state_t try_candidate_state tactic bool := -- Ξ» arg, match arg with -- | some ⟨result, candidate⟩ := do { -- state_t.lift result.is_done -- } -- | none := pure ff -- end, -- let try_candidate : state_t try_candidate_state tactic (option $ tactic_result unit Γ— string Γ— native.float) := do { -- state_t.lift $ eval_trace format!"[try_candidate] ENTERING", -- ts ← state_t.lift tactic.read, -- state_t.lift $ eval_trace format!"[try_candidate] READ TACTIC STATE", -- ⟨rest, _⟩ ← state_t.get, -- match rest with -- | [] := do { -- state_t.lift $ eval_trace format!"[try_candidate] END OF LOOP", -- pure $ some ⟨interaction_monad.fail "all candidates failed" ts, "FAILURE", 0.0⟩ -- } -- | (next_candidate::candidates) := do { -- state_t.modify (Ξ» ⟨_, rs⟩, ⟨candidates, rs⟩), -- result ← monad_lift $ try_get_tac_and_capture_result next_candidate.fst, -- when (interaction_monad.result.is_success $ result) $ -- state_t.modify $ Ξ» ⟨candidates, rs⟩, ⟨candidates, rs ++ [some $ ⟨result, next_candidate⟩]⟩, -- state_t.lift $ eval_trace format!"[try_candidate] CAPTURED RESULT: {result}", -- pure $ some ⟨result, next_candidate⟩ -- } -- end -- }, let find_successful_candidates (candidates : list (string Γ— native.float)) : tactic (list (tactic_result unit Γ— string Γ— native.float)) := do { tasks ← candidates.mmap (Ξ» arg, flip prod.mk arg <$> tactic.run_async (try_get_tac_and_capture_result arg.fst : tactic $ tactic_result unit Γ— string)), tactic.using_new_ref ff $ Ξ» flag, do tasks.iterM [] $ Ξ» acc ⟨task, tac_string, score⟩, do { mcond (tactic.read_ref flag) (pure acc) $ do { let ⟨result, new_tac_string⟩ := task.get, if (interaction_monad.result.is_success result) then do { whenM (result.is_done) $ tactic.write_ref flag tt, pure $ acc ++ [⟨result, new_tac_string, score⟩] } else do { pure acc } } } }, -- this is responsible for gracefully handling "error" JSON messages and should return an empty list of candidates candidates ← list.filter (Ξ» x, not $ "tidy".is_prefix_of $ prod.fst x) <$> (get_candidates msg >>= list.dedup'), eval_trace format!"[run_all_beam_candidates] CANDIDATES: {candidates}", -- successful_candidates ← (prod.snd <$> prod.snd <$> state_t.run (iterate_until try_candidate stop candidates.length $ pure none) ⟨candidates, []⟩), successful_candidates ← (list.map pure) <$> (get_candidates msg >>= list.dedup' >>= find_successful_candidates), eval_trace format!"[run_all_beam_candidates] EXITING TRY_CANDIDATE LOOP", eval_trace format!"[run_all_beam_candidates] SUCCESSFUL CANDIDATES: {successful_candidates}", pure ⟨successful_candidates.filter_map id, prod.fst <$> candidates⟩ } end run_all_beam_candidates
d110cae3f784ad174adff163d012a76a8e28e385
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/empty_thm.lean
1af981a5c6b347f2abbfbb4520346607b76fc1cc
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
158
lean
import logic open tactic definition simple := apply _root_.trivial tactic_hint simple theorem foo : true theorem foo2 (a : Prop) : a : theorem foo3 : true
bb0761e116da7fc9aad365470b8deadf2df3c694
c777c32c8e484e195053731103c5e52af26a25d1
/archive/imo/imo2019_q2.lean
ca6781c82a7e5623454f3ad6269793edd35e63f8
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
26,501
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.angle.sphere import geometry.euclidean.sphere.second_inter /-! # IMO 2019 Q2 In triangle `ABC`, point `A₁` lies on side `BC` and point `B₁` lies on side `AC`. Let `P` and `Q` be points on segments `AA₁` and `BB₁`, respectively, such that `PQ` is parallel to `AB`. Let `P₁` be a point on line `PB₁`, such that `B₁` lies strictly between `P` and `P₁`, and `∠PP₁C = ∠BAC`. Similarly, let `Q₁` be a point on line `QA₁`, such that `A₁` lies strictly between `Q` and `Q₁`, and `∠CQ₁Q = ∠CBA`. Prove that points `P`, `Q`, `P₁`, and `Q₁` are concyclic. We follow Solution 1 from the [official solutions](https://www.imo2019.uk/wp-content/uploads/2018/07/solutions-r856.pdf). Letting the rays `AA₁` and `BB₁` intersect the circumcircle of `ABC` at `Aβ‚‚` and `Bβ‚‚` respectively, we show with an angle chase that `P`, `Q`, `Aβ‚‚`, `Bβ‚‚` are concyclic and let `Ο‰` be the circle through those points. We then show that `C`, `Q₁`, `Aβ‚‚`, `A₁` are concyclic, and then that `Q₁` lies on `Ο‰`, and similarly that `P₁` lies on `Ο‰`, so the required four points are concyclic. Note that most of the formal proof is actually proving nondegeneracy conditions needed for that angle chase / concyclicity argument, where an informal solution doesn't discuss those conditions at all. Also note that (as described in `geometry.euclidean.angle.oriented.basic`) the oriented angles used are modulo `2 * Ο€`, so parts of the angle chase that are only valid for angles modulo `Ο€` (as used in the informal solution) are represented as equalities of twice angles, which we write as `(2 : β„€) β€’ ∑ _ _ _ = (2 : β„€) β€’ _ _ _`. -/ /-- We apply the following conventions for formalizing IMO geometry problems. A problem is assumed to take place in the plane unless that is clearly not intended, so it is not required to prove that the points are coplanar (whether or not that in fact follows from the other conditions). Angles in problem statements are taken to be unoriented. A reference to an angle `∠XYZ` is taken to imply that `X` and `Z` are not equal to `Y`, since choices of junk values play no role in informal mathematics, and those implications are included as hypotheses for the problem whether or not they follow from the other hypotheses. Similar, a reference to `XY` as a line is taken to imply that `X` does not equal `Y` and that is included as a hypothesis, and a reference to `XY` being parallel to something is considered a reference to it as a line. However, such an implicit hypothesis about two points being different is included only once for any given two points (even if it follows from more than one reference to a line or an angle), if `X β‰  Y` is included then `Y β‰  X` is not included separately, and such hypotheses are not included in the case where there is also a reference in the problem to a triangle including those two points, or to strict betweenness of three points including those two. If betweenness is stated, it is taken to be strict betweenness. However, segments and sides are taken to include their endpoints (unless this makes a problem false), although those degenerate cases might not necessarily have been considered when the problem was formulated and contestants might not have been expected to deal with them. A reference to a point being on a side or a segment is expressed directly with `wbtw` rather than more literally with `affine_segment`. -/ library_note "IMO geometry formalization conventions" noncomputable theory open affine affine.simplex euclidean_geometry finite_dimensional open_locale affine euclidean_geometry real local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ variables (V : Type*) (Pt : Type*) variables [normed_add_comm_group V] [inner_product_space ℝ V] [metric_space Pt] variables [normed_add_torsor V Pt] [hd2 : fact (finrank ℝ V = 2)] include hd2 /-- A configuration satisfying the conditions of the problem. We define this structure to avoid passing many hypotheses around as we build up information about the configuration; the final result for a statement of the problem not using this structure is then deduced from one in terms of this structure. -/ @[nolint has_nonempty_instance] structure imo2019q2_cfg := (A B C A₁ B₁ P Q P₁ Q₁ : Pt) (affine_independent_ABC : affine_independent ℝ ![A, B, C]) (wbtw_B_A₁_C : wbtw ℝ B A₁ C) (wbtw_A_B₁_C : wbtw ℝ A B₁ C) (wbtw_A_P_A₁ : wbtw ℝ A P A₁) (wbtw_B_Q_B₁ : wbtw ℝ B Q B₁) (PQ_parallel_AB : line[ℝ, P, Q] βˆ₯ line[ℝ, A, B]) -- A hypothesis implicit in the named line. (P_ne_Q : P β‰  Q) (sbtw_P_B₁_P₁ : sbtw ℝ P B₁ P₁) (angle_PP₁C_eq_angle_BAC : ∠ P P₁ C = ∠ B A C) -- A hypothesis implicit in the first named angle. (C_ne_P₁ : C β‰  P₁) (sbtw_Q_A₁_Q₁ : sbtw ℝ Q A₁ Q₁) (angle_CQ₁Q_eq_angle_CBA : ∠ C Q₁ Q = ∠ C B A) -- A hypothesis implicit in the first named angle. (C_ne_Q₁ : C β‰  Q₁) /-- A default choice of orientation, for lemmas that need to pick one. -/ def some_orientation : module.oriented ℝ V (fin 2) := ⟨basis.orientation (fin_basis_of_finrank_eq _ _ hd2.out)⟩ variables {V Pt} namespace imo2019q2_cfg variables (cfg : imo2019q2_cfg V Pt) /-- The configuration has symmetry, allowing results proved for one point to be applied for another (where the informal solution says "similarly"). -/ def symm : imo2019q2_cfg V Pt := { A := cfg.B, B := cfg.A, C := cfg.C, A₁ := cfg.B₁, B₁ := cfg.A₁, P := cfg.Q, Q := cfg.P, P₁ := cfg.Q₁, Q₁ := cfg.P₁, affine_independent_ABC := begin rw ←affine_independent_equiv (equiv.swap (0 : fin 3) 1), convert cfg.affine_independent_ABC using 1, ext x, fin_cases x; refl end, wbtw_B_A₁_C := cfg.wbtw_A_B₁_C, wbtw_A_B₁_C := cfg.wbtw_B_A₁_C, wbtw_A_P_A₁ := cfg.wbtw_B_Q_B₁, wbtw_B_Q_B₁ := cfg.wbtw_A_P_A₁, PQ_parallel_AB := set.pair_comm cfg.P cfg.Q β–Έ set.pair_comm cfg.A cfg.B β–Έ cfg.PQ_parallel_AB, P_ne_Q := cfg.P_ne_Q.symm, sbtw_P_B₁_P₁ := cfg.sbtw_Q_A₁_Q₁, angle_PP₁C_eq_angle_BAC := angle_comm cfg.C cfg.Q₁ cfg.Q β–Έ angle_comm cfg.C cfg.B cfg.A β–Έ cfg.angle_CQ₁Q_eq_angle_CBA, C_ne_P₁ := cfg.C_ne_Q₁, sbtw_Q_A₁_Q₁ := cfg.sbtw_P_B₁_P₁, angle_CQ₁Q_eq_angle_CBA := angle_comm cfg.P cfg.P₁ cfg.C β–Έ angle_comm cfg.B cfg.A cfg.C β–Έ cfg.angle_PP₁C_eq_angle_BAC, C_ne_Q₁ := cfg.C_ne_P₁ } /-! ### Configuration properties that are obvious from the diagram, and construction of the points `Aβ‚‚` and `Bβ‚‚` -/ lemma A_ne_B : cfg.A β‰  cfg.B := cfg.affine_independent_ABC.injective.ne (dec_trivial : (0 : fin 3) β‰  1) lemma A_ne_C : cfg.A β‰  cfg.C := cfg.affine_independent_ABC.injective.ne (dec_trivial : (0 : fin 3) β‰  2) lemma B_ne_C : cfg.B β‰  cfg.C := cfg.affine_independent_ABC.injective.ne (dec_trivial : (1 : fin 3) β‰  2) lemma not_collinear_ABC : Β¬collinear ℝ ({cfg.A, cfg.B, cfg.C} : set Pt) := affine_independent_iff_not_collinear_set.1 cfg.affine_independent_ABC /-- `ABC` as a `triangle`. -/ def triangle_ABC : triangle ℝ Pt := ⟨_, cfg.affine_independent_ABC⟩ lemma A_mem_circumsphere : cfg.A ∈ cfg.triangle_ABC.circumsphere := cfg.triangle_ABC.mem_circumsphere 0 lemma B_mem_circumsphere : cfg.B ∈ cfg.triangle_ABC.circumsphere := cfg.triangle_ABC.mem_circumsphere 1 lemma C_mem_circumsphere : cfg.C ∈ cfg.triangle_ABC.circumsphere := cfg.triangle_ABC.mem_circumsphere 2 lemma symm_triangle_ABC : cfg.symm.triangle_ABC = cfg.triangle_ABC.reindex (equiv.swap 0 1) := by { ext i, fin_cases i; refl } lemma symm_triangle_ABC_circumsphere : cfg.symm.triangle_ABC.circumsphere = cfg.triangle_ABC.circumsphere := by rw [symm_triangle_ABC, affine.simplex.circumsphere_reindex] /-- `Aβ‚‚` is the second point of intersection of the ray `AA₁` with the circumcircle of `ABC`. -/ def Aβ‚‚ : Pt := cfg.triangle_ABC.circumsphere.second_inter cfg.A (cfg.A₁ -α΅₯ cfg.A) /-- `Bβ‚‚` is the second point of intersection of the ray `BB₁` with the circumcircle of `ABC`. -/ def Bβ‚‚ : Pt := cfg.triangle_ABC.circumsphere.second_inter cfg.B (cfg.B₁ -α΅₯ cfg.B) lemma Aβ‚‚_mem_circumsphere : cfg.Aβ‚‚ ∈ cfg.triangle_ABC.circumsphere := (sphere.second_inter_mem _).2 cfg.A_mem_circumsphere lemma Bβ‚‚_mem_circumsphere : cfg.Bβ‚‚ ∈ cfg.triangle_ABC.circumsphere := (sphere.second_inter_mem _).2 cfg.B_mem_circumsphere lemma symm_Aβ‚‚ : cfg.symm.Aβ‚‚ = cfg.Bβ‚‚ := by { simp_rw [Aβ‚‚, Bβ‚‚, symm_triangle_ABC_circumsphere], refl } lemma QP_parallel_BA : line[ℝ, cfg.Q, cfg.P] βˆ₯ line[ℝ, cfg.B, cfg.A] := by { rw [set.pair_comm cfg.Q, set.pair_comm cfg.B], exact cfg.PQ_parallel_AB } lemma A_ne_A₁ : cfg.A β‰  cfg.A₁ := begin intro h, have h' := cfg.not_collinear_ABC, rw [h, set.insert_comm] at h', exact h' cfg.wbtw_B_A₁_C.collinear end lemma collinear_PAA₁Aβ‚‚ : collinear ℝ ({cfg.P, cfg.A, cfg.A₁, cfg.Aβ‚‚} : set Pt) := begin rw [Aβ‚‚, (cfg.triangle_ABC.circumsphere.second_inter_collinear cfg.A cfg.A₁).collinear_insert_iff_of_ne (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_insert _ _)) cfg.A_ne_A₁, set.insert_comm], exact cfg.wbtw_A_P_A₁.collinear end lemma A₁_ne_C : cfg.A₁ β‰  cfg.C := begin intro h, have hsbtw := cfg.sbtw_Q_A₁_Q₁, rw h at hsbtw, have ha := hsbtw.angle₂₃₁_eq_zero, rw [angle_CQ₁Q_eq_angle_CBA, angle_comm] at ha, exact (angle_ne_zero_of_not_collinear cfg.not_collinear_ABC) ha end lemma B₁_ne_C : cfg.B₁ β‰  cfg.C := cfg.symm.A₁_ne_C lemma Q_not_mem_CB : cfg.Q βˆ‰ line[ℝ, cfg.C, cfg.B] := begin intro hQ, have hQA₁ : line[ℝ, cfg.Q, cfg.A₁] ≀ line[ℝ, cfg.C, cfg.B] := affine_span_pair_le_of_mem_of_mem hQ cfg.wbtw_B_A₁_C.symm.mem_affine_span, have hQ₁ : cfg.Q₁ ∈ line[ℝ, cfg.C, cfg.B], { rw affine_subspace.le_def' at hQA₁, exact hQA₁ _ cfg.sbtw_Q_A₁_Q₁.right_mem_affine_span }, have hc : collinear ℝ ({cfg.C, cfg.Q₁, cfg.Q} : set Pt), { have hc' : collinear ℝ ({cfg.B, cfg.C, cfg.Q₁, cfg.Q} : set Pt), { rw [set.insert_comm cfg.B, set.insert_comm cfg.B, set.pair_comm, set.insert_comm cfg.C, set.insert_comm cfg.C], exact collinear_insert_insert_of_mem_affine_span_pair hQ₁ hQ }, exact hc'.subset (set.subset_insert _ _) }, rw [collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi, cfg.angle_CQ₁Q_eq_angle_CBA, or_iff_right cfg.C_ne_Q₁, or_iff_right cfg.sbtw_Q_A₁_Q₁.left_ne_right, angle_comm] at hc, exact cfg.not_collinear_ABC (hc.elim collinear_of_angle_eq_zero collinear_of_angle_eq_pi) end lemma Q_ne_B : cfg.Q β‰  cfg.B := begin intro h, have h' := cfg.Q_not_mem_CB, rw h at h', exact h' (right_mem_affine_span_pair _ _ _) end lemma s_opp_side_CB_Q_Q₁ : line[ℝ, cfg.C, cfg.B].s_opp_side cfg.Q cfg.Q₁ := cfg.sbtw_Q_A₁_Q₁.s_opp_side_of_not_mem_of_mem cfg.Q_not_mem_CB cfg.wbtw_B_A₁_C.symm.mem_affine_span /-! ### Relate the orientations of different angles in the configuration -/ section oriented variables [module.oriented ℝ V (fin 2)] lemma oangle_CQ₁Q_sign_eq_oangle_CBA_sign : (∑ cfg.C cfg.Q₁ cfg.Q).sign = (∑ cfg.C cfg.B cfg.A).sign := by rw [←cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_right, cfg.s_opp_side_CB_Q_Q₁.oangle_sign_eq_neg (left_mem_affine_span_pair ℝ cfg.C cfg.B) cfg.wbtw_B_A₁_C.symm.mem_affine_span, ←real.angle.sign_neg, ←oangle_rev, cfg.wbtw_B_A₁_C.oangle_sign_eq_of_ne_right cfg.Q cfg.A₁_ne_C, oangle_rotate_sign, cfg.wbtw_B_Q_B₁.oangle_eq_right cfg.Q_ne_B, cfg.wbtw_A_B₁_C.symm.oangle_sign_eq_of_ne_left cfg.B cfg.B₁_ne_C.symm] lemma oangle_CQ₁Q_eq_oangle_CBA : ∑ cfg.C cfg.Q₁ cfg.Q = ∑ cfg.C cfg.B cfg.A := oangle_eq_of_angle_eq_of_sign_eq cfg.angle_CQ₁Q_eq_angle_CBA cfg.oangle_CQ₁Q_sign_eq_oangle_CBA_sign end oriented /-! ### More obvious configuration properties -/ lemma A₁_ne_B : cfg.A₁ β‰  cfg.B := begin intro h, have hwbtw := cfg.wbtw_A_P_A₁, rw h at hwbtw, have hPQ : line[ℝ, cfg.P, cfg.Q] = line[ℝ, cfg.A, cfg.B], { rw affine_subspace.eq_iff_direction_eq_of_mem (left_mem_affine_span_pair _ _ _) hwbtw.mem_affine_span, exact cfg.PQ_parallel_AB.direction_eq }, haveI := some_orientation V, have haQ : (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.Q = (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.A, { rw [collinear.two_zsmul_oangle_eq_right _ cfg.A_ne_B cfg.Q_ne_B], rw [set.pair_comm, set.insert_comm], refine collinear_insert_of_mem_affine_span_pair _, rw ←hPQ, exact right_mem_affine_span_pair _ _ _ }, have ha : (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.Q = (2 : β„€) β€’ ∑ cfg.C cfg.Q₁ cfg.Q, { rw [oangle_CQ₁Q_eq_oangle_CBA, haQ] }, have hn : Β¬collinear ℝ ({cfg.C, cfg.B, cfg.Q} : set Pt), { rw [collinear_iff_of_two_zsmul_oangle_eq haQ, set.pair_comm, set.insert_comm, set.pair_comm], exact cfg.not_collinear_ABC }, have hc := cospherical_of_two_zsmul_oangle_eq_of_not_collinear ha hn, have hBQ₁ : cfg.B β‰  cfg.Q₁, { rw [←h], exact cfg.sbtw_Q_A₁_Q₁.ne_right }, have hQQ₁ : cfg.Q β‰  cfg.Q₁ := cfg.sbtw_Q_A₁_Q₁.left_ne_right, have hBQ₁Q : affine_independent ℝ ![cfg.B, cfg.Q₁, cfg.Q] := hc.affine_independent_of_mem_of_ne (set.mem_insert_of_mem _ (set.mem_insert _ _)) (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_insert _ _))) (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _)))) hBQ₁ cfg.Q_ne_B.symm hQQ₁.symm, rw affine_independent_iff_not_collinear_set at hBQ₁Q, refine hBQ₁Q _, rw [←h, set.pair_comm, set.insert_comm], exact cfg.sbtw_Q_A₁_Q₁.wbtw.collinear end lemma sbtw_B_A₁_C : sbtw ℝ cfg.B cfg.A₁ cfg.C := ⟨cfg.wbtw_B_A₁_C, cfg.A₁_ne_B, cfg.A₁_ne_C⟩ lemma sbtw_A_B₁_C : sbtw ℝ cfg.A cfg.B₁ cfg.C := cfg.symm.sbtw_B_A₁_C lemma sbtw_A_A₁_Aβ‚‚ : sbtw ℝ cfg.A cfg.A₁ cfg.Aβ‚‚ := begin refine sphere.sbtw_second_inter cfg.A_mem_circumsphere _, convert cfg.sbtw_B_A₁_C.dist_lt_max_dist _, change _ = max (dist (cfg.triangle_ABC.points 1) _) (dist (cfg.triangle_ABC.points 2) _), simp_rw [circumsphere_center, circumsphere_radius, dist_circumcenter_eq_circumradius, max_self] end lemma sbtw_B_B₁_Bβ‚‚ : sbtw ℝ cfg.B cfg.B₁ cfg.Bβ‚‚ := by { rw ←cfg.symm_Aβ‚‚, exact cfg.symm.sbtw_A_A₁_Aβ‚‚ } lemma Aβ‚‚_ne_A : cfg.Aβ‚‚ β‰  cfg.A := cfg.sbtw_A_A₁_Aβ‚‚.left_ne_right.symm lemma Aβ‚‚_ne_P : cfg.Aβ‚‚ β‰  cfg.P := (cfg.sbtw_A_A₁_Aβ‚‚.trans_wbtw_left_ne cfg.wbtw_A_P_A₁).symm lemma Aβ‚‚_ne_B : cfg.Aβ‚‚ β‰  cfg.B := begin intro h, have h₁ := cfg.sbtw_A_A₁_Aβ‚‚, rw h at h₁, refine cfg.not_collinear_ABC _, have hc : collinear ℝ ({cfg.A, cfg.C, cfg.B, cfg.A₁} : set Pt) := collinear_insert_insert_of_mem_affine_span_pair h₁.left_mem_affine_span cfg.sbtw_B_A₁_C.right_mem_affine_span, refine hc.subset _, rw [set.pair_comm _ cfg.A₁, set.insert_comm _ cfg.A₁, set.insert_comm _ cfg.A₁, set.pair_comm], exact set.subset_insert _ _ end lemma Aβ‚‚_ne_C : cfg.Aβ‚‚ β‰  cfg.C := begin intro h, have h₁ := cfg.sbtw_A_A₁_Aβ‚‚, rw h at h₁, refine cfg.not_collinear_ABC _, have hc : collinear ℝ ({cfg.A, cfg.B, cfg.C, cfg.A₁} : set Pt) := collinear_insert_insert_of_mem_affine_span_pair h₁.left_mem_affine_span cfg.sbtw_B_A₁_C.left_mem_affine_span, refine hc.subset (set.insert_subset_insert (set.insert_subset_insert _)), rw set.singleton_subset_iff, exact set.mem_insert _ _ end lemma Bβ‚‚_ne_B : cfg.Bβ‚‚ β‰  cfg.B := by { rw ←symm_Aβ‚‚, exact cfg.symm.Aβ‚‚_ne_A } lemma Bβ‚‚_ne_Q : cfg.Bβ‚‚ β‰  cfg.Q := by { rw ←symm_Aβ‚‚, exact cfg.symm.Aβ‚‚_ne_P } lemma Bβ‚‚_ne_Aβ‚‚ : cfg.Bβ‚‚ β‰  cfg.Aβ‚‚ := begin intro h, have hA : sbtw ℝ (cfg.triangle_ABC.points 1) cfg.A₁ (cfg.triangle_ABC.points 2) := cfg.sbtw_B_A₁_C, have hB : sbtw ℝ (cfg.triangle_ABC.points 0) cfg.B₁ (cfg.triangle_ABC.points 2) := cfg.sbtw_A_B₁_C, have hA' : cfg.Aβ‚‚ ∈ line[ℝ, cfg.triangle_ABC.points 0, cfg.A₁] := sphere.second_inter_vsub_mem_affine_span _ _ _, have hB' : cfg.Aβ‚‚ ∈ line[ℝ, cfg.triangle_ABC.points 1, cfg.B₁], { rw ←h, exact sphere.second_inter_vsub_mem_affine_span _ _ _ }, exact (sbtw_of_sbtw_of_sbtw_of_mem_affine_span_pair dec_trivial hA hB hA' hB').symm.not_rotate cfg.sbtw_A_A₁_Aβ‚‚.wbtw end lemma wbtw_B_Q_Bβ‚‚ : wbtw ℝ cfg.B cfg.Q cfg.Bβ‚‚ := cfg.sbtw_B_B₁_Bβ‚‚.wbtw.trans_left cfg.wbtw_B_Q_B₁ /-! ### The first equality in the first angle chase in the solution -/ section oriented variables [module.oriented ℝ V (fin 2)] lemma two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_BAAβ‚‚ : (2 : β„€) β€’ ∑ cfg.Q cfg.P cfg.Aβ‚‚ = (2 : β„€) β€’ ∑ cfg.B cfg.A cfg.Aβ‚‚ := begin refine two_zsmul_oangle_of_parallel cfg.QP_parallel_BA _, convert affine_subspace.parallel.refl _ using 1, rw [cfg.collinear_PAA₁Aβ‚‚.affine_span_eq_of_ne (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _)))) (set.mem_insert_of_mem _ (set.mem_insert _ _)) cfg.Aβ‚‚_ne_A, cfg.collinear_PAA₁Aβ‚‚.affine_span_eq_of_ne (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _)))) (set.mem_insert _ _) cfg.Aβ‚‚_ne_P] end end oriented /-! ### More obvious configuration properties -/ lemma not_collinear_QPAβ‚‚ : Β¬ collinear ℝ ({cfg.Q, cfg.P, cfg.Aβ‚‚} : set Pt) := begin haveI := some_orientation V, rw [collinear_iff_of_two_zsmul_oangle_eq cfg.two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_BAAβ‚‚, ←affine_independent_iff_not_collinear_set], have h : cospherical ({cfg.B, cfg.A, cfg.Aβ‚‚} : set Pt), { refine cfg.triangle_ABC.circumsphere.cospherical.subset _, simp [set.insert_subset, cfg.A_mem_circumsphere, cfg.B_mem_circumsphere, cfg.Aβ‚‚_mem_circumsphere] }, exact h.affine_independent_of_ne cfg.A_ne_B.symm cfg.Aβ‚‚_ne_B.symm cfg.Aβ‚‚_ne_A.symm end lemma Q₁_ne_Aβ‚‚ : cfg.Q₁ β‰  cfg.Aβ‚‚ := begin intro h, have h₁ := cfg.sbtw_Q_A₁_Q₁, rw h at h₁, refine cfg.not_collinear_QPAβ‚‚ _, have hAβ‚‚ := cfg.sbtw_A_A₁_Aβ‚‚.right_mem_affine_span, have hAβ‚‚A₁ : line[ℝ, cfg.Aβ‚‚, cfg.A₁] ≀ line[ℝ, cfg.A, cfg.A₁] := affine_span_pair_le_of_left_mem hAβ‚‚, have hQ : cfg.Q ∈ line[ℝ, cfg.A, cfg.A₁], { rw affine_subspace.le_def' at hAβ‚‚A₁, exact hAβ‚‚A₁ _ h₁.left_mem_affine_span }, exact collinear_triple_of_mem_affine_span_pair hQ cfg.wbtw_A_P_A₁.mem_affine_span hAβ‚‚ end lemma affine_independent_QPAβ‚‚ : affine_independent ℝ ![cfg.Q, cfg.P, cfg.Aβ‚‚] := affine_independent_iff_not_collinear_set.2 cfg.not_collinear_QPAβ‚‚ lemma affine_independent_PQBβ‚‚ : affine_independent ℝ ![cfg.P, cfg.Q, cfg.Bβ‚‚] := by { rw ←symm_Aβ‚‚, exact cfg.symm.affine_independent_QPAβ‚‚ } /-- `QPAβ‚‚` as a `triangle`. -/ def triangle_QPAβ‚‚ : triangle ℝ Pt := ⟨_, cfg.affine_independent_QPAβ‚‚βŸ© /-- `PQBβ‚‚` as a `triangle`. -/ def triangle_PQBβ‚‚ : triangle ℝ Pt := ⟨_, cfg.affine_independent_PQBβ‚‚βŸ© lemma symm_triangle_QPAβ‚‚ : cfg.symm.triangle_QPAβ‚‚ = cfg.triangle_PQBβ‚‚ := by { simp_rw [triangle_PQBβ‚‚, ←symm_Aβ‚‚], ext i, fin_cases i; refl } /-- `Ο‰` is the circle containing `Q`, `P` and `Aβ‚‚`, which will be shown also to contain `Bβ‚‚`, `P₁` and `Q₁`. -/ def Ο‰ : sphere Pt := cfg.triangle_QPAβ‚‚.circumsphere lemma P_mem_Ο‰ : cfg.P ∈ cfg.Ο‰ := cfg.triangle_QPAβ‚‚.mem_circumsphere 1 lemma Q_mem_Ο‰ : cfg.Q ∈ cfg.Ο‰ := cfg.triangle_QPAβ‚‚.mem_circumsphere 0 /-! ### The rest of the first angle chase in the solution -/ section oriented variables [module.oriented ℝ V (fin 2)] lemma two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_QBβ‚‚Aβ‚‚ : (2 : β„€) β€’ ∑ cfg.Q cfg.P cfg.Aβ‚‚ = (2 : β„€) β€’ ∑ cfg.Q cfg.Bβ‚‚ cfg.Aβ‚‚ := calc (2 : β„€) β€’ ∑ cfg.Q cfg.P cfg.Aβ‚‚ = (2 : β„€) β€’ ∑ cfg.B cfg.A cfg.Aβ‚‚ : cfg.two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_BAAβ‚‚ ... = (2 : β„€) β€’ ∑ cfg.B cfg.Bβ‚‚ cfg.Aβ‚‚ : sphere.two_zsmul_oangle_eq cfg.B_mem_circumsphere cfg.A_mem_circumsphere cfg.Bβ‚‚_mem_circumsphere cfg.Aβ‚‚_mem_circumsphere cfg.A_ne_B cfg.Aβ‚‚_ne_A.symm cfg.Bβ‚‚_ne_B cfg.Bβ‚‚_ne_Aβ‚‚ ... = (2 : β„€) β€’ ∑ cfg.Q cfg.Bβ‚‚ cfg.Aβ‚‚ : by rw cfg.wbtw_B_Q_Bβ‚‚.symm.oangle_eq_left cfg.Bβ‚‚_ne_Q.symm end oriented /-! ### Conclusions from that first angle chase -/ lemma cospherical_QPBβ‚‚Aβ‚‚ : cospherical ({cfg.Q, cfg.P, cfg.Bβ‚‚, cfg.Aβ‚‚} : set Pt) := begin haveI := some_orientation V, exact cospherical_of_two_zsmul_oangle_eq_of_not_collinear cfg.two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_QBβ‚‚Aβ‚‚ cfg.not_collinear_QPAβ‚‚ end lemma symm_Ο‰_eq_triangle_PQBβ‚‚_circumsphere : cfg.symm.Ο‰ = cfg.triangle_PQBβ‚‚.circumsphere := by rw [Ο‰, symm_triangle_QPAβ‚‚] lemma symm_Ο‰ : cfg.symm.Ο‰ = cfg.Ο‰ := begin rw [symm_Ο‰_eq_triangle_PQBβ‚‚_circumsphere, Ο‰], refine circumsphere_eq_of_cospherical hd2.out cfg.cospherical_QPBβ‚‚Aβ‚‚ _ _, { simp only [triangle_PQBβ‚‚, matrix.range_cons, matrix.range_empty, set.singleton_union, insert_emptyc_eq], rw set.insert_comm, refine set.insert_subset_insert (set.insert_subset_insert _), simp }, { simp only [triangle_QPAβ‚‚, matrix.range_cons, matrix.range_empty, set.singleton_union, insert_emptyc_eq], refine set.insert_subset_insert (set.insert_subset_insert _), simp } end /-! ### The second angle chase in the solution -/ section oriented variables [module.oriented ℝ V (fin 2)] lemma two_zsmul_oangle_CAβ‚‚A₁_eq_two_zsmul_oangle_CBA : (2 : β„€) β€’ ∑ cfg.C cfg.Aβ‚‚ cfg.A₁ = (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.A := calc (2 : β„€) β€’ ∑ cfg.C cfg.Aβ‚‚ cfg.A₁ = (2 : β„€) β€’ ∑ cfg.C cfg.Aβ‚‚ cfg.A : by rw cfg.sbtw_A_A₁_Aβ‚‚.symm.oangle_eq_right ... = (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.A : sphere.two_zsmul_oangle_eq cfg.C_mem_circumsphere cfg.Aβ‚‚_mem_circumsphere cfg.B_mem_circumsphere cfg.A_mem_circumsphere cfg.Aβ‚‚_ne_C cfg.Aβ‚‚_ne_A cfg.B_ne_C cfg.A_ne_B.symm lemma two_zsmul_oangle_CAβ‚‚A₁_eq_two_zsmul_oangle_CQ₁A₁ : (2 : β„€) β€’ ∑ cfg.C cfg.Aβ‚‚ cfg.A₁ = (2 : β„€) β€’ ∑ cfg.C cfg.Q₁ cfg.A₁ := calc (2 : β„€) β€’ ∑ cfg.C cfg.Aβ‚‚ cfg.A₁ = (2 : β„€) β€’ ∑ cfg.C cfg.B cfg.A : cfg.two_zsmul_oangle_CAβ‚‚A₁_eq_two_zsmul_oangle_CBA ... = (2 : β„€) β€’ ∑ cfg.C cfg.Q₁ cfg.Q : by rw oangle_CQ₁Q_eq_oangle_CBA ... = (2 : β„€) β€’ ∑ cfg.C cfg.Q₁ cfg.A₁ : by rw cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_right end oriented /-! ### Conclusions from that second angle chase -/ lemma not_collinear_CAβ‚‚A₁ : Β¬collinear ℝ ({cfg.C, cfg.Aβ‚‚, cfg.A₁} : set Pt) := begin haveI := some_orientation V, rw [collinear_iff_of_two_zsmul_oangle_eq cfg.two_zsmul_oangle_CAβ‚‚A₁_eq_two_zsmul_oangle_CBA, set.pair_comm, set.insert_comm, set.pair_comm], exact cfg.not_collinear_ABC end lemma cospherical_A₁Q₁CAβ‚‚ : cospherical ({cfg.A₁, cfg.Q₁, cfg.C, cfg.Aβ‚‚} : set Pt) := begin haveI := some_orientation V, rw [set.insert_comm cfg.Q₁, set.insert_comm cfg.A₁, set.pair_comm, set.insert_comm cfg.A₁, set.pair_comm], exact cospherical_of_two_zsmul_oangle_eq_of_not_collinear cfg.two_zsmul_oangle_CAβ‚‚A₁_eq_two_zsmul_oangle_CQ₁A₁ cfg.not_collinear_CAβ‚‚A₁ end /-! ### The third angle chase in the solution -/ section oriented variables [module.oriented ℝ V (fin 2)] lemma two_zsmul_oangle_QQ₁Aβ‚‚_eq_two_zsmul_oangle_QPAβ‚‚ : (2 : β„€) β€’ ∑ cfg.Q cfg.Q₁ cfg.Aβ‚‚ = (2 : β„€) β€’ ∑ cfg.Q cfg.P cfg.Aβ‚‚ := calc (2 : β„€) β€’ ∑ cfg.Q cfg.Q₁ cfg.Aβ‚‚ = (2 : β„€) β€’ ∑ cfg.A₁ cfg.Q₁ cfg.Aβ‚‚ : by rw cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_left ... = (2 : β„€) β€’ ∑ cfg.A₁ cfg.C cfg.Aβ‚‚ : cfg.cospherical_A₁Q₁CAβ‚‚.two_zsmul_oangle_eq cfg.sbtw_Q_A₁_Q₁.right_ne cfg.Q₁_ne_Aβ‚‚ cfg.A₁_ne_C.symm cfg.Aβ‚‚_ne_C.symm ... = (2 : β„€) β€’ ∑ cfg.B cfg.C cfg.Aβ‚‚ : by rw cfg.sbtw_B_A₁_C.symm.oangle_eq_left ... = (2 : β„€) β€’ ∑ cfg.B cfg.A cfg.Aβ‚‚ : sphere.two_zsmul_oangle_eq cfg.B_mem_circumsphere cfg.C_mem_circumsphere cfg.A_mem_circumsphere cfg.Aβ‚‚_mem_circumsphere cfg.B_ne_C.symm cfg.Aβ‚‚_ne_C.symm cfg.A_ne_B cfg.Aβ‚‚_ne_A.symm ... = (2 : β„€) β€’ ∑ cfg.Q cfg.P cfg.Aβ‚‚ : cfg.two_zsmul_oangle_QPAβ‚‚_eq_two_zsmul_oangle_BAAβ‚‚.symm end oriented /-! ### Conclusions from that third angle chase -/ lemma Q₁_mem_Ο‰ : cfg.Q₁ ∈ cfg.Ο‰ := begin haveI := some_orientation V, exact affine.triangle.mem_circumsphere_of_two_zsmul_oangle_eq (dec_trivial : (0 : fin 3) β‰  1) (dec_trivial : (0 : fin 3) β‰  2) dec_trivial cfg.two_zsmul_oangle_QQ₁Aβ‚‚_eq_two_zsmul_oangle_QPAβ‚‚ end lemma P₁_mem_Ο‰ : cfg.P₁ ∈ cfg.Ο‰ := by { rw ←symm_Ο‰, exact cfg.symm.Q₁_mem_Ο‰ } theorem result : concyclic ({cfg.P, cfg.Q, cfg.P₁, cfg.Q₁} : set Pt) := begin refine ⟨_, coplanar_of_fact_finrank_eq_two _⟩, rw cospherical_iff_exists_sphere, refine ⟨cfg.Ο‰, _⟩, simp only [set.insert_subset, set.singleton_subset_iff], exact ⟨cfg.P_mem_Ο‰, cfg.Q_mem_Ο‰, cfg.P₁_mem_Ο‰, cfg.Q₁_mem_Ο‰βŸ© end end imo2019q2_cfg theorem imo2019_q2 (A B C A₁ B₁ P Q P₁ Q₁ : Pt) (affine_independent_ABC : affine_independent ℝ ![A, B, C]) (wbtw_B_A₁_C : wbtw ℝ B A₁ C) (wbtw_A_B₁_C : wbtw ℝ A B₁ C) (wbtw_A_P_A₁ : wbtw ℝ A P A₁) (wbtw_B_Q_B₁ : wbtw ℝ B Q B₁) (PQ_parallel_AB : line[ℝ, P, Q] βˆ₯ line[ℝ, A, B]) (P_ne_Q : P β‰  Q) (sbtw_P_B₁_P₁ : sbtw ℝ P B₁ P₁) (angle_PP₁C_eq_angle_BAC : ∠ P P₁ C = ∠ B A C) (C_ne_P₁ : C β‰  P₁) (sbtw_Q_A₁_Q₁ : sbtw ℝ Q A₁ Q₁) (angle_CQ₁Q_eq_angle_CBA : ∠ C Q₁ Q = ∠ C B A) (C_ne_Q₁ : C β‰  Q₁) : concyclic ({P, Q, P₁, Q₁} : set Pt) := (⟨A, B, C, A₁, B₁, P, Q, P₁, Q₁, affine_independent_ABC, wbtw_B_A₁_C, wbtw_A_B₁_C, wbtw_A_P_A₁, wbtw_B_Q_B₁, PQ_parallel_AB, P_ne_Q, sbtw_P_B₁_P₁, angle_PP₁C_eq_angle_BAC, C_ne_P₁, sbtw_Q_A₁_Q₁, angle_CQ₁Q_eq_angle_CBA, C_ne_Qβ‚βŸ© : imo2019q2_cfg V Pt).result
15bb643b6c6834b247fce726ee9abbd9e61794fb
92c6b42948d74fe325c2d88530f1d36da388b2f7
/src/sexp.lean
7690529a874888ce4f3ace27640ad14f34fe592c
[ "MIT" ]
permissive
riaqn/smtlean
8ad65055b6c1600cd03b9e345059a3b24419b6d5
c11768cfb43cd634340b552f5039cba094701a87
refs/heads/master
1,584,569,627,940
1,535,314,713,000
1,535,314,713,000
135,333,334
0
1
null
null
null
null
UTF-8
Lean
false
false
4,740
lean
import data.buffer.parser import .common universe u attribute [reducible] def symbol := string inductive literal : Type | num : nat β†’ literal | str : string β†’ literal instance : has_to_string literal := ⟨ Ξ» lit, match lit with | literal.num n := "<SOME NAT>" | literal.str s := "\"" ++ s ++ "\"" end ⟩ -- list representation of S-exp inductive sexp : Type | symbol : symbol β†’ sexp | literal : literal β†’ sexp | list : list sexp β†’ sexp prefix . :1 := sexp.list prefix ! :2 := sexp.symbol prefix # :3 := sexp.literal class has_from_sexp (Ξ± : Type u) := (from_sexp {} : sexp β†’ except string Ξ± ) export has_from_sexp (from_sexp) class has_to_sexp (Ξ± : Type u) := (to_sexp {} : Ξ± β†’ sexp) export has_to_sexp (to_sexp) -- sexp β†’ string mutual def sexp_to_string, list_sexp_to_string with sexp_to_string : sexp β†’ string | (sexp.literal lit) := to_string lit | (sexp.symbol s) := s | (sexp.list l) := "(" ++ (string.intercalate " " (list_sexp_to_string l) ) ++ ")" with list_sexp_to_string : list sexp β†’ list string | [ ] := [] | (t :: l') := sexp_to_string t :: list_sexp_to_string l' instance : has_to_string sexp := ⟨ sexp_to_string ⟩ #eval (to_string $ . [! "and", . [! "or", (. [ ]), ! "a"], ! "b"]) namespace parse open parser inductive lexicon : Type | symbol : symbol β†’ lexicon | literal : literal β†’ lexicon | left : lexicon | right : lexicon | comment : string β†’ lexicon | whitespaces : lexicon def parse_whitespace : parser unit := one_of' ['\x09', '\x0a', '\x0d', '\x20'] def parse_comment : parser string := do ch ';', s ← many $ sat $ Ξ» c, Β¬ ((c = '\x0a') || (c = '\x0d')), ch '\x0a' <|> ch '\x0d', return s.as_string def parse_letter : parser char := sat $ Ξ» c, (c β‰₯ 'a') && (c ≀ 'z') || (c β‰₯ 'A') && (c ≀ 'Z') def parse_digit : parser char := sat $ Ξ» c, (c β‰₯ '0') && (c ≀ '9') def parse_punc : parser char := one_of ['~', '!', '@', '$', '%', '^', '&', '*', '_', '-', '+', '=', '<', '>', '.', '?', '/', ':', '\\'] def parse_symbol : parser symbol := do s ← parse_letter <|> parse_punc, l ← many (parse_letter <|> parse_digit <|> parse_punc), return (s :: l).as_string -- TODO: parse_literal def parse_lexicon : parser lexicon := (lexicon.symbol <$> parse_symbol) <|> (ch '(' >> return lexicon.left) <|> (ch ')' >> return lexicon.right) <|> (lexicon.comment <$> parse_comment) <|> ((many1 parse_whitespace) >> return lexicon.whitespaces) def parse_lexicons : parser (list lexicon) := do many parse_lexicon --TODO: make all the parsing function in (stateT parse_state (either parse_error) sexp)' attribute [reducible] def stack (Ξ± : Type u) : Type u := list Ξ± def conclude' {Ξ± : Type u} : stack Ξ± β†’ list Ξ± β†’ list Ξ± | (x :: xs) l := conclude' xs (x :: l) | [] l := l def conclude {Ξ± : Type u} : stack Ξ± β†’ list Ξ± := assume s, conclude' s list.nil attribute [reducible] def parse_state : Type := stack (stack sexp) -- the stack of occuring lists def conclude_list : parse_state β†’ except parse_error parse_state | (l0 :: l1 :: ls) := except.ok $ ((sexp.list (conclude l0) :: l1)::ls) | _ := except.error $ "stack too shallow to conclude" def introduce_list : parse_state β†’ except parse_error parse_state := assume p, except.ok $ ([] :: p) def append_list (e : sexp) : parse_state β†’ except parse_error parse_state | (l :: ls) := except.ok $ ((e :: l) :: ls) | _ := except.error $ "no list to append to" def sexp_from_lexicons : list lexicon β†’ parse_state β†’ except parse_error sexp | (l :: ls) p := match l with | lexicon.whitespaces := sexp_from_lexicons ls p | lexicon.comment _ := sexp_from_lexicons ls p | lexicon.symbol s := append_list (sexp.symbol s) p >>= sexp_from_lexicons ls | lexicon.literal lit := append_list (sexp.literal lit) p >>= sexp_from_lexicons ls | lexicon.left := introduce_list p >>= sexp_from_lexicons ls | lexicon.right := conclude_list p >>= sexp_from_lexicons ls end | ([]) p := do match p with | [] := except.error "too many right parenthesis" | [l] := match l with | [] := except.error "there is nothing" | [e] := except.ok e | _ := except.error (string.append "there is too many; wrap it with () if you mean a list\n" (l.to_string)) end | l := except.error $ string.append "too many left parenthesis\n" (l.to_string) end instance : has_from_buffer sexp := ⟨λ cb, (match run parse_lexicons cb with | sum.inl e := except.error e | sum.inr a := except.ok a end ) >>= (Ξ» ls, sexp_from_lexicons ls [[]]) ⟩ end parse #eval to_string (from_string "(and (or () b ) c)" : except parse_error sexp)
1222ad186382327669e16bdef4c5148a9da2df55
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/shapes/kernels.lean
1e3ba29caebd638a9a2a26ce73d90527a9b8e3fa
[ "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
27,074
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟢ Y` is the equalizer of `f` and `0 : X ⟢ Y`. (Similarly the cokernel is the coequalizer.) The basic definitions are * `kernel : (X ⟢ Y) β†’ C` * `kernel.ΞΉ : kernel f ⟢ X` * `kernel.condition : kernel.ΞΉ f ≫ f = 0` and * `kernel.lift (k : W ⟢ X) (h : k ≫ f = 0) : W ⟢ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, we prove * `kernel.ΞΉ_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.eq_zero_of_epi_kernel`: if `kernel.ΞΉ f` is an epimorphism, then `f = 0` * `kernel.of_mono`: the kernel of a monomorphism is the zero object * `kernel.lift_mono`: the lift of a monomorphism `k : W ⟢ X` such that `k ≫ f = 0` is still a monomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism * `kernel.ΞΉ_of_zero`: `kernel.ΞΉ (0 : X ⟢ Y)` is an isomorphism and the corresponding dual statements. ## Future work * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u u' open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables [has_zero_morphisms C] /-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/ abbreviation has_kernel {X Y : C} (f : X ⟢ Y) : Prop := has_limit (parallel_pair f 0) /-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/ abbreviation has_cokernel {X Y : C} (f : X ⟢ Y) : Prop := has_colimit (parallel_pair f 0) variables {X Y : C} (f : X ⟢ Y) section /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ΞΉ s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.Ο€.app one = 0 := by rw [←fork.app_zero_left, kernel_fork.condition] /-- A morphism `ΞΉ` satisfying `ΞΉ ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ΞΉ {Z : C} (ΞΉ : Z ⟢ X) (w : ΞΉ ≫ f = 0) : kernel_fork f := fork.of_ΞΉ ΞΉ $ by rw [w, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.ΞΉ_of_ΞΉ {X Y P : C} (f : X ⟢ Y) (ΞΉ : P ⟢ X) (w : ΞΉ ≫ f = 0) : fork.ΞΉ (kernel_fork.of_ΞΉ ΞΉ w) = ΞΉ := rfl section local attribute [tidy] tactic.case_bash /-- Every kernel fork `s` is isomorphic (actually, equal) to `fork.of_ΞΉ (fork.ΞΉ s) _`. -/ def iso_of_ΞΉ (s : fork f 0) : s β‰… fork.of_ΞΉ (fork.ΞΉ s) (fork.condition s) := cones.ext (iso.refl _) $ by tidy /-- If `ΞΉ = ΞΉ'`, then `fork.of_ΞΉ ΞΉ _` and `fork.of_ΞΉ ΞΉ' _` are isomorphic. -/ def of_ΞΉ_congr {P : C} {ΞΉ ΞΉ' : P ⟢ X} {w : ΞΉ ≫ f = 0} (h : ΞΉ = ΞΉ') : kernel_fork.of_ΞΉ ΞΉ w β‰… kernel_fork.of_ΞΉ ΞΉ' (by rw [←h, w]) := cones.ext (iso.refl _) $ by tidy /-- If `F` is an equivalence, then applying `F` to a diagram indexing a (co)kernel of `f` yields the diagram indexing the (co)kernel of `F.map f`. -/ def comp_nat_iso {D : Type u'} [category.{v} D] [has_zero_morphisms D] (F : C β₯€ D) [is_equivalence F] : parallel_pair f 0 β‹™ F β‰… parallel_pair (F.map f) 0 := nat_iso.of_components (Ξ» j, match j with | zero := iso.refl _ | one := iso.refl _ end) $ by tidy end /-- If `s` is a limit kernel fork and `k : W ⟢ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟢ s.X` such that `l ≫ fork.ΞΉ s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟢ X) (h : k ≫ f = 0) : {l : W ⟢ s.X // l ≫ fork.ΞΉ s = k} := ⟨hs.lift $ kernel_fork.of_ΞΉ _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a kernel fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : kernel_fork f) (lift : Ξ  (s : kernel_fork f), s.X ⟢ t.X) (fac : βˆ€ (s : kernel_fork f), lift s ≫ t.ΞΉ = s.ΞΉ) (uniq : βˆ€ (s : kernel_fork f) (m : s.X ⟢ t.X) (w : m ≫ t.ΞΉ = s.ΞΉ), m = lift s) : is_limit t := { lift := lift, fac' := Ξ» s j, by { cases j, { exact fac s, }, { simp, }, }, uniq' := Ξ» s m w, uniq s m (w limits.walking_parallel_pair.zero), } /-- This is a more convenient formulation to show that a `kernel_fork` constructed using `kernel_fork.of_ΞΉ` is a limit cone. -/ def is_limit.of_ΞΉ {W : C} (g : W ⟢ X) (eq : g ≫ f = 0) (lift : Ξ  {W' : C} (g' : W' ⟢ X) (eq' : g' ≫ f = 0), W' ⟢ W) (fac : βˆ€ {W' : C} (g' : W' ⟢ X) (eq' : g' ≫ f = 0), lift g' eq' ≫ g = g') (uniq : βˆ€ {W' : C} (g' : W' ⟢ X) (eq' : g' ≫ f = 0) (m : W' ⟢ W) (w : m ≫ g = g'), m = lift g' eq') : is_limit (kernel_fork.of_ΞΉ g eq) := is_limit_aux _ (Ξ» s, lift s.ΞΉ s.condition) (Ξ» s, fac s.ΞΉ s.condition) (Ξ» s, uniq s.ΞΉ s.condition) end section variables [has_kernel f] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ΞΉ : kernel f ⟢ X := equalizer.ΞΉ f 0 @[simp] lemma equalizer_as_kernel : equalizer.ΞΉ f 0 = kernel.ΞΉ f := rfl @[simp, reassoc] lemma kernel.condition : kernel.ΞΉ f ≫ f = 0 := kernel_fork.condition _ /-- Given any morphism `k : W ⟢ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ΞΉ f` via `kernel.lift : W ⟢ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟢ X) (h : k ≫ f = 0) : W ⟢ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ΞΉ k h) @[simp, reassoc] lemma kernel.lift_ΞΉ {W : C} (k : W ⟢ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ΞΉ f = k := limit.lift_Ο€ _ _ @[simp] lemma kernel.lift_zero {W : C} {h} : kernel.lift f (0 : W ⟢ X) h = 0 := by { ext, simp, } instance kernel.lift_mono {W : C} (k : W ⟢ X) (h : k ≫ f = 0) [mono k] : mono (kernel.lift f k h) := ⟨λ Z g g' w, begin replace w := w =≫ kernel.ΞΉ f, simp only [category.assoc, kernel.lift_ΞΉ] at w, exact (cancel_mono k).1 w, end⟩ /-- Any morphism `k : W ⟢ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟢ kernel f` such that `l ≫ kernel.ΞΉ f = k`. -/ def kernel.lift' {W : C} (k : W ⟢ X) (h : k ≫ f = 0) : {l : W ⟢ kernel f // l ≫ kernel.ΞΉ f = k} := ⟨kernel.lift f k h, kernel.lift_ΞΉ _ _ _⟩ /-- Every kernel of the zero morphism is an isomorphism -/ instance kernel.ΞΉ_zero_is_iso : is_iso (kernel.ΞΉ (0 : X ⟢ Y)) := equalizer.ΞΉ_of_self _ lemma eq_zero_of_epi_kernel [epi (kernel.ΞΉ f)] : f = 0 := (cancel_epi (kernel.ΞΉ f)).1 (by simp) /-- The kernel of a zero morphism is isomorphic to the source. -/ def kernel_zero_iso_source : kernel (0 : X ⟢ Y) β‰… X := equalizer.iso_source_of_self 0 @[simp] lemma kernel_zero_iso_source_hom : kernel_zero_iso_source.hom = kernel.ΞΉ (0 : X ⟢ Y) := rfl @[simp] lemma kernel_zero_iso_source_inv : kernel_zero_iso_source.inv = kernel.lift (0 : X ⟢ Y) (πŸ™ X) (by simp) := rfl /-- If two morphisms are known to be equal, then their kernels are isomorphic. -/ def kernel_iso_of_eq {f g : X ⟢ Y} [has_kernel f] [has_kernel g] (h : f = g) : kernel f β‰… kernel g := has_limit.iso_of_nat_iso (by simp[h]) @[simp] lemma kernel_iso_of_eq_refl {h : f = f} : kernel_iso_of_eq h = iso.refl (kernel f) := by { ext, simp [kernel_iso_of_eq], } @[simp] lemma kernel_iso_of_eq_trans {f g h : X ⟢ Y} [has_kernel f] [has_kernel g] [has_kernel h] (w₁ : f = g) (wβ‚‚ : g = h) : kernel_iso_of_eq w₁ β‰ͺ≫ kernel_iso_of_eq wβ‚‚ = kernel_iso_of_eq (w₁.trans wβ‚‚) := by { unfreezingI { induction w₁, induction wβ‚‚, }, ext, simp [kernel_iso_of_eq], } variables {f} lemma kernel_not_epi_of_nonzero (w : f β‰  0) : Β¬epi (kernel.ΞΉ f) := Ξ» I, by exactI w (eq_zero_of_epi_kernel f) lemma kernel_not_iso_of_nonzero (w : f β‰  0) : (is_iso (kernel.ΞΉ f)) β†’ false := Ξ» I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance } /-- When `g` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `f`. -/ def kernel_comp_is_iso {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : kernel (f ≫ g) β‰… kernel f := { hom := kernel.lift _ (kernel.ΞΉ _) (by { rw [←cancel_mono g], simp, }), inv := kernel.lift _ (kernel.ΞΉ _) (by simp), } @[simp] lemma kernel_comp_is_iso_hom_comp_kernel_ΞΉ {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : (kernel_comp_is_iso f g).hom ≫ kernel.ΞΉ f = kernel.ΞΉ (f ≫ g) := by simp [kernel_comp_is_iso] @[simp] lemma kernel_comp_is_iso_inv_comp_kernel_ΞΉ {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : (kernel_comp_is_iso f g).inv ≫ kernel.ΞΉ (f ≫ g) = kernel.ΞΉ f := by simp [kernel_comp_is_iso] /-- When `f` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `g`. -/ def kernel_is_iso_comp {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : kernel (f ≫ g) β‰… kernel g := { hom := kernel.lift _ (kernel.ΞΉ _ ≫ f) (by simp), inv := kernel.lift _ (kernel.ΞΉ _ ≫ inv f) (by simp), } @[simp] lemma kernel_is_iso_comp_hom_comp_kernel_ΞΉ {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : (kernel_is_iso_comp f g).hom ≫ kernel.ΞΉ g = kernel.ΞΉ (f ≫ g) ≫ f := by simp [kernel_is_iso_comp] @[simp] lemma kernel_is_iso_comp_inv_comp_kernel_ΞΉ {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : (kernel_is_iso_comp f g).inv ≫ kernel.ΞΉ (f ≫ g) = kernel.ΞΉ g ≫ (inv f) := by simp [kernel_is_iso_comp] end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, Ο€ := { app := Ξ» j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := fork.is_limit.mk _ (Ξ» s, 0) (Ξ» s, by { erw zero_comp, convert (zero_of_comp_mono f _).symm, exact kernel_fork.condition _ }) (Ξ» _ _ _, zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_kernel f] [mono f] : kernel f β‰… 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ΞΉ_of_mono [has_kernel f] [mono f] : kernel.ΞΉ f = 0 := zero_of_source_iso_zero _ (kernel.of_mono f) end has_zero_object section transport /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/ def is_kernel.of_comp_iso {Z : C} (l : X ⟢ Z) (i : Z β‰… Y) (h : l ≫ i.hom = f) {s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ΞΉ (fork.ΞΉ s) $ show fork.ΞΉ s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := fork.is_limit.mk _ (Ξ» s, hs.lift $ kernel_fork.of_ΞΉ (fork.ΞΉ s) $ by simp [←h]) (Ξ» s, by simp) (Ξ» s m h, by { apply fork.is_limit.hom_ext hs, simpa using h walking_parallel_pair.zero }) /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/ def kernel.of_comp_iso [has_kernel f] {Z : C} (l : X ⟢ Z) (i : Z β‰… Y) (h : l ≫ i.hom = f) : is_limit (kernel_fork.of_ΞΉ (kernel.ΞΉ f) $ show kernel.ΞΉ f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := is_kernel.of_comp_iso f l i h $ limit.is_limit _ /-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that `i.hom ≫ s.ΞΉ = l`, then `l` is a kernel of `f`. -/ def is_kernel.iso_kernel {Z : C} (l : Z ⟢ X) {s : kernel_fork f} (hs : is_limit s) (i : Z β‰… s.X) (h : i.hom ≫ fork.ΞΉ s = l) : is_limit (kernel_fork.of_ΞΉ l $ show l ≫ f = 0, by simp [←h]) := is_limit.of_iso_limit hs $ cones.ext i.symm $ Ξ» j, by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } } /-- If `i` is an isomorphism such that `i.hom ≫ kernel.ΞΉ f = l`, then `l` is a kernel of `f`. -/ def kernel.iso_kernel [has_kernel f] {Z : C} (l : Z ⟢ X) (i : Z β‰… kernel f) (h : i.hom ≫ kernel.ΞΉ f = l) : is_limit (kernel_fork.of_ΞΉ l $ by simp [←h]) := is_kernel.iso_kernel f l (limit.is_limit _) i h end transport section variables (X Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ def kernel.ΞΉ_of_zero : is_iso (kernel.ΞΉ (0 : X ⟢ Y)) := equalizer.ΞΉ_of_self _ end section /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.Ο€ s = 0 := by rw [cofork.condition, zero_comp] @[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ΞΉ.app zero = 0 := by rw [←cofork.left_app_one, cokernel_cofork.condition] /-- A morphism `Ο€` satisfying `f ≫ Ο€ = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_Ο€ {Z : C} (Ο€ : Y ⟢ Z) (w : f ≫ Ο€ = 0) : cokernel_cofork f := cofork.of_Ο€ Ο€ $ by rw [w, zero_comp] @[simp] lemma cokernel_cofork.Ο€_of_Ο€ {X Y P : C} (f : X ⟢ Y) (Ο€ : Y ⟢ P) (w : f ≫ Ο€ = 0) : cofork.Ο€ (cokernel_cofork.of_Ο€ Ο€ w) = Ο€ := rfl /-- Every cokernel cofork `s` is isomorphic (actually, equal) to `cofork.of_Ο€ (cofork.Ο€ s) _`. -/ def iso_of_Ο€ (s : cofork f 0) : s β‰… cofork.of_Ο€ (cofork.Ο€ s) (cofork.condition s) := cocones.ext (iso.refl _) $ Ξ» j, by cases j; tidy /-- If `Ο€ = Ο€'`, then `cokernel_cofork.of_Ο€ Ο€ _` and `cokernel_cofork.of_Ο€ Ο€' _` are isomorphic. -/ def of_Ο€_congr {P : C} {Ο€ Ο€' : Y ⟢ P} {w : f ≫ Ο€ = 0} (h : Ο€ = Ο€') : cokernel_cofork.of_Ο€ Ο€ w β‰… cokernel_cofork.of_Ο€ Ο€' (by rw [←h, w]) := cocones.ext (iso.refl _) $ Ξ» j, by cases j; tidy /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟢ W` satisfying `f ≫ k = 0` induces `l : s.X ⟢ W` such that `cofork.Ο€ s ≫ l = k`. -/ def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟢ W) (h : f ≫ k = 0) : {l : s.X ⟢ W // cofork.Ο€ s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_Ο€ _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a cokernel cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : cokernel_cofork f) (desc : Ξ  (s : cokernel_cofork f), t.X ⟢ s.X) (fac : βˆ€ (s : cokernel_cofork f), t.Ο€ ≫ desc s = s.Ο€) (uniq : βˆ€ (s : cokernel_cofork f) (m : t.X ⟢ s.X) (w : t.Ο€ ≫ m = s.Ο€), m = desc s) : is_colimit t := { desc := desc, fac' := Ξ» s j, by { cases j, { simp, }, { exact fac s, }, }, uniq' := Ξ» s m w, uniq s m (w limits.walking_parallel_pair.one), } /-- This is a more convenient formulation to show that a `cokernel_cofork` constructed using `cokernel_cofork.of_Ο€` is a limit cone. -/ def is_colimit.of_Ο€ {Z : C} (g : Y ⟢ Z) (eq : f ≫ g = 0) (desc : Ξ  {Z' : C} (g' : Y ⟢ Z') (eq' : f ≫ g' = 0), Z ⟢ Z') (fac : βˆ€ {Z' : C} (g' : Y ⟢ Z') (eq' : f ≫ g' = 0), g ≫ desc g' eq' = g') (uniq : βˆ€ {Z' : C} (g' : Y ⟢ Z') (eq' : f ≫ g' = 0) (m : Z ⟢ Z') (w : g ≫ m = g'), m = desc g' eq') : is_colimit (cokernel_cofork.of_Ο€ g eq) := is_colimit_aux _ (Ξ» s, desc s.Ο€ s.condition) (Ξ» s, fac s.Ο€ s.condition) (Ξ» s, uniq s.Ο€ s.condition) end section variables [has_cokernel f] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.Ο€ : Y ⟢ cokernel f := coequalizer.Ο€ f 0 @[simp] lemma coequalizer_as_cokernel : coequalizer.Ο€ f 0 = cokernel.Ο€ f := rfl @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.Ο€ f = 0 := cokernel_cofork.condition _ /-- Given any morphism `k : Y ⟢ W` such that `f ≫ k = 0`, `k` factors through `cokernel.Ο€ f` via `cokernel.desc : cokernel f ⟢ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟢ W) (h : f ≫ k = 0) : cokernel f ⟢ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_Ο€ k h) @[simp, reassoc] lemma cokernel.Ο€_desc {W : C} (k : Y ⟢ W) (h : f ≫ k = 0) : cokernel.Ο€ f ≫ cokernel.desc f k h = k := colimit.ΞΉ_desc _ _ @[simp] lemma cokernel.desc_zero {W : C} {h} : cokernel.desc f (0 : Y ⟢ W) h = 0 := by { ext, simp, } instance cokernel.desc_epi {W : C} (k : Y ⟢ W) (h : f ≫ k = 0) [epi k] : epi (cokernel.desc f k h) := ⟨λ Z g g' w, begin replace w := cokernel.Ο€ f ≫= w, simp only [cokernel.Ο€_desc_assoc] at w, exact (cancel_epi k).1 w, end⟩ /-- Any morphism `k : Y ⟢ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟢ W` such that `cokernel.Ο€ f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟢ W) (h : f ≫ k = 0) : {l : cokernel f ⟢ W // cokernel.Ο€ f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.Ο€_desc _ _ _⟩ /-- The cokernel of the zero morphism is an isomorphism -/ instance cokernel.Ο€_zero_is_iso : is_iso (cokernel.Ο€ (0 : X ⟢ Y)) := coequalizer.Ο€_of_self _ lemma eq_zero_of_mono_cokernel [mono (cokernel.Ο€ f)] : f = 0 := (cancel_mono (cokernel.Ο€ f)).1 (by simp) /-- The cokernel of a zero morphism is isomorphic to the target. -/ def cokernel_zero_iso_target : cokernel (0 : X ⟢ Y) β‰… Y := coequalizer.iso_target_of_self 0 @[simp] lemma cokernel_zero_iso_target_hom : cokernel_zero_iso_target.hom = cokernel.desc (0 : X ⟢ Y) (πŸ™ Y) (by simp) := rfl @[simp] lemma cokernel_zero_iso_target_inv : cokernel_zero_iso_target.inv = cokernel.Ο€ (0 : X ⟢ Y) := rfl /-- If two morphisms are known to be equal, then their cokernels are isomorphic. -/ def cokernel_iso_of_eq {f g : X ⟢ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel f β‰… cokernel g := has_colimit.iso_of_nat_iso (by simp[h]) @[simp] lemma cokernel_iso_of_eq_refl {h : f = f} : cokernel_iso_of_eq h = iso.refl (cokernel f) := by { ext, simp [cokernel_iso_of_eq], } @[simp] lemma cokernel_iso_of_eq_trans {f g h : X ⟢ Y} [has_cokernel f] [has_cokernel g] [has_cokernel h] (w₁ : f = g) (wβ‚‚ : g = h) : cokernel_iso_of_eq w₁ β‰ͺ≫ cokernel_iso_of_eq wβ‚‚ = cokernel_iso_of_eq (w₁.trans wβ‚‚) := by { unfreezingI { induction w₁, induction wβ‚‚, }, ext, simp [cokernel_iso_of_eq], } variables {f} lemma cokernel_not_mono_of_nonzero (w : f β‰  0) : Β¬mono (cokernel.Ο€ f) := Ξ» I, by exactI w (eq_zero_of_mono_cokernel f) lemma cokernel_not_iso_of_nonzero (w : f β‰  0) : (is_iso (cokernel.Ο€ f)) β†’ false := Ξ» I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance } /-- When `g` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `f`. -/ def cokernel_comp_is_iso {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel (f ≫ g) β‰… cokernel f := { hom := cokernel.desc _ (inv g ≫ cokernel.Ο€ f) (by simp), inv := cokernel.desc _ (g ≫ cokernel.Ο€ (f ≫ g)) (by rw [←category.assoc, cokernel.condition]), } @[simp] lemma cokernel_Ο€_comp_cokernel_comp_is_iso_hom {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel.Ο€ (f ≫ g) ≫ (cokernel_comp_is_iso f g).hom = inv g ≫ cokernel.Ο€ f := by simp [cokernel_comp_is_iso] @[simp] lemma cokernel_Ο€_comp_cokernel_comp_is_iso_inv {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel.Ο€ f ≫ (cokernel_comp_is_iso f g).inv = g ≫ cokernel.Ο€ (f ≫ g) := by simp [cokernel_comp_is_iso] /-- When `f` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `g`. -/ def cokernel_is_iso_comp {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel (f ≫ g) β‰… cokernel g := { hom := cokernel.desc _ (cokernel.Ο€ g) (by simp), inv := cokernel.desc _ (cokernel.Ο€ (f ≫ g)) (by { rw [←cancel_epi f, ←category.assoc], simp, }), } @[simp] lemma cokernel_Ο€_comp_cokernel_is_iso_comp_hom {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel.Ο€ (f ≫ g) ≫ (cokernel_is_iso_comp f g).hom = cokernel.Ο€ g := by simp [cokernel_is_iso_comp] @[simp] lemma cokernel_Ο€_comp_cokernel_is_iso_comp_inv {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel.Ο€ g ≫ (cokernel_is_iso_comp f g).inv = cokernel.Ο€ (f ≫ g) := by simp [cokernel_is_iso_comp] end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ΞΉ := { app := Ξ» j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := cofork.is_colimit.mk _ (Ξ» s, 0) (Ξ» s, by { erw zero_comp, convert (zero_of_epi_comp f _).symm, exact cokernel_cofork.condition _ }) (Ξ» _ _ _, zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f β‰… 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism of an epimorphism is a zero morphism -/ lemma cokernel.Ο€_of_epi [has_cokernel f] [epi f] : cokernel.Ο€ f = 0 := zero_of_target_iso_zero _ (cokernel.of_epi f) end has_zero_object section has_image /-- The cokernel of the image inclusion of a morphism `f` is isomorphic to the cokernel of `f`. (This result requires that the factorisation through the image is an epimorphism. This holds in any category with equalizers.) -/ @[simps] def cokernel_image_ΞΉ {X Y : C} (f : X ⟢ Y) [has_image f] [has_cokernel (image.ΞΉ f)] [has_cokernel f] [epi (factor_thru_image f)] : cokernel (image.ΞΉ f) β‰… cokernel f := { hom := cokernel.desc _ (cokernel.Ο€ f) begin have w := cokernel.condition f, conv at w { to_lhs, congr, rw ←image.fac f, }, rw [←has_zero_morphisms.comp_zero (limits.factor_thru_image f), category.assoc, cancel_epi] at w, exact w, end, inv := cokernel.desc _ (cokernel.Ο€ _) begin conv { to_lhs, congr, rw ←image.fac f, }, rw [category.assoc, cokernel.condition, has_zero_morphisms.comp_zero], end, } end has_image section variables (X Y) /-- The cokernel of a zero morphism is an isomorphism -/ def cokernel.Ο€_of_zero : is_iso (cokernel.Ο€ (0 : X ⟢ Y)) := coequalizer.Ο€_of_self _ end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_cokernel f] [has_kernel (cokernel.Ο€ f)] [epi f] : is_iso (kernel.ΞΉ (cokernel.Ο€ f)) := equalizer.ΞΉ_of_eq $ cokernel.Ο€_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_kernel f] [has_cokernel (kernel.ΞΉ f)] [mono f] : is_iso (cokernel.Ο€ (kernel.ΞΉ f)) := coequalizer.Ο€_of_eq $ kernel.ΞΉ_of_mono f end has_zero_object section transport /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of `l`. -/ def is_cokernel.of_iso_comp {Z : C} (l : Z ⟢ Y) (i : X β‰… Z) (h : i.hom ≫ l = f) {s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_Ο€ (cofork.Ο€ s) $ show l ≫ cofork.Ο€ s = 0, by simp [i.eq_inv_comp.2 h]) := cofork.is_colimit.mk _ (Ξ» s, hs.desc $ cokernel_cofork.of_Ο€ (cofork.Ο€ s) $ by simp [←h]) (Ξ» s, by simp) (Ξ» s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h walking_parallel_pair.one }) /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of `l`. -/ def cokernel.of_iso_comp [has_cokernel f] {Z : C} (l : Z ⟢ Y) (i : X β‰… Z) (h : i.hom ≫ l = f) : is_colimit (cokernel_cofork.of_Ο€ (cokernel.Ο€ f) $ show l ≫ cokernel.Ο€ f = 0, by simp [i.eq_inv_comp.2 h]) := is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _ /-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that `s.Ο€ ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def is_cokernel.cokernel_iso {Z : C} (l : Y ⟢ Z) {s : cokernel_cofork f} (hs : is_colimit s) (i : s.X β‰… Z) (h : cofork.Ο€ s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_Ο€ l $ show f ≫ l = 0, by simp [←h]) := is_colimit.of_iso_colimit hs $ cocones.ext i $ Ξ» j, by { cases j, { simp }, { exact h } } /-- If `i` is an isomorphism such that `cokernel.Ο€ f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def cokernel.cokernel_iso [has_cokernel f] {Z : C} (l : Y ⟢ Z) (i : cokernel f β‰… Z) (h : cokernel.Ο€ f ≫ i.hom = l) : is_colimit (cokernel_cofork.of_Ο€ l $ by simp [←h]) := is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h end transport end category_theory.limits namespace category_theory.limits variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] /-- `has_kernels` represents the existence of kernels for every morphism. -/ class has_kernels : Prop := (has_limit : Ξ  {X Y : C} (f : X ⟢ Y), has_kernel f) /-- `has_cokernels` represents the existence of cokernels for every morphism. -/ class has_cokernels : Prop := (has_colimit : Ξ  {X Y : C} (f : X ⟢ Y), has_cokernel f) attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit @[priority 100] instance has_kernels_of_has_equalizers [has_equalizers C] : has_kernels C := { has_limit := by apply_instance } @[priority 100] instance has_cokernels_of_has_coequalizers [has_coequalizers C] : has_cokernels C := { has_colimit := by apply_instance } end category_theory.limits
5aafa0ac319c3d1b1e1a2c92083120b342cd8137
75cbd886877138cccf93fb0ef52fb0eb9c519305
/src/maps.lean
997d0668b498dfddcb5130a1fa0ebe4c8d606383
[]
no_license
kmill/lean-graphs
973ad2bb652032c2ef6087995af60294a561dab5
bd3139daf81c0f41ce5ade951195858cdf038bd2
refs/heads/master
1,667,752,580,941
1,592,947,279,000
1,592,947,279,000
274,511,081
1
0
null
null
null
null
UTF-8
Lean
false
false
13,138
lean
-- combinatorial maps --import data.multiset import data.list.perm import data.fintype.basic import data.equiv.basic import group_theory.perm.cycles import myequiv import tactic namespace maps open function open equiv universe u -- A two-dimension combinatorial map is a collection D of darts, a -- permutation Οƒ whose orbits correspond to vertices, and a -- fixed-point-free involution Ο„ whose orbits correspond to edges. We -- think of Οƒ as giving the next dart counterclockwise around an edge, -- and Ο„ as giving the opposite dart of an edge. (Note: this -- definition excludes disjoint isolated vertices.) -- -- We only care about the case where the orbits of Οƒ are finite, but -- we do not require it in the definition. structure cmap (D : Type u) := (Οƒ : perm D) (Ο„ : perm D) (Ο„_inv : involutive Ο„) (Ο„_fp_free : Β¬has_fixed_point Ο„) namespace cmap variables {D D' : Type u} -- The next dart counter-clockwise around a face @[simp] def Ο• (m : cmap D) : perm D := equiv.trans m.Οƒ.symm m.Ο„ -- We only will care about the case of equivalences, but in this -- definition a homomorphism of combinatorial maps is sort of like a -- branched covering map of surfaces branched over the vertices. def hom (m : cmap D) (m' : cmap D') (f : D β†’ D') := (f ∘ m.Οƒ = m'.Οƒ ∘ f) ∧ (f ∘ m.Ο„ = m'.Ο„ ∘ f) lemma hom_inv_is_hom (m : cmap D) (m' : cmap D') (f : equiv D D') (h : hom m m' f) : hom m' m f.symm := begin split, calc f.symm ∘ m'.Οƒ = f.symm ∘ m'.Οƒ ∘ id : by refl ... = f.symm ∘ m'.Οƒ ∘ (f ∘ f.symm) : by rw ←self_comp_symm ... = f.symm ∘ (m'.Οƒ ∘ f) ∘ f.symm : by refl ... = f.symm ∘ (f ∘ m.Οƒ) ∘ f.symm : by rw ← h.1 ... = (f.symm ∘ f) ∘ m.Οƒ ∘ f.symm : by refl ... = id ∘ m.Οƒ ∘ f.symm : by rw symm_comp_self ... = m.Οƒ ∘ f.symm : by refl, calc f.symm ∘ m'.Ο„ = f.symm ∘ m'.Ο„ ∘ id : by refl ... = f.symm ∘ m'.Ο„ ∘ (f ∘ f.symm) : by rw ←self_comp_symm ... = f.symm ∘ (m'.Ο„ ∘ f) ∘ f.symm : by refl ... = f.symm ∘ (f ∘ m.Ο„) ∘ f.symm : by rw ← h.2 ... = (f.symm ∘ f) ∘ m.Ο„ ∘ f.symm : by refl ... = id ∘ m.Ο„ ∘ f.symm : by rw symm_comp_self ... = m.Ο„ ∘ f.symm : by refl, end -- In light of `hom_inv_is_hom`, we define an equivalence of maps as -- an equivalence of their dart sets that is a homomorphism. def equiv_maps (m : cmap D) (m' : cmap D') (f : equiv D D') := hom m m' f -- We define the opposite of a map to be the one which reverses the identities of the darts on each edge def opp (m : cmap D) : cmap D := ⟨equiv.trans (equiv.trans m.Ο„ m.Οƒ) m.Ο„, m.Ο„, m.Ο„_inv, m.Ο„_fp_free⟩ -- Form the dual map. This swaps the roles of vertices and faces def dual (m : cmap D) : cmap D := ⟨m.Ο•, m.Ο„, m.Ο„_inv, m.Ο„_fp_free⟩ lemma double_dual_is_opp (m : cmap D) : m.dual.dual = m.opp := begin cases m, dsimp [opp, dual], congr, calc (m_Οƒ.symm.trans m_Ο„).symm = m_Ο„.symm.trans m_Οƒ.symm.symm : by rw equiv.symm_trans_eq_trans_sym ... = m_Ο„.symm.trans m_Οƒ : by rw equiv.symm_symm ... = m_Ο„.trans m_Οƒ : by rw equiv.symm_involution m_Ο„ m_Ο„_inv, end -- The opposite of a map (and hence the double dual) is equivalent to the original map. lemma double_dual (m : cmap D) : βˆƒ (f : equiv D D), hom m m.opp f := begin use m.Ο„, split, calc m.Ο„ ∘ m.Οƒ = m.Ο„ ∘ m.Οƒ ∘ id : by refl ... = m.Ο„ ∘ m.Οƒ ∘ (m.Ο„ ∘ m.Ο„) : by rw ←equiv.involution_comp_involution m.Ο„ m.Ο„_inv ... = m.opp.Οƒ ∘ m.Ο„ : by refl, refl, end -- A "dual homomorphism" is a homomorphism that sends vertices to -- faces and faces to vertices. The entire point of this definition -- is purely for `dual_dequiv`. def dhom (m : cmap D) (m' : cmap D') (f : D β†’ D') := (f ∘ m.Οƒ = m'.Ο• ∘ f) ∧ (f ∘ m.Ο„ = m'.Ο„ ∘ f) -- This is a dhom from a map to its dual. See `dual_dequiv`. def to_dual (m : cmap D) : D β†’ D := m.Ο„ -- A map and its dual are dual equivalent (hence the name) lemma dual_dequiv (m : cmap D) : dhom m m.dual (to_dual m) := begin split, ext, simp [dual, to_dual], refl, end @[reducible] def vertex_setoid (m : cmap D) := perm.psetoid m.Οƒ @[reducible] def edge_setoid (m : cmap D) := perm.psetoid m.Ο„ @[reducible] def face_setoid (m : cmap D) := perm.psetoid m.Ο• @[reducible] def vertices (m : cmap D) := quotient (vertex_setoid m) @[reducible] def edges (m : cmap D) := quotient (edge_setoid m) @[reducible] def faces (m : cmap D) := quotient (face_setoid m) -- The vertex at the dart @[reducible] def dart_vertex (m : cmap D) (d : D) : m.vertices := @quotient.mk _ (vertex_setoid m) d -- The edge on the the dart @[reducible] def dart_edge (m : cmap D) (d : D) : m.edges := @quotient.mk _ (edge_setoid m) d -- The face to the left of the dart. That is, the one traced out by `m.Ο•` @[reducible] def dart_face (m : cmap D) (d : D) : m.faces := @quotient.mk _ (face_setoid m) d -- The degree of a vertex is the number of incident darts. def vertices.deg {m : cmap D} [fintype D] [decidable_eq D] (v : m.vertices) : β„• := begin dsimp [vertices] at v, induction v, exact fintype.card {d | perm.same_cycle m.Οƒ v d}, simp, congr, ext, change m.Οƒ.same_cycle v_a v_b at v_p, split, intro sc1, exact perm.same_cycle.trans _ (perm.same_cycle.symm _ v_p) sc1, intro sc2, exact perm.same_cycle.trans _ v_p sc2, end def vertices.darts {m : cmap D} (v : m.vertices) := {d : D | m.dart_vertex d = v} instance vertices.darts.fintype {m : cmap D} [fintype D] [decidable_eq D] (v : m.vertices) : fintype v.darts := begin induction v, change fintype {d : D | @quotient.mk _ (vertex_setoid m) d = @quotient.mk _ (vertex_setoid m) v}, simp, change fintype {d : D | perm.same_cycle m.Οƒ d v}, apply_instance, have h : βˆ€ d, m.Οƒ.same_cycle d v_a ↔ m.Οƒ.same_cycle d v_b, { sorry, }, suggest, end def vertices.deg {m : cmap D} [fintype D] [decidable_eq D] (v : m.vertices) : β„• := fintype.card v.darts -- Apply m.Οƒ to a dart at a vertex, yielding another dart at the same vertex def vertices.Οƒ {m : cmap D} (v : m.vertices) : perm v.darts := begin let f : v.darts β†’ v.darts, { rintro ⟨d, hd⟩, refine ⟨m.Οƒ d, _⟩, simp [vertices.darts] at ⊒ hd, rw ←hd, dsimp [dart_vertex], apply quotient.sound, change perm.same_cycle _ _ _, rw ←perm.same_cycle_apply, }, let g : v.darts β†’ v.darts, { rintro ⟨d, hd⟩, refine ⟨m.Οƒ.symm d, _⟩, simp [vertices.darts] at ⊒ hd, rw ←hd, dsimp [dart_vertex], apply quotient.sound, change perm.same_cycle _ _ _, rw ←perm.same_cycle_inv_apply, rw perm.inv_def, }, use [f,g], rintro ⟨d,h⟩, simp [f,g], rintro ⟨d,h⟩, simp [f,g], end -- Apply m.Οƒ to a dart at a vertex, yielding another dart at the same vertex def vertices.Οƒ {m : cmap D} (v : m.vertices) (d : v.darts) : v.darts := begin cases d, refine ⟨m.Οƒ d_val, _⟩, simp [vertices.darts] at ⊒ d_property, rw ← d_property, dsimp [dart_vertex], apply quotient.sound, change perm.same_cycle _ _ _, rw ←perm.same_cycle_apply, end def faces.darts {m : cmap D} (f : m.faces) := {d : D | m.dart_face d = f} def faces.Οƒ {m : cmap D} (f : m.faces) (d : f.darts) : f.darts := def dart_between.helper {m : cmap D} [decidable_eq D] (v : m.vertices) : β„• β†’ v.darts β†’ v.darts β†’ v.darts β†’ Prop | 0 _ _ _ := false | (n+1) dlo dhi d := if dlo = dhi then true else dart_between.helper n (v.Οƒ dlo) dhi d -- Given three darts dlo, dhi, and d around a given vertex, determines -- whether d is between dlo and dhi (inclusive), going counterclockwise. def dart_between {m : cmap D} [fintype D] [decidable_eq D] (v : m.vertices) (dlo dhi d : v.darts) : Prop := dart_between.helper v v.deg dlo dhi d --def vertices.darts_from {m : cmap D} [fintype D] [decidable_eq D] (v : m.vertices) {d : D} (h : v = m.dart_vertex d) : list D := --(list.range v.deg).m -- The number of sides of a given face def faces.sides {m : cmap D} [fintype D] [decidable_eq D] (f : m.faces) : β„• := begin dsimp [faces] at f, induction f, exact fintype.card {d | perm.same_cycle m.Ο• f d}, simp, congr, ext, change m.Ο•.same_cycle f_a f_b at f_p, split, intro sc1, exact perm.same_cycle.trans _ (perm.same_cycle.symm _ f_p) sc1, intro sc2, exact perm.same_cycle.trans _ f_p sc2, end def dual_vertex_face_equiv (m : cmap D) : m.faces ≃ m.dual.vertices := begin let f : m.faces β†’ m.dual.vertices := begin intro x, induction x, exact m.dual.dart_vertex x, change perm.same_cycle _ _ _ at x_p, simpa, end, let g : m.dual.vertices β†’ m.faces := begin intro x, induction x, exact m.dart_face x, change perm.same_cycle _ _ _ at x_p, simpa, end, use [f, g], intro x, induction x, refl, refl, intro x, induction x, refl, refl, end def dual_edge_edge_equiv (m : cmap D) : m.edges ≃ m.dual.edges := begin use [id, id], intro x, induction x, refl, refl, intro x, induction x, refl, refl, end -- def opp_vertex_equiv_vertex (m : cmap D) : m.vertices ≃ m.opp.vertices := -- ⟨begin -- dsimp [vertices], -- intro v, induction v, exact dart_vertex m.opp (m.Ο„ v), -- simp [dart_vertex], -- apply quot.sound, -- simp [perm.same_cycle, opp], -- rcases v_p with ⟨i,eq⟩, use i, unfold_coes, -- -- calc (((m.Ο„.trans m.Οƒ).trans m.Ο„) ^ i) (m.Ο„ v_a) -- -- = (m.Ο„.trans (m.Οƒ ^ i).trans m.Ο„.symm) (m.Ο„ v_a) -- -- ... = (m.Ο„.trans (m.Οƒ ^ i).trans m.Ο„.symm) (m.Ο„ v_a) -- end,sorry,sorry,sorry⟩ -- def dual_vertex_face_equiv (m : cmap D) : m.vertices ≃ m.dual.faces := -- begin -- refine ⟨_,_,_,_⟩, -- dsimp [vertices,faces,dual,vertex_setoid,face_setoid], -- end def euler_characteristic (m : cmap D) [fintype D] [decidable_eq D] : β„€ := ↑(fintype.card m.vertices) - ↑(fintype.card m.edges) + ↑(fintype.card m.faces) inductive path (m : cmap D) : m.vertices β†’ m.vertices β†’ Type u | refl {v : m.vertices} : path v v | edge (d : D) : path (m.dart_vertex d) (m.dart_vertex (m.Ο„ d)) | join {u v w : m.vertices} : path u v β†’ path v w β†’ path u w def path.symm {m : cmap D} : βˆ€ {v w : m.vertices}, path m v w β†’ path m w v | _ _ path.refl := path.refl | _ _ (path.join p₁ pβ‚‚) := path.join pβ‚‚.symm p₁.symm | _ _ (path.edge d) := begin have h : m.dart_vertex d = m.dart_vertex (m.Ο„ (m.Ο„ d)), rw m.Ο„_inv d, rw h, exact path.edge (m.Ο„ d), end def path.length {m : cmap D} : βˆ€{v w : m.vertices}, path m v w β†’ β„• | _ _ path.refl := 0 | _ _ (path.edge d) := 1 | _ _ (path.join p1 p2) := p1.length + p2.length def connected (m : cmap D) (v w : m.vertices) : Prop := nonempty (path m v w) def connected.setoid (m : cmap D) : setoid m.vertices := ⟨connected m, (Ξ» x, ⟨path.refl⟩), (Ξ» x y r, nonempty.rec_on r (Ξ» r', ⟨path.symm r'⟩)), (Ξ» x y z r₁ rβ‚‚, nonempty.rec_on r₁ (Ξ» r₁', nonempty.rec_on rβ‚‚ (Ξ» rβ‚‚', ⟨path.join r₁' rβ‚‚'⟩)))⟩ def Ο€β‚€ (m : cmap D) := quotient (connected.setoid m) def disk (m : cmap D) (v : m.vertices) (n : β„•) : set m.vertices := {w : m.vertices | βˆƒ (p : path m v w), p.length ≀ n} lemma disk.subset (m : cmap D) (v : m.vertices) {n₁ nβ‚‚ : β„•} (h : n₁ ≀ nβ‚‚) : m.disk v n₁ βŠ† m.disk v nβ‚‚ := begin rintros v ⟨p, plen⟩, exact ⟨p, by linarith⟩, end lemma disk.finite_bound (m : cmap D) [fintype D] [decidable_eq D] {v w : m.vertices} (h : m.connected v w) : w ∈ m.disk v (fintype.card D) := begin unfreezeI, rcases h with ⟨p⟩, let lengths := {n | n ≀ p.length ∧ βˆƒ (q : m.path v w), n = q.length}, have len_in : p.length ∈ lengths, { split, linarith, use p, }, have Asup := well_founded.has_min nat.lt_wf lengths ⟨p.length, len_in⟩, rcases Asup with ⟨m, m_in, Asup⟩, rcases m_in.2 with ⟨q, qlen⟩, have hup : q.length ≀ fintype.card D, { by_contradiction, push_neg at a, -- rw qlen at a, sorry, --pigeonhole principle }, exact ⟨q, hup⟩, end instance disk.decidable_pred (m : cmap D) [fintype D] [decidable_eq D] (v : m.vertices) (n : β„•) : decidable_pred (m.disk v n) := begin intro w, dunfold disk, end -- this is the statement that you can do graph searches instance connected.decidable_rel (m : cmap D) [fintype D] [decidable_eq D] : decidable_rel (connected m) := begin intros v w, let d := m.disk v (fintype.card D), end instance Ο€β‚€.fintype (m : cmap D) [fintype D] [decidable_eq D] : fintype (Ο€β‚€ m) := begin have h : decidable_rel (connected.setoid m).r, { change decidable_rel (connected m), apply_instance, }, apply @quotient.fintype _ _ (connected.setoid m) h, end -- The zeroth Betti number is the number of connected components def bβ‚€ (m : cmap D) [fintype D] [decidable_eq D] : β„• := fintype.card (Ο€β‚€ m) --def genus (m : cmap D) [fintype D] [decidable_eq D] : β„• := m.bβ‚€ - m.euler_characteristic/2 end cmap end maps
1dc6ee3a0d9fda2776d68f03d2e47f58516f9b37
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/field.lean
4a3e9d4703a39cfe67308dc64babfb6cd27ad4bc
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
8,907
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 algebra.ring logic.basic open set universe u variables {Ξ± : Type u} -- Default priority sufficient as core version has custom-set lower priority (100) /-- Core version `division_ring_has_div` erratically requires two instances of `division_ring` -/ instance division_ring_has_div' [division_ring Ξ±] : has_div Ξ± := ⟨algebra.div⟩ instance division_ring.to_domain [s : division_ring Ξ±] : domain Ξ± := { eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» a b h, classical.by_contradiction $ Ξ» hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s } @[simp] theorem inv_one [division_ring Ξ±] : (1⁻¹ : Ξ±) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field Ξ±] (x : Ξ±) : x⁻¹⁻¹ = x := if h : x = 0 then by rw [h, inv_zero, inv_zero] else division_ring.inv_inv h lemma inv_involutive' [discrete_field Ξ±] : function.involutive (has_inv.inv : Ξ± β†’ Ξ±) := inv_inv' namespace units variables [division_ring Ξ±] {a b : Ξ±} /-- Embed an element of a division ring 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 : Ξ±) (ha : a β‰  0) : units Ξ± := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] theorem inv_eq_inv (u : units Ξ±) : (↑u⁻¹ : Ξ±) = u⁻¹ := (mul_left_inj u).1 $ by rw [units.mul_inv, mul_inv_cancel]; apply units.ne_zero @[simp] theorem mk0_val (ha : a β‰  0) : (mk0 a ha : Ξ±) = a := rfl @[simp] theorem mk0_inv (ha : a β‰  0) : ((mk0 a ha)⁻¹ : Ξ±) = a⁻¹ := rfl @[simp] lemma mk0_coe (u : units Ξ±) (h : (u : Ξ±) β‰  0) : mk0 (u : Ξ±) h = u := units.ext rfl @[simp] lemma mk0_inj {a b : Ξ±} (ha : a β‰  0) (hb : b β‰  0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, Ξ» h, units.ext h⟩ end units section division_ring variables [s : division_ring Ξ±] {a b c : Ξ±} include s lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl attribute [simp] div_one zero_div div_self theorem divp_eq_div (a : Ξ±) (u : units Ξ±) : a /β‚š u = a / u := congr_arg _ $ units.inv_eq_inv _ @[simp] theorem divp_mk0 (a : Ξ±) {b : Ξ±} (hb : b β‰  0) : a /β‚š units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div (ha : a β‰  0) (hb : b β‰  0) : (a / b)⁻¹ = b / a := (mul_inv_eq (inv_ne_zero hb) ha).trans $ by rw division_ring.inv_inv hb; refl lemma inv_div_left (ha : a β‰  0) (hb : b β‰  0) : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_eq ha hb).symm lemma neg_inv (h : a β‰  0) : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div _ h] lemma division_ring.inv_comm_of_comm (h : a β‰  0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (Ξ» x:Ξ±, a⁻¹ * x * a⁻¹) H.symm, rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one, ← mul_assoc, inv_mul_cancel, one_mul] at this; exact h end lemma div_ne_zero (ha : a β‰  0) (hb : b β‰  0) : a / b β‰  0 := division_ring.mul_ne_zero ha (inv_ne_zero hb) lemma div_ne_zero_iff (hb : b β‰  0) : a / b β‰  0 ↔ a β‰  0 := ⟨mt (Ξ» h, by rw [h, zero_div]), Ξ» ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b β‰  0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma add_div (a b c : Ξ±) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma div_right_inj (hc : c β‰  0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj] lemma sub_div (a b c : Ξ±) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj (ha : a β‰  0) (hb : b β‰  0) : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← division_ring.inv_inv ha, ← division_ring.inv_inv hb, h], congr_arg (Ξ»x,x⁻¹)⟩ lemma division_ring.inv_eq_iff (ha : a β‰  0) (hb : b β‰  0) : a⁻¹ = b ↔ b⁻¹ = a := by rw [← division_ring.inv_inj (inv_ne_zero ha) hb, eq_comm, division_ring.inv_inv ha] lemma div_neg (a : Ξ±) (hb : b β‰  0) : a / -b = -(a / b) := by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div] lemma div_eq_iff_mul_eq (hb : b β‰  0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], Ξ» h, by rw [← h, mul_div_cancel _ hb]⟩ end division_ring instance field.to_integral_domain [F : field Ξ±] : integral_domain Ξ± := { ..F, ..division_ring.to_domain } section variables [field Ξ±] {a b c d : Ξ±} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma inv_add_inv {a b : Ξ±} (ha : a β‰  0) (hb : b β‰  0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : Ξ±} (ha : a β‰  0) (hb : b β‰  0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma mul_div_right_comm (a b c : Ξ±) : (a * b) / c = (a / c) * b := (div_mul_eq_mul_div _ _ _).symm lemma mul_comm_div (a b c : Ξ±) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm (a b c : Ξ±) : (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 : Ξ±) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma field.div_right_comm (a : Ξ±) (hb : b β‰  0) (hc : c β‰  0) : (a / b) / c = (a / c) / b := by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm] lemma field.div_div_div_cancel_right (a : Ξ±) (hb : b β‰  0) (hc : c β‰  0) : (a / c) / (b / c) = a / b := by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc] lemma div_mul_div_cancel (a : Ξ±) (hc : c β‰  0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] lemma div_eq_div_iff (hb : b β‰  0) (hd : d β‰  0) : a / b = c / d ↔ a * d = c * b := (domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $ by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] lemma field.div_div_cancel (ha : a β‰  0) (hb : b β‰  0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha] end section variables [discrete_field Ξ±] {a b c : Ξ±} attribute [simp] inv_zero div_zero lemma div_right_comm (a b c : Ξ±) : (a / b) / c = (a / c) / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else if c0 : c = 0 then by simp only [c0, div_zero, zero_div] else field.div_right_comm _ b0 c0 lemma div_div_div_cancel_right (a b : Ξ±) (hc : c β‰  0) : (a / c) / (b / c) = a / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else field.div_div_div_cancel_right _ b0 hc lemma div_div_cancel (ha : a β‰  0) : a / (a / b) = b := if b0 : b = 0 then by simp only [b0, div_zero] else field.div_div_cancel ha b0 @[simp] lemma inv_eq_zero {a : Ξ±} : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a β‰  0, by simp [*, inv_ne_zero]) lemma neg_inv' (a : Ξ±) : (-a)⁻¹ = - a⁻¹ := begin by_cases a = 0, { rw [h, neg_zero, inv_zero, neg_zero] }, { rw [neg_inv h] } end end @[reducible] def is_field_hom {Ξ± Ξ²} [division_ring Ξ±] [division_ring Ξ²] (f : Ξ± β†’ Ξ²) := is_ring_hom f namespace is_field_hom open is_ring_hom section variables {Ξ² : Type*} [division_ring Ξ±] [division_ring Ξ²] variables (f : Ξ± β†’ Ξ²) [is_field_hom f] {x y : Ξ±} lemma map_ne_zero : f x β‰  0 ↔ x β‰  0 := ⟨mt $ Ξ» h, h.symm β–Έ map_zero f, Ξ» x0 h, one_ne_zero $ calc 1 = f (x * x⁻¹) : by rw [mul_inv_cancel x0, map_one f] ... = 0 : by rw [map_mul f, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 (map_ne_zero f) lemma map_inv' (h : x β‰  0) : f x⁻¹ = (f x)⁻¹ := (domain.mul_left_inj ((map_ne_zero f).2 h)).1 $ by rw [mul_inv_cancel ((map_ne_zero f).2 h), ← map_mul f, mul_inv_cancel h, map_one f] lemma map_div' (h : y β‰  0) : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv' f h lemma injective : function.injective f := (is_add_group_hom.injective_iff _).2 (Ξ» a ha, classical.by_contradiction $ Ξ» ha0, by simpa [ha, is_ring_hom.map_mul f, is_ring_hom.map_one f, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end section variables {Ξ² : Type*} [discrete_field Ξ±] [discrete_field Ξ²] variables (f : Ξ± β†’ Ξ²) [is_field_hom f] {x y : Ξ±} lemma map_inv : f x⁻¹ = (f x)⁻¹ := classical.by_cases (by rintro rfl; simp only [map_zero f, inv_zero]) (map_inv' f) lemma map_div : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv f end end is_field_hom
58188be0d13d45d96bfe60034b1a6fd50250ab7c
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/algebra/group.lean
38859e23432da362db7a24d7eed0c376f508bf1a
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
17,321
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 local attribute [instance] set.pointwise_one set.pointwise_mul set.pointwise_add filter.pointwise_mul filter.pointwise_add filter.pointwise_one section variables [topological_space Ξ±] [group Ξ±] [topological_group Ξ±] @[to_additive] lemma is_open_pointwise_mul_left {s t : set Ξ±} : is_open t β†’ is_open (s * t) := Ξ» ht, begin have : βˆ€a, is_open ((Ξ» (x : Ξ±), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw pointwise_mul_eq_Union_mul_left, exact is_open_Union (Ξ»a, is_open_Union $ Ξ»ha, this _), end @[to_additive] lemma is_open_pointwise_mul_right {s t : set Ξ±} : is_open s β†’ is_open (s * t) := Ξ» hs, begin have : βˆ€a, is_open ((Ξ» (x : Ξ±), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw pointwise_mul_eq_Union_mul_right, exact is_open_Union (Ξ»a, is_open_Union $ Ξ»ha, this _), end variables (Ξ±) lemma topological_group.t1_space (h : @is_closed Ξ± _ {1}) : t1_space Ξ± := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space Ξ±] : regular_space Ξ± := ⟨assume s a hs ha, let f := Ξ» p : Ξ± Γ— Ξ±, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ tβ‚‚ open such that a ∈ t₁ Γ— tβ‚‚ βŠ† f⁻¹' (-s) let ⟨t₁, tβ‚‚, ht₁, htβ‚‚, a_mem_t₁, one_mem_tβ‚‚, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:Ξ±) (by simpa [f]) in begin use s * tβ‚‚, use is_open_pointwise_mul_left htβ‚‚, use Ξ» x hx, ⟨x, hx, 1, one_mem_tβ‚‚, (mul_one _).symm⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_tβ‚βŸ©, rintros x hx ⟨y, hy, z, hz, yz⟩, have : x * z⁻¹ ∈ sᢜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space Ξ±] : t2_space Ξ± := regular_space.t2_space Ξ± end section variables [topological_space Ξ±] [comm_group Ξ±] [topological_group Ξ±] @[to_additive] lemma nhds_pointwise_mul (x y : Ξ±) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(Ξ»a, a * x⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, (Ξ»a, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, v_mem, w, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, ⟨b, hb, ba⟩, c, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, _, y, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (Ξ»x:Ξ±, 𝓝 x) := ⟨λ_ _, nhds_pointwise_mul _ _⟩ end end filter_mul
c7392f6fa5536a48afdc6ebb21f722c6e61b3730
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/perm/cycle/basic.lean
804eba5fc61eb7faaa9ce89eb37df0ba8bddce8c
[ "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
59,962
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.finset.noncomm_prod import group_theory.perm.sign import logic.equiv.fintype /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm Ξ²`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `Ξ²` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `Ξ²` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. ## Main results * This file contains several closure results: - `closure_is_cycle` : The symmetric group is generated by cycles - `closure_cycle_adjacent_swap` : The symmetric group is generated by a cycle and an adjacent transposition - `closure_cycle_coprime_swap` : The symmetric group is generated by a cycle and a coprime transposition - `closure_prime_cycle_swap` : The symmetric group is generated by a prime cycle and a transposition -/ namespace equiv.perm open equiv function finset variables {Ξ± : Type*} {Ξ² : Type*} [decidable_eq Ξ±] section sign_cycle /-! ### `is_cycle` -/ variables [fintype Ξ±] /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm Ξ²) : Prop := βˆƒ x, f x β‰  x ∧ βˆ€ y, f y β‰  y β†’ βˆƒ i : β„€, (f ^ i) x = y lemma is_cycle.ne_one {f : perm Ξ²} (h : is_cycle f) : f β‰  1 := Ξ» hf, by simpa [hf, is_cycle] using h @[simp] lemma not_is_cycle_one : Β¬ (1 : perm Ξ²).is_cycle := Ξ» H, H.ne_one rfl lemma is_cycle.two_le_card_support {f : perm Ξ±} (h : is_cycle f) : 2 ≀ f.support.card := two_le_card_support_of_ne_one h.ne_one lemma is_cycle_swap {Ξ± : Type*} [decidable_eq Ξ±] {x y : Ξ±} (hxy : x β‰  y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, Ξ» a (ha : ite (a = x) y (ite (a = y) x a) β‰  a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by { rw [zpow_one, swap_apply_def], split_ifs at *; cc }⟩⟩ lemma is_swap.is_cycle {Ξ± : Type*} [decidable_eq Ξ±] {f : perm Ξ±} (hf : is_swap f) : is_cycle f := begin obtain ⟨x, y, hxy, rfl⟩ := hf, exact is_cycle_swap hxy, end lemma is_cycle.inv {f : perm Ξ²} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }, Ξ» y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }) in ⟨-i, by rwa [zpow_neg, inv_zpow, inv_inv]⟩⟩ lemma is_cycle.is_cycle_conj {f g : perm Ξ²} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) := begin obtain ⟨a, ha1, ha2⟩ := hf, refine ⟨g a, by simp [ha1], Ξ» b hb, _⟩, obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _, { refine ⟨i, _⟩, rw conj_zpow, simp [hi] }, { contrapose! hb, rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] } end lemma is_cycle.exists_zpow_eq {f : perm Ξ²} (hf : is_cycle f) {x y : Ξ²} (hx : f x β‰  x) (hy : f y β‰  y) : βˆƒ i : β„€, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← zpow_add, sub_add_cancel, hb]⟩ lemma is_cycle.exists_pow_eq [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) {x y : Ξ²} (hx : f x β‰  x) (hy : f y β‰  y) : βˆƒ i : β„•, (f ^ i) x = y := let ⟨n, hn⟩ := hf.exists_zpow_eq hx hy in by classical; exact ⟨(n % order_of f).to_nat, by { have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))), rwa [← zpow_coe_nat, int.to_nat_of_nonneg this, ← zpow_eq_mod_order_of] }⟩ lemma is_cycle.exists_pow_eq_one [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) : βˆƒ (k : β„•) (hk : 1 < k), f ^ k = 1 := begin classical, have : is_of_fin_order f := exists_pow_eq_one f, rw is_of_fin_order_iff_pow_eq_one at this, obtain ⟨x, hx, hx'⟩ := hf, obtain ⟨_ | _ | k, hk, hk'⟩ := this, { exact absurd hk (lt_asymm hk) }, { rw pow_one at hk', simpa [hk'] using hx }, { exact ⟨k + 2, by simp, hk'⟩ } end /-- The subgroup generated by a cycle is in bijection with its support -/ noncomputable def is_cycle.zpowers_equiv_support {Οƒ : perm Ξ±} (hΟƒ : is_cycle Οƒ) : (↑(subgroup.zpowers Οƒ) : set (perm Ξ±)) ≃ (↑(Οƒ.support) : set Ξ±) := equiv.of_bijective (Ξ» Ο„, βŸ¨Ο„ (classical.some hΟƒ), begin obtain βŸ¨Ο„, n, rfl⟩ := Ο„, rw [finset.mem_coe, coe_fn_coe_base', subtype.coe_mk, zpow_apply_mem_support, mem_support], exact (classical.some_spec hΟƒ).1, end⟩) begin split, { rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h, ext y, by_cases hy : Οƒ y = y, { simp_rw [subtype.coe_mk, zpow_apply_eq_self_of_apply_eq_self hy] }, { obtain ⟨i, rfl⟩ := (classical.some_spec hΟƒ).2 y hy, rw [subtype.coe_mk, subtype.coe_mk, zpow_apply_comm Οƒ m i, zpow_apply_comm Οƒ n i], exact congr_arg _ (subtype.ext_iff.mp h) } }, by { rintros ⟨y, hy⟩, rw [finset.mem_coe, mem_support] at hy, obtain ⟨n, rfl⟩ := (classical.some_spec hΟƒ).2 y hy, exact βŸ¨βŸ¨Οƒ ^ n, n, rfl⟩, rfl⟩ }, end @[simp] lemma is_cycle.zpowers_equiv_support_apply {Οƒ : perm Ξ±} (hΟƒ : is_cycle Οƒ) {n : β„•} : hΟƒ.zpowers_equiv_support βŸ¨Οƒ ^ n, n, rfl⟩ = ⟨(Οƒ ^ n) (classical.some hΟƒ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hΟƒ).1)⟩ := rfl @[simp] lemma is_cycle.zpowers_equiv_support_symm_apply {Οƒ : perm Ξ±} (hΟƒ : is_cycle Οƒ) (n : β„•) : hΟƒ.zpowers_equiv_support.symm ⟨(Οƒ ^ n) (classical.some hΟƒ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hΟƒ).1)⟩ = βŸ¨Οƒ ^ n, n, rfl⟩ := (equiv.symm_apply_eq _).2 hΟƒ.zpowers_equiv_support_apply lemma order_of_is_cycle {Οƒ : perm Ξ±} (hΟƒ : is_cycle Οƒ) : order_of Οƒ = Οƒ.support.card := begin rw [order_eq_card_zpowers, ←fintype.card_coe], convert fintype.card_congr (is_cycle.zpowers_equiv_support hΟƒ), end lemma is_cycle_swap_mul_aux₁ {Ξ± : Type*} [decidable_eq Ξ±] : βˆ€ (n : β„•) {b x : Ξ±} {f : perm Ξ±} (hb : (swap x (f x) * f) b β‰  b) (h : (f ^ n) (f x) = b), βˆƒ i : β„€, ((swap x (f x) * f) ^ i) (f x) = b | 0 := Ξ» b x f hb h, ⟨0, h⟩ | (n+1 : β„•) := Ξ» b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b β‰  b ∧ b β‰  x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) β‰  f⁻¹ b, by { rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← f.injective.eq_iff, apply_inv_self], exact this.1 }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by { rw [apply_inv_self], rwa [pow_succ, mul_apply] at h }) in ⟨i + 1, by rw [add_comm, zpow_add, mul_apply, hi, zpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_auxβ‚‚ {Ξ± : Type*} [decidable_eq Ξ±] : βˆ€ (n : β„€) {b x : Ξ±} {f : perm Ξ±} (hb : (swap x (f x) * f) b β‰  b) (h : (f ^ n) (f x) = b), βˆƒ i : β„€, ((swap x (f x) * f) ^ i) (f x) = b | (n : β„•) := Ξ» b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := Ξ» b x f hb h, if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b β‰  b ∧ b β‰  x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) β‰  f⁻¹ b, by { rw [mul_apply, swap_apply_def], split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, zpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc }, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← zpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, zpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, zpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, zpow_add, zpow_one, zpow_neg, ← inv_zpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, zpow_add, zpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma is_cycle.eq_swap_of_apply_apply_eq_self {Ξ± : Type*} [decidable_eq Ξ±] {f : perm Ξ±} (hf : is_cycle f) {x : Ξ±} (hfx : f x β‰  x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ Ξ» y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (Ξ» hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, zpow_add, mul_apply, hi] at hj, cases zpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle.swap_mul {Ξ± : Type*} [decidable_eq Ξ±] {f : perm Ξ±} (hf : is_cycle f) {x : Ξ±} (hx : f x β‰  x) (hffx : f (f x) β‰  x) : is_cycle (swap x (f x) * f) := ⟨f x, by { simp [swap_apply_def, mul_apply, if_neg hffx, f.injective.eq_iff, if_neg hx, hx], }, Ξ» y hy, let ⟨i, hi⟩ := hf.exists_zpow_eq hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : β„€)) x : by rw [zpow_one, mul_apply] ... = y : by rwa [← zpow_add, sub_add_cancel], is_cycle_swap_mul_auxβ‚‚ (i - 1) hy hi⟩ lemma is_cycle.sign : βˆ€ {f : perm Ξ±} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := Ξ» hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self hx.1 h1, card_support_swap hx.1.symm], refl } else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq _ _ h1, card_insert_of_not_mem (not_mem_erase _ _), sdiff_singleton_eq_erase], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by { rw [sign_mul, sign_swap hx.1.symm, (hf.swap_mul hx.1 h1).sign, ← h], simp only [pow_add, mul_one, neg_neg, one_mul, mul_neg, eq_self_iff_true, pow_one, neg_mul_neg] } using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, measure_wf (Ξ» f, f.support.card)⟩]} lemma is_cycle_of_is_cycle_pow {Οƒ : perm Ξ±} {n : β„•} (h1 : is_cycle (Οƒ ^ n)) (h2 : Οƒ.support ≀ (Οƒ ^ n).support) : is_cycle Οƒ := begin have key : βˆ€ x : Ξ±, (Οƒ ^ n) x β‰  x ↔ Οƒ x β‰  x, { simp_rw [←mem_support], exact finset.ext_iff.mp (le_antisymm (support_pow_le Οƒ n) h2) }, obtain ⟨x, hx1, hx2⟩ := h1, refine ⟨x, (key x).mp hx1, Ξ» y hy, _⟩, cases (hx2 y ((key y).mpr hy)) with i _, exact ⟨n * i, by rwa zpow_mul⟩ end -- The lemma `support_zpow_le` is relevant. It means that `h2` is equivalent to -- `Οƒ.support = (Οƒ ^ n).support`, as well as to `Οƒ.support.card ≀ (Οƒ ^ n).support.card`. lemma is_cycle_of_is_cycle_zpow {Οƒ : perm Ξ±} {n : β„€} (h1 : is_cycle (Οƒ ^ n)) (h2 : Οƒ.support ≀ (Οƒ ^ n).support) : is_cycle Οƒ := begin cases n, { exact is_cycle_of_is_cycle_pow h1 h2 }, { simp only [le_eq_subset, zpow_neg_succ_of_nat, perm.support_inv] at h1 h2, simpa using is_cycle_of_is_cycle_pow h1.inv h2 } end lemma is_cycle.extend_domain {Ξ± : Type*} {p : Ξ² β†’ Prop} [decidable_pred p] (f : Ξ± ≃ subtype p) {g : perm Ξ±} (h : is_cycle g) : is_cycle (g.extend_domain f) := begin obtain ⟨a, ha, ha'⟩ := h, refine ⟨f a, _, Ξ» b hb, _⟩, { rw extend_domain_apply_image, exact Ξ» con, ha (f.injective (subtype.coe_injective con)) }, by_cases pb : p b, { obtain ⟨i, hi⟩ := ha' (f.symm ⟨b, pb⟩) (Ξ» con, hb _), { refine ⟨i, _⟩, have hnat : βˆ€ (k : β„•) (a : Ξ±), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k ih, { refl }, rw [pow_succ, perm.mul_apply, ih, extend_domain_apply_image, pow_succ, perm.mul_apply] }, have hint : βˆ€ (k : β„€) (a : Ξ±), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k k, { rw [zpow_of_nat, zpow_of_nat, hnat] }, rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_eq_iff_eq, hnat, apply_inv_self] }, rw [hint, hi, apply_symm_apply, subtype.coe_mk] }, { rw [extend_domain_apply_subtype _ _ pb, con, apply_symm_apply, subtype.coe_mk] } }, { exact (hb (extend_domain_apply_not_subtype _ _ pb)).elim } end lemma nodup_of_pairwise_disjoint_cycles {l : list (perm Ξ²)} (h1 : βˆ€ f ∈ l, is_cycle f) (h2 : l.pairwise disjoint) : l.nodup := nodup_of_pairwise_disjoint (Ξ» h, (h1 1 h).ne_one rfl) h2 end sign_cycle /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle (f : perm Ξ²) (x y : Ξ²) : Prop := βˆƒ i : β„€, (f ^ i) x = y @[refl] lemma same_cycle.refl (f : perm Ξ²) (x : Ξ²) : same_cycle f x x := ⟨0, rfl⟩ @[symm] lemma same_cycle.symm {f : perm Ξ²} {x y : Ξ²} : same_cycle f x y β†’ same_cycle f y x := Ξ» ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← hi, inv_apply_self]⟩ @[trans] lemma same_cycle.trans {f : perm Ξ²} {x y z : Ξ²} : same_cycle f x y β†’ same_cycle f y z β†’ same_cycle f x z := Ξ» ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [zpow_add, mul_apply, hi, hj]⟩ lemma same_cycle.apply_eq_self_iff {f : perm Ξ²} {x y : Ξ²} : same_cycle f x y β†’ (f x = x ↔ f y = y) := Ξ» ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← zpow_one_add, add_comm, zpow_add_one, mul_apply, (f ^ i).injective.eq_iff] lemma is_cycle.same_cycle {f : perm Ξ²} (hf : is_cycle f) {x y : Ξ²} (hx : f x β‰  x) (hy : f y β‰  y) : same_cycle f x y := hf.exists_zpow_eq hx hy lemma same_cycle.nat' [fintype Ξ²] {f : perm Ξ²} {x y : Ξ²} (h : same_cycle f x y) : βˆƒ (i : β„•) (h : i < order_of f), (f ^ i) x = y := begin classical, obtain ⟨k, rfl⟩ := h, use ((k % order_of f).nat_abs), have hβ‚€ := int.coe_nat_pos.mpr (order_of_pos f), have h₁ := int.mod_nonneg k hβ‚€.ne', rw [←zpow_coe_nat, int.nat_abs_of_nonneg h₁, ←zpow_eq_mod_order_of], refine ⟨_, rfl⟩, rw [←int.coe_nat_lt, int.nat_abs_of_nonneg h₁], exact int.mod_lt_of_pos _ hβ‚€, end lemma same_cycle.nat'' [fintype Ξ²] {f : perm Ξ²} {x y : Ξ²} (h : same_cycle f x y) : βˆƒ (i : β„•) (hpos : 0 < i) (h : i ≀ order_of f), (f ^ i) x = y := begin classical, obtain ⟨_|i, hi, rfl⟩ := h.nat', { refine ⟨order_of f, order_of_pos f, le_rfl, _⟩, rw [pow_order_of_eq_one, pow_zero] }, { exact ⟨i.succ, i.zero_lt_succ, hi.le, rfl⟩ } end instance [fintype Ξ±] (f : perm Ξ±) : decidable_rel (same_cycle f) := Ξ» x y, decidable_of_iff (βˆƒ n ∈ list.range (fintype.card (perm Ξ±)), (f ^ n) x = y) ⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, Ξ» ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2 (int.coe_nat_lt.1 $ by { rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { simp [order_of_le_card_univ] }, exact fintype_perm }, exact fintype_perm, }), by { rw [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← zpow_eq_mod_order_of, hi], exact fintype_perm }⟩⟩ lemma same_cycle_apply {f : perm Ξ²} {x y : Ξ²} : same_cycle f x (f y) ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [zpow_add, mul_apply, hi, zpow_neg_one, inv_apply_self]⟩, Ξ» ⟨i, hi⟩, ⟨1 + i, by rw [zpow_add, mul_apply, hi, zpow_one]⟩⟩ lemma same_cycle_cycle {f : perm Ξ²} {x : Ξ²} (hx : f x β‰  x) : is_cycle f ↔ (βˆ€ {y}, same_cycle f x y ↔ f y β‰  y) := ⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $ by { rw [← zpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi, rw [hi, hy] }, hf.exists_zpow_eq hx⟩, Ξ» h, ⟨x, hx, Ξ» y hy, h.2 hy⟩⟩ lemma same_cycle_inv (f : perm Ξ²) {x y : Ξ²} : same_cycle f⁻¹ x y ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← inv_zpow, hi]⟩, Ξ» ⟨i, hi⟩, ⟨-i, by rw [zpow_neg, ← inv_zpow, inv_inv, hi]⟩ ⟩ lemma same_cycle_inv_apply {f : perm Ξ²} {x y : Ξ²} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y := by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv] @[simp] lemma same_cycle_pow_left_iff {f : perm Ξ²} {x y : Ξ²} {n : β„•} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin split, { rintro ⟨k, rfl⟩, use (k + n), simp [zpow_add] }, { rintro ⟨k, rfl⟩, use (k - n), rw [←zpow_coe_nat, ←mul_apply, ←zpow_add, int.sub_add_cancel] } end @[simp] lemma same_cycle_zpow_left_iff {f : perm Ξ²} {x y : Ξ²} {n : β„€} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin cases n, { exact same_cycle_pow_left_iff }, { rw [zpow_neg_succ_of_nat, ←inv_pow, ←same_cycle_inv, same_cycle_pow_left_iff, same_cycle_inv] } end /-- Unlike `support_congr`, which assumes that `βˆ€ (x ∈ g.support), f x = g x)`, here we have the weaker assumption that `βˆ€ (x ∈ f.support), f x = g x`. -/ lemma is_cycle.support_congr [fintype Ξ±] {f g : perm Ξ±} (hf : is_cycle f) (hg : is_cycle g) (h : f.support βŠ† g.support) (h' : βˆ€ (x ∈ f.support), f x = g x) : f = g := begin have : f.support = g.support, { refine le_antisymm h _, intros z hz, obtain ⟨x, hx, hf'⟩ := id hf, have hx' : g x β‰  x, { rwa [←h' x (mem_support.mpr hx)] }, obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz), have h'' : βˆ€ (x ∈ f.support ∩ g.support), f x = g x, { intros x hx, exact h' x (mem_of_mem_inter_left hx) }, rwa [←hm, ←pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')), pow_apply_mem_support, mem_support] }, refine support_congr h _, simpa [←this] using h' end /-- If two cyclic permutations agree on all terms in their intersection, and that intersection is not empty, then the two cyclic permutations must be equal. -/ lemma is_cycle.eq_on_support_inter_nonempty_congr [fintype Ξ±] {f g : perm Ξ±} (hf : is_cycle f) (hg : is_cycle g) (h : βˆ€ (x ∈ f.support ∩ g.support), f x = g x) {x : Ξ±} (hx : f x = g x) (hx' : x ∈ f.support) : f = g := begin have hx'' : x ∈ g.support, { rwa [mem_support, ←hx, ←mem_support] }, have : f.support βŠ† g.support, { intros y hy, obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy), rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support] }, rw (inter_eq_left_iff_subset _ _).mpr this at h, exact hf.support_congr hg this h end lemma is_cycle.support_pow_eq_iff [fintype Ξ±] {f : perm Ξ±} (hf : is_cycle f) {n : β„•} : support (f ^ n) = support f ↔ Β¬ order_of f ∣ n := begin rw order_of_dvd_iff_pow_eq_one, split, { intros h H, refine hf.ne_one _, rw [←support_eq_empty_iff, ←h, H, support_one] }, { intro H, apply le_antisymm (support_pow_le _ n) _, intros x hx, contrapose! H, ext z, by_cases hz : f z = z, { rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply] }, { obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx), apply (f ^ k).injective, rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply], simpa using H } } end lemma is_cycle.pow_iff [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) {n : β„•} : is_cycle (f ^ n) ↔ n.coprime (order_of f) := begin classical, split, { intro h, have hr : support (f ^ n) = support f, { rw hf.support_pow_eq_iff, rintro ⟨k, rfl⟩, refine h.ne_one _, simp [pow_mul, pow_order_of_eq_one] }, have : order_of (f ^ n) = order_of f, { rw [order_of_is_cycle h, hr, order_of_is_cycle hf] }, rw [order_of_pow, nat.div_eq_self] at this, cases this, { exact absurd this (order_of_pos _).ne' }, { rwa [nat.coprime_iff_gcd_eq_one, nat.gcd_comm] } }, { intro h, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h, have hf' : is_cycle ((f ^ n) ^ m) := by rwa hm, refine is_cycle_of_is_cycle_pow hf' _, intros x hx, rw [hm], exact support_pow_le _ n hx } end lemma is_cycle.pow_eq_one_iff [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) {n : β„•} : f ^ n = 1 ↔ βˆƒ x, f x β‰  x ∧ (f ^ n) x = x := begin classical, split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, by_cases h : support (f ^ n) = support f, { rw [← mem_support, ← h, mem_support] at hx, contradiction }, { rw [hf.support_pow_eq_iff, not_not] at h, obtain ⟨k, rfl⟩ := h, rw [pow_mul, pow_order_of_eq_one, one_pow] } } end lemma is_cycle.pow_eq_pow_iff [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) {a b : β„•} : f ^ a = f ^ b ↔ βˆƒ x, f x β‰  x ∧ (f ^ a) x = (f ^ b) x := begin classical, split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, wlog hab : a ≀ b, suffices : f ^ (b - a) = 1, { rw [pow_sub _ hab, mul_inv_eq_one] at this, rw this }, rw hf.pow_eq_one_iff, by_cases hfa : (f ^ a) x ∈ f.support, { refine ⟨(f ^ a) x, mem_support.mp hfa, _⟩, simp only [pow_sub _ hab, equiv.perm.coe_mul, function.comp_app, inv_apply_self, ← hx'] }, { have h := @equiv.perm.zpow_apply_comm _ f 1 a x, simp only [zpow_one, zpow_coe_nat] at h, rw [not_mem_support, h, function.injective.eq_iff (f ^ a).injective] at hfa, contradiction }} end lemma is_cycle.mem_support_pos_pow_iff_of_lt_order_of [fintype Ξ±] {f : perm Ξ±} (hf : is_cycle f) {n : β„•} (npos : 0 < n) (hn : n < order_of f) {x : Ξ±} : x ∈ (f ^ n).support ↔ x ∈ f.support := begin have : Β¬ order_of f ∣ n := nat.not_dvd_of_pos_of_lt npos hn, rw ←hf.support_pow_eq_iff at this, rw this end lemma is_cycle.is_cycle_pow_pos_of_lt_prime_order [fintype Ξ²] {f : perm Ξ²} (hf : is_cycle f) (hf' : (order_of f).prime) (n : β„•) (hn : 0 < n) (hn' : n < order_of f) : is_cycle (f ^ n) := begin classical, have : n.coprime (order_of f), { refine nat.coprime.symm _, rw nat.prime.coprime_iff_not_dvd hf', exact nat.not_dvd_of_pos_of_lt hn hn' }, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this, have hf'' := hf, rw ←hm at hf'', refine is_cycle_of_is_cycle_pow hf'' _, rw [hm], exact support_pow_le f n end /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : perm Ξ± := of_subtype (@subtype_perm _ f (same_cycle f x) (Ξ» _, same_cycle_apply.symm)) lemma cycle_of_apply [fintype Ξ±] (f : perm Ξ±) (x y : Ξ±) : cycle_of f x y = if same_cycle f x y then f y else y := rfl lemma cycle_of_inv [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : (cycle_of f x)⁻¹ = cycle_of f⁻¹ x := equiv.ext $ Ξ» y, begin rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply], split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at * end @[simp] lemma cycle_of_pow_apply_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : βˆ€ n : β„•, (cycle_of f x ^ n) x = (f ^ n) x | 0 := rfl | (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply, cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply], exact ⟨n, rfl⟩ } @[simp] lemma cycle_of_zpow_apply_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : βˆ€ n : β„€, (cycle_of f x ^ n) x = (f ^ n) x | (n : β„•) := cycle_of_pow_apply_self f x n | -[1+ n] := by rw [zpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv, zpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self] lemma same_cycle.cycle_of_apply [fintype Ξ±] {f : perm Ξ±} {x y : Ξ±} (h : same_cycle f x y) : cycle_of f x y = f y := dif_pos h lemma cycle_of_apply_of_not_same_cycle [fintype Ξ±] {f : perm Ξ±} {x y : Ξ±} (h : Β¬same_cycle f x y) : cycle_of f x y = y := dif_neg h lemma same_cycle.cycle_of_eq [fintype Ξ±] {f : perm Ξ±} {x y : Ξ±} (h : same_cycle f x y) : cycle_of f x = cycle_of f y := begin ext z, rw cycle_of_apply, split_ifs with hz hz, { exact (h.symm.trans hz).cycle_of_apply.symm }, { exact (cycle_of_apply_of_not_same_cycle (mt h.trans hz)).symm } end @[simp] lemma cycle_of_apply_apply_zpow_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) (k : β„€) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := begin rw same_cycle.cycle_of_apply, { rw [add_comm, zpow_add, zpow_one, mul_apply] }, { exact ⟨k, rfl⟩ } end @[simp] lemma cycle_of_apply_apply_pow_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) (k : β„•) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := by convert cycle_of_apply_apply_zpow_self f x k using 1 @[simp] lemma cycle_of_apply_apply_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : cycle_of f x (f x) = f (f x) := by convert cycle_of_apply_apply_pow_self f x 1 using 1 @[simp] lemma cycle_of_apply_self [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply lemma is_cycle.cycle_of_eq [fintype Ξ±] {f : perm Ξ±} (hf : is_cycle f) {x : Ξ±} (hx : f x β‰  x) : cycle_of f x = f := equiv.ext $ Ξ» y, if h : same_cycle f x y then by rw [h.cycle_of_apply] else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)] @[simp] lemma cycle_of_eq_one_iff [fintype Ξ±] (f : perm Ξ±) {x : Ξ±} : cycle_of f x = 1 ↔ f x = x := begin simp_rw [ext_iff, cycle_of_apply, one_apply], refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), Ξ» h y, _⟩, by_cases hy : f y = y, { rw [hy, if_t_t] }, { exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) }, end @[simp] lemma cycle_of_self_apply [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : cycle_of f (f x) = cycle_of f x := (same_cycle_apply.mpr (same_cycle.refl _ _)).symm.cycle_of_eq @[simp] lemma cycle_of_self_apply_pow [fintype Ξ±] (f : perm Ξ±) (n : β„•) (x : Ξ±) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_pow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq @[simp] lemma cycle_of_self_apply_zpow [fintype Ξ±] (f : perm Ξ±) (n : β„€) (x : Ξ±) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_zpow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq lemma is_cycle.cycle_of [fintype Ξ±] {f : perm Ξ±} (hf : is_cycle f) {x : Ξ±} : cycle_of f x = if f x = x then 1 else f := begin by_cases hx : f x = x, { rwa [if_pos hx, cycle_of_eq_one_iff] }, { rwa [if_neg hx, hf.cycle_of_eq] }, end lemma cycle_of_one [fintype Ξ±] (x : Ξ±) : cycle_of 1 x = 1 := (cycle_of_eq_one_iff 1).mpr rfl lemma is_cycle_cycle_of [fintype Ξ±] (f : perm Ξ±) {x : Ξ±} (hx : f x β‰  x) : is_cycle (cycle_of f x) := have cycle_of f x x β‰  x, by rwa [(same_cycle.refl _ _).cycle_of_apply], (same_cycle_cycle this).2 $ Ξ» y, ⟨λ h, mt h.apply_eq_self_iff.2 this, Ξ» h, if hxy : same_cycle f x y then let ⟨i, hi⟩ := hxy in ⟨i, by rw [cycle_of_zpow_apply_self, hi]⟩ else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩ @[simp] lemma two_le_card_support_cycle_of_iff [fintype Ξ±] {f : perm Ξ±} {x : Ξ±} : 2 ≀ card (cycle_of f x).support ↔ f x β‰  x := begin refine ⟨λ h, _, Ξ» h, by simpa using (is_cycle_cycle_of _ h).two_le_card_support⟩, contrapose! h, rw ←cycle_of_eq_one_iff at h, simp [h] end @[simp] lemma card_support_cycle_of_pos_iff [fintype Ξ±] {f : perm Ξ±} {x : Ξ±} : 0 < card (cycle_of f x).support ↔ f x β‰  x := begin rw [←two_le_card_support_cycle_of_iff, ←nat.succ_le_iff], exact ⟨λ h, or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩ end lemma pow_apply_eq_pow_mod_order_of_cycle_of_apply [fintype Ξ±] (f : perm Ξ±) (n : β„•) (x : Ξ±) : (f ^ n) x = (f ^ (n % order_of (cycle_of f x))) x := by rw [←cycle_of_pow_apply_self f, ←cycle_of_pow_apply_self f, pow_eq_mod_order_of] lemma cycle_of_mul_of_apply_right_eq_self [fintype Ξ±] {f g : perm Ξ±} (h : _root_.commute f g) (x : Ξ±) (hx : g x = x) : (f * g).cycle_of x = f.cycle_of x := begin ext y, by_cases hxy : (f * g).same_cycle x y, { obtain ⟨z, rfl⟩ := hxy, rw cycle_of_apply_apply_zpow_self, simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx] }, { rw [cycle_of_apply_of_not_same_cycle hxy, cycle_of_apply_of_not_same_cycle], contrapose! hxy, obtain ⟨z, rfl⟩ := hxy, refine ⟨z, _⟩, simp [h.mul_zpow, zpow_apply_eq_self_of_apply_eq_self hx] } end lemma disjoint.cycle_of_mul_distrib [fintype Ξ±] {f g : perm Ξ±} (h : f.disjoint g) (x : Ξ±) : (f * g).cycle_of x = (f.cycle_of x * g.cycle_of x) := begin cases (disjoint_iff_eq_or_eq.mp h) x with hfx hgx, { simp [h.commute.eq, cycle_of_mul_of_apply_right_eq_self h.symm.commute, hfx] }, { simp [cycle_of_mul_of_apply_right_eq_self h.commute, hgx] } end lemma support_cycle_of_eq_nil_iff [fintype Ξ±] {f : perm Ξ±} {x : Ξ±} : (f.cycle_of x).support = βˆ… ↔ x βˆ‰ f.support := by simp lemma support_cycle_of_le [fintype Ξ±] (f : perm Ξ±) (x : Ξ±) : support (f.cycle_of x) ≀ support f := begin intros y hy, rw [mem_support, cycle_of_apply] at hy, split_ifs at hy, { exact mem_support.mpr hy }, { exact absurd rfl hy } end lemma mem_support_cycle_of_iff [fintype Ξ±] {f : perm Ξ±} {x y : Ξ±} : y ∈ support (f.cycle_of x) ↔ same_cycle f x y ∧ x ∈ support f := begin by_cases hx : f x = x, { rw (cycle_of_eq_one_iff _).mpr hx, simp [hx] }, { rw [mem_support, cycle_of_apply], split_ifs with hy, { simp only [hx, hy, iff_true, ne.def, not_false_iff, and_self, mem_support], rcases hy with ⟨k, rfl⟩, rw ←not_mem_support, simpa using hx }, { simpa [hx] using hy } } end lemma same_cycle.mem_support_iff [fintype Ξ±] {f : perm Ξ±} {x y : Ξ±} (h : same_cycle f x y) : x ∈ support f ↔ y ∈ support f := ⟨λ hx, support_cycle_of_le f x (mem_support_cycle_of_iff.mpr ⟨h, hx⟩), Ξ» hy, support_cycle_of_le f y (mem_support_cycle_of_iff.mpr ⟨h.symm, hy⟩)⟩ lemma pow_mod_card_support_cycle_of_self_apply [fintype Ξ±] (f : perm Ξ±) (n : β„•) (x : Ξ±) : (f ^ (n % (f.cycle_of x).support.card)) x = (f ^ n) x := begin by_cases hx : f x = x, { rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx] }, { rw [←cycle_of_pow_apply_self, ←cycle_of_pow_apply_self f, ←order_of_is_cycle (is_cycle_cycle_of f hx), ←pow_eq_mod_order_of] } end /-- x is in the support of f iff cycle_of f x is a cycle.-/ lemma is_cycle_cycle_of_iff [fintype Ξ±] (f : perm Ξ±) {x : Ξ±} : is_cycle (cycle_of f x) ↔ (f x β‰  x) := begin split, { intro hx, rw ne.def, rw ← cycle_of_eq_one_iff f, exact equiv.perm.is_cycle.ne_one hx, }, { intro hx, apply equiv.perm.is_cycle_cycle_of, exact hx } end /-! ### `cycle_factors` -/ /-- Given a list `l : list Ξ±` and a permutation `f : perm Ξ±` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux [fintype Ξ±] : Ξ  (l : list Ξ±) (f : perm Ξ±), (βˆ€ {x}, f x β‰  x β†’ x ∈ l) β†’ {l : list (perm Ξ±) // l.prod = f ∧ (βˆ€ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} | [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const, and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *, ext, simp * }⟩ | (x::l) f h := if hx : f x = x then cycle_factors_aux l f (Ξ» y hy, list.mem_of_ne_of_mem (Ξ» h, hy (by rwa h)) (h hy)) else let ⟨m, hm₁, hmβ‚‚, hmβ‚ƒβŸ© := cycle_factors_aux l ((cycle_of f x)⁻¹ * f) (Ξ» y hy, list.mem_of_ne_of_mem (Ξ» h : y = x, by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl }) (h (Ξ» h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy, split_ifs at hy; cc }))) in ⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp }, Ξ» g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (Ξ» hg, hg.symm β–Έ is_cycle_cycle_of _ hx) (hmβ‚‚ g), list.pairwise_cons.2 ⟨λ g hg y, or_iff_not_imp_left.2 (Ξ» hfy, have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy), have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩, have βˆ€ h ∈ m.erase g, disjoint g h, from (list.pairwise_cons.1 ((hgm.pairwise_iff (Ξ» a b (h : disjoint a b), h.symm)).2 hm₃)).1, classical.by_cases id $ Ξ» hgy : g y β‰  y, (disjoint_prod_right _ this y).resolve_right $ have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply], by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁, rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply, inv_apply_self, inv_eq_iff_eq, eq_comm] }), hmβ‚ƒβŸ©βŸ© lemma mem_list_cycles_iff {Ξ± : Type*} [fintype Ξ±] {l : list (perm Ξ±)} (h1 : βˆ€ Οƒ : perm Ξ±, Οƒ ∈ l β†’ Οƒ.is_cycle) (h2 : l.pairwise disjoint) {Οƒ : perm Ξ±} : Οƒ ∈ l ↔ Οƒ.is_cycle ∧ βˆ€ (a : Ξ±) (h4 : Οƒ a β‰  a), Οƒ a = l.prod a := begin suffices : Οƒ.is_cycle β†’ (Οƒ ∈ l ↔ βˆ€ (a : Ξ±) (h4 : Οƒ a β‰  a), Οƒ a = l.prod a), { exact ⟨λ hΟƒ, ⟨h1 Οƒ hΟƒ, (this (h1 Οƒ hΟƒ)).mp hΟƒβŸ©, Ξ» hΟƒ, (this hΟƒ.1).mpr hΟƒ.2⟩ }, intro h3, classical, split, { intros h a ha, exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha) }, { intros h, have hΟƒl : Οƒ.support βŠ† l.prod.support, { intros x hx, rw mem_support at hx, rwa [mem_support, ←h _ hx] }, obtain ⟨a, ha, -⟩ := id h3, rw ←mem_support at ha, obtain βŸ¨Ο„, hΟ„, hΟ„a⟩ := exists_mem_support_of_mem_support_prod (hΟƒl ha), have hΟ„l : βˆ€ (x ∈ Ο„.support), Ο„ x = l.prod x := eq_on_support_mem_disjoint hΟ„ h2, have key : βˆ€ (x ∈ Οƒ.support ∩ Ο„.support), Οƒ x = Ο„ x, { intros x hx, rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hΟ„l x (mem_of_mem_inter_right hx)] }, convert hΟ„, refine h3.eq_on_support_inter_nonempty_congr (h1 _ hΟ„) key _ ha, exact key a (mem_inter_of_mem ha hΟ„a) } end lemma list_cycles_perm_list_cycles {Ξ± : Type*} [fintype Ξ±] {l₁ lβ‚‚ : list (perm Ξ±)} (hβ‚€ : l₁.prod = lβ‚‚.prod) (h₁l₁ : βˆ€ Οƒ : perm Ξ±, Οƒ ∈ l₁ β†’ Οƒ.is_cycle) (h₁lβ‚‚ : βˆ€ Οƒ : perm Ξ±, Οƒ ∈ lβ‚‚ β†’ Οƒ.is_cycle) (hβ‚‚l₁ : l₁.pairwise disjoint) (hβ‚‚lβ‚‚ : lβ‚‚.pairwise disjoint) : l₁ ~ lβ‚‚ := begin classical, refine (list.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ hβ‚‚l₁) (nodup_of_pairwise_disjoint_cycles h₁lβ‚‚ hβ‚‚lβ‚‚)).mpr (Ξ» Οƒ, _), by_cases hΟƒ : Οƒ.is_cycle, { obtain ⟨a, ha⟩ := not_forall.mp (mt ext hΟƒ.ne_one), rw [mem_list_cycles_iff h₁l₁ hβ‚‚l₁, mem_list_cycles_iff h₁lβ‚‚ hβ‚‚lβ‚‚, hβ‚€] }, { exact iff_of_false (mt (h₁l₁ Οƒ) hΟƒ) (mt (h₁lβ‚‚ Οƒ) hΟƒ) } end /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors [fintype Ξ±] [linear_order Ξ±] (f : perm Ξ±) : {l : list (perm Ξ±) // l.prod = f ∧ (βˆ€ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := cycle_factors_aux (univ.sort (≀)) f (Ξ» _ _, (mem_sort _).2 (mem_univ _)) /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`, without a linear order. -/ def trunc_cycle_factors [fintype Ξ±] (f : perm Ξ±) : trunc {l : list (perm Ξ±) // l.prod = f ∧ (βˆ€ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := quotient.rec_on_subsingleton (@univ Ξ± _).1 (Ξ» l h, trunc.mk (cycle_factors_aux l f h)) (show βˆ€ x, f x β‰  x β†’ x ∈ (@univ Ξ± _).1, from Ξ» _ _, mem_univ _) section cycle_factors_finset variables [fintype Ξ±] (f : perm Ξ±) /-- Factors a permutation `f` into a `finset` of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors_finset : finset (perm Ξ±) := (trunc_cycle_factors f).lift (Ξ» (l : {l : list (perm Ξ±) // l.prod = f ∧ (βˆ€ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}), l.val.to_finset) (Ξ» ⟨l, hl⟩ ⟨l', hl'⟩, list.to_finset_eq_of_perm _ _ (list_cycles_perm_list_cycles (hl'.left.symm β–Έ hl.left) hl.right.left (hl'.right.left) hl.right.right hl'.right.right)) lemma cycle_factors_finset_eq_list_to_finset {Οƒ : perm Ξ±} {l : list (perm Ξ±)} (hn : l.nodup) : Οƒ.cycle_factors_finset = l.to_finset ↔ (βˆ€ f : perm Ξ±, f ∈ l β†’ f.is_cycle) ∧ l.pairwise disjoint ∧ l.prod = Οƒ := begin obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := trunc.exists_rep Οƒ.trunc_cycle_factors, have ht : cycle_factors_finset Οƒ = l'.to_finset, { rw [cycle_factors_finset, ←hl, trunc.lift_mk] }, rw ht, split, { intro h, have hn' : l'.nodup := nodup_of_pairwise_disjoint_cycles hc' hd', have hperm : l ~ l' := list.perm_of_nodup_nodup_to_finset_eq hn hn' h.symm, refine ⟨_, _, _⟩, { exact Ξ» _ h, hc' _ (hperm.subset h)}, { rwa list.perm.pairwise_iff disjoint.symmetric hperm }, { rw [←hp', hperm.symm.prod_eq'], refine hd'.imp _, exact Ξ» _ _, disjoint.commute } }, { rintro ⟨hc, hd, hp⟩, refine list.to_finset_eq_of_perm _ _ _, refine list_cycles_perm_list_cycles _ hc' hc hd' hd, rw [hp, hp'] } end lemma cycle_factors_finset_eq_finset {Οƒ : perm Ξ±} {s : finset (perm Ξ±)} : Οƒ.cycle_factors_finset = s ↔ (βˆ€ f : perm Ξ±, f ∈ s β†’ f.is_cycle) ∧ (βˆƒ h : (βˆ€ (a ∈ s) (b ∈ s), a β‰  b β†’ disjoint a b), s.noncomm_prod id (Ξ» a ha b hb, (em (a = b)).by_cases (Ξ» h, h β–Έ commute.refl a) (set.pairwise.mono' (Ξ» _ _, disjoint.commute) h ha hb)) = Οƒ) := begin obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq, rw cycle_factors_finset_eq_list_to_finset hl, simp only [noncomm_prod_to_finset, hl, exists_prop, list.mem_to_finset, and.congr_left_iff, and.congr_right_iff, list.map_id, ne.def], intros, exact ⟨list.pairwise.forall disjoint.symmetric, hl.pairwise_of_forall_ne⟩ end lemma cycle_factors_finset_pairwise_disjoint (p : perm Ξ±) (hp : p ∈ cycle_factors_finset f) (q : perm Ξ±) (hq : q ∈ cycle_factors_finset f) (h : p β‰  q) : disjoint p q := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, -⟩ := cycle_factors_finset_eq_finset.mp this, exact hd p hp q hq h end lemma cycle_factors_finset_mem_commute (p : perm Ξ±) (hp : p ∈ cycle_factors_finset f) (q : perm Ξ±) (hq : q ∈ cycle_factors_finset f) : _root_.commute p q := begin by_cases h : p = q, { exact h β–Έ commute.refl _ }, { exact (cycle_factors_finset_pairwise_disjoint _ _ hp _ hq h).commute } end /-- The product of cycle factors is equal to the original `f : perm Ξ±`. -/ lemma cycle_factors_finset_noncomm_prod (comm : βˆ€ (g ∈ f.cycle_factors_finset) (h ∈ f.cycle_factors_finset), commute (id g) (id h) := cycle_factors_finset_mem_commute f) : f.cycle_factors_finset.noncomm_prod id (comm) = f := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, hp⟩ := cycle_factors_finset_eq_finset.mp this, exact hp end lemma mem_cycle_factors_finset_iff {f p : perm Ξ±} : p ∈ cycle_factors_finset f ↔ p.is_cycle ∧ βˆ€ (a ∈ p.support), p a = f a := begin obtain ⟨l, hl, hl'⟩ := f.cycle_factors_finset.exists_list_nodup_eq, rw ←hl', rw [eq_comm, cycle_factors_finset_eq_list_to_finset hl] at hl', simpa [list.mem_to_finset, ne.def, ←hl'.right.right] using mem_list_cycles_iff hl'.left hl'.right.left end lemma cycle_of_mem_cycle_factors_finset_iff {f : perm Ξ±} {x : Ξ±} : cycle_of f x ∈ cycle_factors_finset f ↔ x ∈ f.support := begin rw mem_cycle_factors_finset_iff, split, { rintro ⟨hc, h⟩, contrapose! hc, rw [not_mem_support, ←cycle_of_eq_one_iff] at hc, simp [hc] }, { intros hx, refine ⟨is_cycle_cycle_of _ (mem_support.mp hx), _⟩, intros y hy, rw mem_support at hy, rw cycle_of_apply, split_ifs with H, { refl }, { rw cycle_of_apply_of_not_same_cycle H at hy, contradiction } } end lemma mem_cycle_factors_finset_support_le {p f : perm Ξ±} (h : p ∈ cycle_factors_finset f) : p.support ≀ f.support := begin rw mem_cycle_factors_finset_iff at h, intros x hx, rwa [mem_support, ←h.right x hx, ←mem_support] end lemma cycle_factors_finset_eq_empty_iff {f : perm Ξ±} : cycle_factors_finset f = βˆ… ↔ f = 1 := by simpa [cycle_factors_finset_eq_finset] using eq_comm @[simp] lemma cycle_factors_finset_one : cycle_factors_finset (1 : perm Ξ±) = βˆ… := by simp [cycle_factors_finset_eq_empty_iff] @[simp] lemma cycle_factors_finset_eq_singleton_self_iff {f : perm Ξ±} : f.cycle_factors_finset = {f} ↔ f.is_cycle := by simp [cycle_factors_finset_eq_finset] lemma is_cycle.cycle_factors_finset_eq_singleton {f : perm Ξ±} (hf : is_cycle f) : f.cycle_factors_finset = {f} := cycle_factors_finset_eq_singleton_self_iff.mpr hf lemma cycle_factors_finset_eq_singleton_iff {f g : perm Ξ±} : f.cycle_factors_finset = {g} ↔ f.is_cycle ∧ f = g := begin suffices : f = g β†’ (g.is_cycle ↔ f.is_cycle), { simpa [cycle_factors_finset_eq_finset, eq_comm] }, rintro rfl, exact iff.rfl end /-- Two permutations `f g : perm Ξ±` have the same cycle factors iff they are the same. -/ lemma cycle_factors_finset_injective : function.injective (@cycle_factors_finset Ξ± _ _) := begin intros f g h, rw ←cycle_factors_finset_noncomm_prod f, simpa [h] using cycle_factors_finset_noncomm_prod g end lemma disjoint.disjoint_cycle_factors_finset {f g : perm Ξ±} (h : disjoint f g) : _root_.disjoint (cycle_factors_finset f) (cycle_factors_finset g) := begin rw disjoint_iff_disjoint_support at h, intros x hx, simp only [mem_cycle_factors_finset_iff, inf_eq_inter, mem_inter, mem_support] at hx, obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx, refine h (_ : a ∈ f.support ∩ g.support), simp [ha, ←hf a ha, ←hg a ha] end lemma disjoint.cycle_factors_finset_mul_eq_union {f g : perm Ξ±} (h : disjoint f g) : cycle_factors_finset (f * g) = cycle_factors_finset f βˆͺ cycle_factors_finset g := begin rw cycle_factors_finset_eq_finset, split, { simp only [mem_cycle_factors_finset_iff, mem_union], rintro _ (⟨h, -⟩ | ⟨h, -⟩); exact h }, { refine ⟨_, _⟩, { simp_rw mem_union, rintros x (hx | hx) y (hy | hy) hxy, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy }, { exact h.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact h.symm.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy } }, { rw noncomm_prod_union_of_disjoint h.disjoint_cycle_factors_finset, rw [cycle_factors_finset_noncomm_prod, cycle_factors_finset_noncomm_prod] } } end lemma disjoint_mul_inv_of_mem_cycle_factors_finset {f g : perm Ξ±} (h : f ∈ cycle_factors_finset g) : disjoint (g * f⁻¹) f := begin rw mem_cycle_factors_finset_iff at h, intro x, by_cases hx : f x = x, { exact or.inr hx }, { refine or.inl _, rw [mul_apply, ←h.right, apply_inv_self], rwa [←support_inv, apply_mem_support, support_inv, mem_support] } end /-- If c is a cycle, a ∈ c.support and c is a cycle of f, then `c = f.cycle_of a` -/ lemma cycle_is_cycle_of {f c : equiv.perm Ξ±} {a : Ξ±} (ha : a ∈ c.support) (hc : c ∈ f.cycle_factors_finset) : c = f.cycle_of a := begin suffices : f.cycle_of a = c.cycle_of a, { rw this, apply symm, exact equiv.perm.is_cycle.cycle_of_eq ((equiv.perm.mem_cycle_factors_finset_iff.mp hc).left) (equiv.perm.mem_support.mp ha), }, let hfc := (equiv.perm.disjoint_mul_inv_of_mem_cycle_factors_finset hc).symm, let hfc2 := (perm.disjoint.commute hfc), rw ← equiv.perm.cycle_of_mul_of_apply_right_eq_self hfc2, simp only [hfc2.eq, inv_mul_cancel_right], -- a est dans le support de c, donc pas dans celui de g c⁻¹ exact equiv.perm.not_mem_support.mp (finset.disjoint_left.mp (equiv.perm.disjoint.disjoint_support hfc) ha), end end cycle_factors_finset @[elab_as_eliminator] lemma cycle_induction_on [fintype Ξ²] (P : perm Ξ² β†’ Prop) (Οƒ : perm Ξ²) (base_one : P 1) (base_cycles : βˆ€ Οƒ : perm Ξ², Οƒ.is_cycle β†’ P Οƒ) (induction_disjoint : βˆ€ Οƒ Ο„ : perm Ξ², disjoint Οƒ Ο„ β†’ is_cycle Οƒ β†’ P Οƒ β†’ P Ο„ β†’ P (Οƒ * Ο„)) : P Οƒ := begin suffices : βˆ€ l : list (perm Ξ²), (βˆ€ Ο„ : perm Ξ², Ο„ ∈ l β†’ Ο„.is_cycle) β†’ l.pairwise disjoint β†’ P l.prod, { classical, let x := Οƒ.trunc_cycle_factors.out, exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) }, intro l, induction l with Οƒ l ih, { exact Ξ» _ _, base_one }, { intros h1 h2, rw list.prod_cons, exact induction_disjoint Οƒ l.prod (disjoint_prod_right _ (list.pairwise_cons.mp h2).1) (h1 _ (list.mem_cons_self _ _)) (base_cycles Οƒ (h1 Οƒ (l.mem_cons_self Οƒ))) (ih (Ξ» Ο„ hΟ„, h1 Ο„ (list.mem_cons_of_mem Οƒ hΟ„)) h2.of_cons) } end lemma cycle_factors_finset_mul_inv_mem_eq_sdiff [fintype Ξ±] {f g : perm Ξ±} (h : f ∈ cycle_factors_finset g) : cycle_factors_finset (g * f⁻¹) = (cycle_factors_finset g) \ {f} := begin revert f, apply cycle_induction_on _ g, { simp }, { intros Οƒ hΟƒ f hf, simp only [cycle_factors_finset_eq_singleton_self_iff.mpr hΟƒ, mem_singleton] at hf ⊒, simp [hf] }, { intros Οƒ Ο„ hd hc hΟƒ hΟ„ f, simp_rw [hd.cycle_factors_finset_mul_eq_union, mem_union], -- if only `wlog` could work here... rintro (hf | hf), { rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hΟƒ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd.symm x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact Ξ» H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem hf H) } }, { rw [union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hΟ„ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact Ξ» H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem H hf) } } } end lemma same_cycle.nat_of_mem_support [fintype Ξ±] (f : perm Ξ±) {x y : Ξ±} (h : same_cycle f x y) (hx : x ∈ f.support) : βˆƒ (i : β„•) (hi' : i < (f.cycle_of x).support.card), (f ^ i) x = y := begin revert f, intro f, apply cycle_induction_on _ f, { simp }, { intros g hg H hx, rw mem_support at hx, rw [hg.cycle_of_eq hx, ←order_of_is_cycle hg], exact H.nat' }, { rintros g h hd hg IH IH' ⟨m, rfl⟩ hx, cases (disjoint_iff_eq_or_eq.mp hd) x with hgx hhx, { have hpow : βˆ€ (k : β„€), ((g * h) ^ k) x = (h ^ k) x, { intro k, suffices : (g ^ k) x = x, { simpa [hd.commute.eq, hd.commute.symm.mul_zpow] }, rw zpow_apply_eq_self_of_apply_eq_self, simpa using hgx }, obtain ⟨k, hk, hk'⟩ := IH' _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hgx, rwa [hd.cycle_of_mul_distrib, hgx, one_mul] }, { simpa [←zpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { rw [mem_support, hd.commute.eq] at hx, simpa [hgx] using hx } }, { have hpow : βˆ€ (k : β„€), ((g * h) ^ k) x = (g ^ k) x, { intro k, suffices : (h ^ k) x = x, { simpa [hd.commute.mul_zpow] }, rw zpow_apply_eq_self_of_apply_eq_self, simpa using hhx }, obtain ⟨k, hk, hk'⟩ := IH _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hhx, rwa [hd.cycle_of_mul_distrib, hhx, mul_one] }, { simpa [←zpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { simpa [hhx] using hx } } } end lemma same_cycle.nat [fintype Ξ±] (f : perm Ξ±) {x y : Ξ±} (h : same_cycle f x y) : βˆƒ (i : β„•) (hi : 0 < i) (hi' : i ≀ (f.cycle_of x).support.card + 1), (f ^ i) x = y := begin by_cases hx : x ∈ f.support, { obtain ⟨k, hk, hk'⟩ := same_cycle.nat_of_mem_support f h hx, cases k, { refine ⟨(f.cycle_of x).support.card, _, self_le_add_right _ _, _⟩, { refine zero_lt_one.trans (one_lt_card_support_of_ne_one _), simpa using hx }, { simp only [perm.coe_one, id.def, pow_zero] at hk', subst hk', rw [←order_of_is_cycle (is_cycle_cycle_of _ (mem_support.mp hx)), ←cycle_of_pow_apply_self, pow_order_of_eq_one, one_apply] } }, { exact ⟨k + 1, by simp, nat.le_succ_of_le hk.le, hk'⟩ } }, { refine ⟨1, zero_lt_one, by simp, _⟩, obtain ⟨k, rfl⟩ := h, rw [not_mem_support] at hx, rw [pow_apply_eq_self_of_apply_eq_self hx, zpow_apply_eq_self_of_apply_eq_self hx] } end section generation variables [fintype Ξ±] [fintype Ξ²] open subgroup lemma closure_is_cycle : closure {Οƒ : perm Ξ² | is_cycle Οƒ} = ⊀ := begin classical, exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (Ξ» _, is_swap.is_cycle))), end lemma closure_cycle_adjacent_swap {Οƒ : perm Ξ±} (h1 : is_cycle Οƒ) (h2 : Οƒ.support = ⊀) (x : Ξ±) : closure ({Οƒ, swap x (Οƒ x)} : set (perm Ξ±)) = ⊀ := begin let H := closure ({Οƒ, swap x (Οƒ x)} : set (perm Ξ±)), have h3 : Οƒ ∈ H := subset_closure (set.mem_insert Οƒ _), have h4 : swap x (Οƒ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)), have step1 : βˆ€ (n : β„•), swap ((Οƒ ^ n) x) ((Οƒ^(n+1)) x) ∈ H, { intro n, induction n with n ih, { exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) }, { convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3), rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } }, have step2 : βˆ€ (n : β„•), swap x ((Οƒ ^ n) x) ∈ H, { intro n, induction n with n ih, { convert H.one_mem, exact swap_self x }, { by_cases h5 : x = (Οƒ ^ n) x, { rw [pow_succ, mul_apply, ←h5], exact h4 }, by_cases h6 : x = (Οƒ^(n+1)) x, { rw [←h6, swap_self], exact H.one_mem }, rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6], exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } }, have step3 : βˆ€ (y : Ξ±), swap x y ∈ H, { intro y, have hx : x ∈ (⊀ : finset Ξ±) := finset.mem_univ x, rw [←h2, mem_support] at hx, have hy : y ∈ (⊀ : finset Ξ±) := finset.mem_univ y, rw [←h2, mem_support] at hy, cases is_cycle.exists_pow_eq h1 hx hy with n hn, rw ← hn, exact step2 n }, have step4 : βˆ€ (y z : Ξ±), swap y z ∈ H, { intros y z, by_cases h5 : z = x, { rw [h5, swap_comm], exact step3 y }, by_cases h6 : z = y, { rw [h6, swap_self], exact H.one_mem }, rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x], exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) }, rw [eq_top_iff, ←closure_is_swap, closure_le], rintros Ο„ ⟨y, z, h5, h6⟩, rw h6, exact step4 y z, end lemma closure_cycle_coprime_swap {n : β„•} {Οƒ : perm Ξ±} (h0 : nat.coprime n (fintype.card Ξ±)) (h1 : is_cycle Οƒ) (h2 : Οƒ.support = finset.univ) (x : Ξ±) : closure ({Οƒ, swap x ((Οƒ ^ n) x)} : set (perm Ξ±)) = ⊀ := begin rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0, cases exists_pow_eq_self_of_coprime h0 with m hm, have h2' : (Οƒ ^ n).support = ⊀ := eq.trans (support_pow_coprime h0) h2, have h1' : is_cycle ((Οƒ ^ n) ^ (m : β„€)) := by rwa ← hm at h1, replace h1' : is_cycle (Οƒ ^ n) := is_cycle_of_is_cycle_pow h1' (le_trans (support_pow_le Οƒ n) (ge_of_eq (congr_arg support hm))), rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset], exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert Οƒ _)) n, set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩, end lemma closure_prime_cycle_swap {Οƒ Ο„ : perm Ξ±} (h0 : (fintype.card Ξ±).prime) (h1 : is_cycle Οƒ) (h2 : Οƒ.support = finset.univ) (h3 : is_swap Ο„) : closure ({Οƒ, Ο„} : set (perm Ξ±)) = ⊀ := begin obtain ⟨x, y, h4, h5⟩ := h3, obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp ((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x))) (mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))), rw [h5, ←hi], refine closure_cycle_coprime_swap (nat.coprime.symm (h0.coprime_iff_not_dvd.mpr (Ξ» h, h4 _))) h1 h2 x, cases h with m hm, rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1, pow_order_of_eq_one, one_pow, one_apply] at hi, end end generation section variables [fintype Ξ±] {Οƒ Ο„ : perm Ξ±} noncomputable theory lemma is_conj_of_support_equiv (f : {x // x ∈ (Οƒ.support : set Ξ±)} ≃ {x // x ∈ (Ο„.support : set Ξ±)}) (hf : βˆ€ (x : Ξ±) (hx : x ∈ (Οƒ.support : set Ξ±)), (f βŸ¨Οƒ x, apply_mem_support.2 hx⟩ : Ξ±) = Ο„ ↑(f ⟨x,hx⟩)) : is_conj Οƒ Ο„ := begin refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩, rw mul_inv_eq_iff_eq_mul, ext, simp only [perm.mul_apply], by_cases hx : x ∈ Οƒ.support, { rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem], { exact hf x (finset.mem_coe.2 hx) } }, { rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)), not_not.1 ((not_congr mem_support).mp hx)] } end theorem is_cycle.is_conj (hΟƒ : is_cycle Οƒ) (hΟ„ : is_cycle Ο„) (h : Οƒ.support.card = Ο„.support.card) : is_conj Οƒ Ο„ := begin refine is_conj_of_support_equiv (hΟƒ.zpowers_equiv_support.symm.trans ((zpowers_equiv_zpowers begin rw [order_of_is_cycle hΟƒ, h, order_of_is_cycle hΟ„], end).trans hΟ„.zpowers_equiv_support)) _, intros x hx, simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply], obtain ⟨n, rfl⟩ := hΟƒ.exists_pow_eq (classical.some_spec hΟƒ).1 (mem_support.1 hx), apply eq.trans _ (congr rfl (congr rfl (congr rfl (congr rfl (hΟƒ.zpowers_equiv_support_symm_apply n).symm)))), apply (congr rfl (congr rfl (congr rfl (hΟƒ.zpowers_equiv_support_symm_apply (n + 1))))).trans _, simp only [ne.def, is_cycle.zpowers_equiv_support_apply, subtype.coe_mk, zpowers_equiv_zpowers_apply], rw [pow_succ, perm.mul_apply], end theorem is_cycle.is_conj_iff (hΟƒ : is_cycle Οƒ) (hΟ„ : is_cycle Ο„) : is_conj Οƒ Ο„ ↔ Οƒ.support.card = Ο„.support.card := ⟨begin intro h, obtain βŸ¨Ο€, rfl⟩ := is_conj_iff.1 h, apply finset.card_congr (Ξ» a ha, Ο€ a) (Ξ» _ ha, _) (Ξ» _ _ _ _ ab, Ο€.injective ab) (Ξ» b hb, _), { simp [mem_support.1 ha] }, { refine βŸ¨Ο€β»ΒΉ b, ⟨_, Ο€.apply_inv_self b⟩⟩, contrapose! hb, rw [mem_support, not_not] at hb, rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] } end, hΟƒ.is_conj hΟ„βŸ© @[simp] lemma support_conj : (Οƒ * Ο„ * σ⁻¹).support = Ο„.support.map Οƒ.to_embedding := begin ext, simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply], refl, end lemma card_support_conj : (Οƒ * Ο„ * σ⁻¹).support.card = Ο„.support.card := by simp end theorem disjoint.is_conj_mul {Ξ± : Type*} [fintype Ξ±] {Οƒ Ο„ Ο€ ρ : perm Ξ±} (hc1 : is_conj Οƒ Ο€) (hc2 : is_conj Ο„ ρ) (hd1 : disjoint Οƒ Ο„) (hd2 : disjoint Ο€ ρ) : is_conj (Οƒ * Ο„) (Ο€ * ρ) := begin classical, obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1, obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2, have hd1' := coe_inj.2 hd1.support_mul, have hd2' := coe_inj.2 hd2.support_mul, rw [coe_union] at *, have hd1'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd1), have hd2'' := disjoint_coe.2 (disjoint_iff_disjoint_support.1 hd2), refine is_conj_of_support_equiv _ _, { refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans ((equiv.sum_congr (subtype_equiv f (Ξ» a, _)) (subtype_equiv g (Ξ» a, _))).trans ((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm); { simp only [set.mem_image, to_embedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq] } }, { intros x hx, simp only [trans_apply, symm_trans_apply, set.of_eq_apply, set.of_eq_symm_apply, equiv.sum_congr_apply], rw [hd1', set.mem_union] at hx, cases hx with hxΟƒ hxΟ„, { rw [mem_coe, mem_support] at hxΟƒ, rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app, set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (f x)).resolve_left _, { rw [mul_apply, mul_apply] at h, rw [h, inv_apply_self, (hd1 x).resolve_left hxΟƒ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 x).resolve_left hxΟƒ, mem_coe, apply_mem_support, mem_support] } }, { rw [mem_coe, ← apply_mem_support, mem_support] at hxΟ„, rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app, set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (g (Ο„ x))).resolve_right _, { rw [mul_apply, mul_apply] at h, rw [inv_apply_self, h, (hd1 (Ο„ x)).resolve_right hxΟ„] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 (Ο„ x)).resolve_right hxΟ„, mem_coe, mem_support] } } } end section fixed_points /-! ### Fixed points -/ lemma fixed_point_card_lt_of_ne_one [fintype Ξ±] {Οƒ : perm Ξ±} (h : Οƒ β‰  1) : (filter (Ξ» x, Οƒ x = x) univ).card < fintype.card Ξ± - 1 := begin rw [lt_tsub_iff_left, ← lt_tsub_iff_right, ← finset.card_compl, finset.compl_filter], exact one_lt_card_support_of_ne_one h end end fixed_points end equiv.perm
ba737aac35d9b6b11bec6a362b72102a781b93a9
f1a12d4db0f46eee317d703e3336d33950a2fe7e
/lia/cooper/correctness.lean
3726b8daea95eab75aa46b6c24ae1e7e1e5e727f
[ "Apache-2.0" ]
permissive
avigad/qelim
bce89b79c717b7649860d41a41a37e37c982624f
b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60
refs/heads/master
1,584,548,938,232
1,526,773,708,000
1,526,773,708,000
134,967,693
2
0
null
null
null
null
UTF-8
Lean
false
false
46,076
lean
import .qe open lia lemma I_atom_le (i : int) (ks zs : list int) : I (A' (atom.le i ks)) zs ↔ (i ≀ list.dot_prod ks zs) := iff.refl _ lemma I_atom_dvd (d i ks zs) : I (A' (atom.dvd d i ks)) zs ↔ (has_dvd.dvd d (i + list.dot_prod ks zs)) := iff.refl _ lemma I_atom_ndvd (d i ks zs) : I (A' (atom.ndvd d i ks)) zs ↔ Β¬ (has_dvd.dvd d (i + list.dot_prod ks zs)) := iff.refl _ lemma I_atom_ndvd' (d i : int) (ks zs : list int) : I (A' (atom.ndvd d i ks)) zs ↔ Β¬ I (A' (atom.dvd d i ks)) zs := begin unfold I, unfold interp, unfold atom_type.val, unfold val end meta def atom_dep0_split := `[cases ks with k' ks', apply or.inl, apply not_not_intro rfl, cases (classical.em (k' = 0)) with h h, subst h, apply or.inl, apply not_not_intro rfl, apply or.inr, existsi k', existsi ks', apply and.intro; simp, apply h] lemma le_dep0_split (i ks) : (Β¬ atom_type.dep0 int (atom.le i ks)) ∨ βˆƒ k, βˆƒ ks', (k β‰  0 ∧ ks = (k::ks')) := by atom_dep0_split lemma dvd_dep0_split (d i ks) : (Β¬ atom_type.dep0 int (atom.dvd d i ks)) ∨ βˆƒ k, βˆƒ ks', (k β‰  0 ∧ ks = (k::ks')) := by atom_dep0_split lemma ndvd_dep0_split (d i ks) : (Β¬ atom_type.dep0 int (atom.ndvd d i ks)) ∨ βˆƒ k, βˆƒ ks', (k β‰  0 ∧ ks = (k::ks')) := by atom_dep0_split lemma subst_prsv (i ks xs) : βˆ€ p, nqfree p β†’ (I (subst i ks p) xs ↔ I p ((i + list.dot_prod ks xs)::xs)) | ⊀' _ := by refl | βŠ₯' _ := by refl | (A' (atom.le i ks')) _ := begin unfold subst, unfold map_fm, cases ks' with k' ks'; unfold asubst, repeat {rewrite I_atom_le}, simp, simp, rewrite list.comp_add_dot_prod, rewrite mul_add, simp, end | (A' (atom.ndvd d i ks')) _ := begin unfold subst, unfold map_fm, cases ks' with k' ks'; unfold asubst, repeat {rewrite I_atom_ndvd}, simp, rewrite list.comp_add_dot_prod, simp, rewrite mul_add, simp end | (A' (atom.dvd d i ks')) _ := begin unfold subst, unfold map_fm, cases ks' with k' ks'; unfold asubst, repeat {rewrite I_atom_dvd}, simp, rewrite list.comp_add_dot_prod, simp, rewrite mul_add, simp end | (p ∧' q) hf := begin cases hf with hfp hfq, unfold subst, unfold map_fm, repeat {rewrite exp_I_and}, let ihp := subst_prsv p hfp, unfold subst at ihp, rewrite ihp, let ihq := subst_prsv q hfq, unfold subst at ihq, rewrite ihq end | (p ∨' q) hf := begin cases hf with hfp hfq, unfold subst, unfold map_fm, repeat {rewrite exp_I_or}, let ihp := subst_prsv p hfp, unfold subst at ihp, rewrite ihp, let ihq := subst_prsv q hfq, unfold subst at ihq, rewrite ihq end | (Β¬' p) hf := by cases hf | (βˆƒ' p) hf := by cases hf meta def hco_not_dep0_tac := `[ cases ks with k' ks', refl, cases (classical.em (k' = 0)) with hz hnz, subst hz, refl, exfalso, apply hnd, apply hnz] lemma hco_not_dep0 (m) : βˆ€ a, (Β¬ atom_type.dep0 int a) β†’ hd_coeff_one m a = a := begin intros a hnd, cases a with i ks d i ks d i ks, repeat {cases ks with k' ks', refl, cases (classical.em (k' = 0)) with hz hnz, subst hz, refl, exfalso, apply hnd, apply hnz} end lemma hco_le_nonzero (m i k : int) (ks) : k β‰  0 β†’ hd_coeff_one m (atom.le i (k::ks)) = (let m' := has_div.div m (abs k) in atom.le (m' * i) (int.sign k :: list.map (Ξ» x, m' * x) ks)) := begin intro hne, cases k with n n, cases n, trivial, trivial, trivial, end lemma hco_dvd_nonzero (m d i k ks) : k β‰  0 β†’ hd_coeff_one m (atom.dvd d i (k::ks)) = (let m' := has_div.div m k in atom.dvd (m' * d) (m' * i) (1 :: list.map (Ξ» x, m' * x) ks)) := begin intro hne, cases k with n n, cases n, trivial, trivial, trivial, end lemma hco_ndvd_nonzero (m d i k ks) : k β‰  0 β†’ hd_coeff_one m (atom.ndvd d i (k::ks)) = (let m' := has_div.div m k in atom.ndvd (m' * d) (m' * i) (1 :: list.map (Ξ» x, m' * x) ks)) := begin intro hne, cases k with n n, cases n, trivial, trivial, trivial, end lemma normal_hco_atom (z : int) (hne : z β‰  0) : βˆ€ (a : atom) (ha1 : atom_type.normal β„€ a) (ha2 : has_dvd.dvd (hd_coeff a) z ∨ hd_coeff a = 0), atom_type.normal β„€ (hd_coeff_one z a) | (atom.le i ks) ha1 ha2 := begin cases ks with k ks, trivial, cases k with n, cases n; trivial, trivial end | (atom.dvd d i ks) ha1 ha2 := begin cases ks with k ks, trivial, cases (classical.em (k = 0)) with hk hk, subst hk, trivial, cases ha2 with ha2 ha2, rewrite hco_dvd_nonzero, simp, apply int.mul_nonzero, unfold hd_coeff at ha2, unfold list.head_dft at ha2, apply int.div_nonzero, apply hne, apply ha2, apply ha1, apply hk, exfalso, apply hk ha2 end | (atom.ndvd d i ks) ha1 ha2 := begin cases ks with k ks, trivial, cases (classical.em (k = 0)) with hk hk, subst hk, trivial, cases ha2 with ha2 ha2, rewrite hco_ndvd_nonzero, simp, apply int.mul_nonzero, unfold hd_coeff at ha2, unfold list.head_dft at ha2, apply int.div_nonzero, apply hne, apply ha2, apply ha1, apply hk, exfalso, apply hk ha2 end meta def fnormal_map_hco_of_fnormal_tac := `[unfold map_fm, unfold fnormal, cases hn with hnp hnq, unfold atoms at hnz, rewrite list.forall_mem_union at hnz, cases hnz with hnzp hnzq, apply and.intro; apply fnormal_map_hco_of_fnormal; assumption] lemma fnormal_map_hco_of_fnormal (z : int) (hz : z β‰  0) : βˆ€ (p : fm atom), (fnormal β„€ p) β†’ (βˆ€ a ∈ atoms p, has_dvd.dvd (hd_coeff a) z ∨ hd_coeff a = 0) β†’ fnormal β„€ (map_fm (hd_coeff_one z) p) | ⊀' hn hnz := by unfold map_fm | βŠ₯' hn hnz := by unfold map_fm | (A' a) hn hnz := begin unfold map_fm, unfold fnormal, unfold fnormal at hn, apply normal_hco_atom z hz _ hn, apply hnz, unfold atoms, simp, end | (p ∧' q) hn hnz := by fnormal_map_hco_of_fnormal_tac | (p ∨' q) hn hnz := by fnormal_map_hco_of_fnormal_tac | (Β¬' p) hp hpz := begin unfold map_fm, unfold fnormal, apply fnormal_map_hco_of_fnormal p hp hpz, end | (βˆƒ' p) hn hnz := by unfold map_fm lemma hd_coeffs_one_normal_prsv : preserves hd_coeffs_one (fnormal int) := begin intros p hp, unfold hd_coeffs_one, unfold fnormal, have hne : int.lcms (list.map hd_coeff (atoms_dep0 β„€ p)) β‰  0, apply int.nonzero_of_pos, apply int.lcms_pos, apply @list.forall_mem_map_of_forall_mem _ _ (atom_type.dep0 int) (Ξ» (z : int), z β‰  0) hd_coeff (atoms_dep0 int p), unfold atoms_dep0, intros a ha, apply list.of_mem_filter ha, intros a ha, apply ha, apply and.intro, intro hc, apply hne hc, apply fnormal_map_hco_of_fnormal _ hne _ hp, intros a ha, apply or_of_not_imp_right, intro haz, apply int.dvd_lcms, rewrite list.mem_map, existsi a, apply and.intro, unfold atoms_dep0, apply list.mem_filter_of_mem, apply ha, apply haz, refl end lemma normal_asubst_of_normal : βˆ€ a : atom, atom_type.normal int a β†’ βˆ€ i ks, atom_type.normal int (asubst i ks a) := begin intro a, cases a with i ks d i ks d i ks; intros h i' ks'; cases ks with k ks; trivial end lemma fnormal_subst_of_fnormal (i ks) : βˆ€ p, fnormal int p β†’ fnormal int (subst i ks p) | ⊀' h := by unfold subst | βŠ₯' h := by unfold subst | (A' a) h := begin unfold subst, unfold map_fm, unfold fnormal, apply normal_asubst_of_normal _ h end | (p ∧' q) h := begin cases h with hp hq, apply and.intro; apply fnormal_subst_of_fnormal; assumption end | (p ∨' q) h := begin cases h with hp hq, apply and.intro; apply fnormal_subst_of_fnormal; assumption end | (Β¬' p) h := fnormal_subst_of_fnormal p h | (βˆƒ' p) h := by unfold subst meta def nqfree_hco_of_nqfree_tac := `[unfold map_fm, cases h with hp hq, apply and.intro; apply nqfree_hco_of_nqfree; assumption] lemma nqfree_hco_of_nqfree (z) : βˆ€ (p : fm atom), nqfree p β†’ nqfree (map_fm (hd_coeff_one z) p) | ⊀' h := by unfold map_fm | βŠ₯' h := by unfold map_fm | (A' _) h := by unfold map_fm | (p ∧' q) h := by nqfree_hco_of_nqfree_tac | (p ∨' q) h := by nqfree_hco_of_nqfree_tac | (Β¬' _) h := by cases h | (βˆƒ' _) h := by unfold map_fm lemma nqfree_hcso_of_nqfree : βˆ€ (p : fm atom), nqfree p β†’ nqfree (hd_coeffs_one p) := begin intros p h, unfold hd_coeffs_one, apply and.intro, trivial, apply nqfree_hco_of_nqfree _ _ h end lemma qfree_subst_of_qfree (i ks) : βˆ€ p, qfree p β†’ qfree (subst i ks p) | ⊀' h := by unfold subst | βŠ₯' h := by unfold subst | (A' a) h := by unfold subst | (p ∧' q) h := begin cases h with hp hq, apply and.intro, apply qfree_subst_of_qfree p hp, apply qfree_subst_of_qfree q hq end | (p ∨' q) h := begin cases h with hp hq, apply and.intro, apply qfree_subst_of_qfree p hp, apply qfree_subst_of_qfree q hq end | (Β¬' p) h := qfree_subst_of_qfree p h | (βˆƒ' p) h := by unfold subst lemma pred_inf_minus_of_pred (P) (hup : prop_up_closed P) (hdn : down_closed P) : βˆ€ p, P p β†’ P (inf_minus p) | ⊀' h := h | βŠ₯' h := h | (A' a) h := begin cases a with k ks, cases ks with k' ks, apply h, unfold inf_minus, apply cases_ite; intro h1, apply hup ⊀', apply cases_ite; intro h2, apply hup βŠ₯', rewrite int.eq_zero_of_nonpos_of_nonzero k' h1 h2 at h, apply h, apply h, apply h end | (p ∧' q) h := begin unfold inf_minus, apply pred_and_o _ hup; apply pred_inf_minus_of_pred; apply hdn _ _ _ h; constructor end | (p ∨' q) h := begin unfold inf_minus, apply pred_or_o _ hup; apply pred_inf_minus_of_pred; apply hdn _ _ _ h; constructor end | (Β¬' p) h := h | (βˆƒ' p) h := h lemma qfree_inf_minus_of_qfree : βˆ€ p, qfree p β†’ qfree (inf_minus p) := pred_inf_minus_of_pred _ prop_up_closed_qfree down_closed_qfree lemma fnormal_inf_minus_of_fnormal : βˆ€ p, fnormal int p β†’ fnormal int (inf_minus p) := pred_inf_minus_of_pred _ prop_up_closed_fnormal down_closed_fnormal lemma qe_cooper_one_normal_prsv : preserves qe_cooper_one (fnormal int) := begin unfold preserves, intros p hp, unfold qe_cooper_one, simp, apply fnormal_or_o, apply fnormal_disj, intros z hz, apply fnormal_subst_of_fnormal, apply fnormal_inf_minus_of_fnormal, apply hp, apply fnormal_disj, intros zzs hzzs, apply fnormal_disj, intros z hz, apply fnormal_subst_of_fnormal, apply hp end lemma sqe_cooper_normal_prsv : preserves sqe_cooper (fnormal int) := begin intros p hp, unfold sqe_cooper, apply qe_cooper_one_normal_prsv, apply hd_coeffs_one_normal_prsv, apply hp end lemma qfree_qco_of_nqfree : qfree_res_of_nqfree_arg qe_cooper_one := begin unfold qfree_res_of_nqfree_arg, intros p hp, unfold qe_cooper_one, simp, apply qfree_or_o; apply qfree_disj, intros z hz, apply qfree_subst_of_qfree, apply qfree_inf_minus_of_qfree, apply qfree_of_nqfree _ hp, intros zzs hzzs, apply qfree_disj, intros z hz, apply qfree_subst_of_qfree, apply qfree_of_nqfree _ hp end lemma qfree_sqe_cooper_of_nqfree : qfree_res_of_nqfree_arg sqe_cooper := begin unfold qfree_res_of_nqfree_arg, unfold sqe_cooper, intros p h, apply qfree_qco_of_nqfree, apply nqfree_hcso_of_nqfree, apply h end def unified (p : fm atom) : Prop := βˆ€ a ∈ atoms p, hd_coeff a = -1 ∨ hd_coeff a = 0 ∨ hd_coeff a = 1 lemma unfied_hd_coeff : βˆ€ (a : atom) (z : int), hd_coeff (hd_coeff_one z a) = -1 ∨ hd_coeff (hd_coeff_one z a) = 0 ∨ hd_coeff (hd_coeff_one z a) = 1 := begin intros a z, cases a with i ks d i ks d i ks; cases ks with k ks, apply or.inr (or.inl rfl), cases (classical.em (k = 0)) with hk hk, subst hk, apply or.inr (or.inl rfl), rewrite hco_le_nonzero _ _ _ _ hk, simp, unfold hd_coeff, unfold list.head_dft, apply int.sign_split, apply or.inr (or.inl rfl), cases (classical.em (k = 0)) with hk hk, subst hk, apply or.inr (or.inl rfl), rewrite hco_dvd_nonzero _ _ _ _ _ hk, simp, unfold hd_coeff, unfold list.head_dft, simp, apply or.inr (or.inl rfl), cases (classical.em (k = 0)) with hk hk, subst hk, apply or.inr (or.inl rfl), rewrite hco_ndvd_nonzero _ _ _ _ _ hk, simp, unfold hd_coeff, unfold list.head_dft, simp end lemma ex_iff_inf_or_bnd_aux (P : int β†’ Prop) (hP : βˆ€ (y : β„€), (P y β†’ βˆƒ (x : β„€), x < y ∧ P x)) (y : int) : βˆ€ (m n : nat), n ≀ m β†’ P (y + int.of_nat n) β†’ βˆƒ (x : int), (x < y ∧ P x) | 0 n hle hn := begin cases n with n, have he : int.of_nat 0 = 0, refl, rewrite he at hn, rewrite add_zero at hn, apply hP, apply hn, cases hle end | (m+1) n hle hn := begin cases (lt_or_eq_of_le hle) with hlt heq, apply ex_iff_inf_or_bnd_aux m n, apply nat.le_of_lt_succ, apply hlt, apply hn, subst heq, clear hle, cases (hP _ hn) with w hw, cases hw with hw1 hw2, cases (classical.em (w < y)) with hw3 hw3, existsi w, apply and.intro; assumption, rewrite not_lt at hw3, cases (int.exists_nat_diff y w (m+1) hw3 hw1) with k hk, cases hk with hk1 hk2, apply ex_iff_inf_or_bnd_aux m k, apply nat.le_of_lt_succ, apply hk1, rewrite hk2 at hw2, apply hw2, end lemma ex_iff_inf_or_bnd (P : int β†’ Prop) : (βˆƒ z, P z) ↔ ((βˆ€ y, βˆƒ x, x < y ∧ P x) ∨ (βˆƒ y, (P y ∧ βˆ€ x, x < y β†’ Β¬ P x))) := begin apply iff.intro; intro h1, cases (classical.em ( βˆƒ (y : β„€), P y ∧ βˆ€ (x : β„€), x < y β†’ Β¬P x)) with h2 h2, apply or.inr h2, rewrite not_exists at h2, apply or.inl, intro y, cases h1 with z hz, cases (lt_or_le z y) with hlt hle, existsi z, apply and.intro; assumption, rewrite iff.symm sub_nonneg at hle, rewrite int.nonneg_iff_exists at hle, cases hle with n hn, apply (ex_iff_inf_or_bnd_aux P _ y n n _), rewrite sub_eq_iff_eq_add at hn, rewrite hn at hz, rewrite add_comm, apply hz, intros x hx, apply classical.by_contradiction, intro hc, apply (h2 x), apply and.intro hx, rewrite not_exists at hc, intros w hw1 hw2, apply hc w, apply and.intro; assumption, apply le_refl, cases h1 with hinf hbnd, cases (hinf 0) with z hz, existsi z, apply hz^.elim_right, cases hbnd with z hz, existsi z, apply hz^.elim_left end lemma mem_bnd_points_and (p q) : βˆ€ b, ((b ∈ bnd_points p ∨ b ∈ bnd_points q) β†’ b ∈ bnd_points (p ∧' q)) := begin unfold bnd_points, intro zzs, repeat {rewrite list.mem_filter_map}, intro hm, cases hm with hm hm; {cases hm with a ha, cases ha with ha1 ha2, unfold atoms_dep0 at ha1, rewrite list.mem_filter at ha1, cases ha1 with ha1a ha1b, existsi a, apply and.intro _ ha2, apply list.mem_filter_of_mem _ ha1b, unfold atoms, {apply list.mem_union_left ha1a _ <|> apply list.mem_union_right _ ha1a}} end lemma unified_hd_coeffs_one : βˆ€ p, nqfree p β†’ unified (hd_coeffs_one p) := begin intros p hf, unfold hd_coeffs_one, unfold unified, unfold atoms, simp, apply and.intro, apply or.inr (or.inr rfl), intros a ha, rewrite list.mem_iff_mem_of_equiv (atoms_map_fm _ _ hf) at ha, rewrite list.mem_map at ha, cases ha with a' ha', cases ha' with h1 h2, subst h2, apply unfied_hd_coeff end meta def inf_minus_prsv_tac := `[existsi (0 : int), intros z hz, unfold inf_minus] lemma inf_minus_prsv (zs) : βˆ€ (p : fm atom), βˆƒ (y : int), βˆ€ z, z < y β†’ (I (inf_minus p) (z::zs) ↔ I p (z::zs)) | ⊀' := begin existsi (0 : int), intros z hz, apply true_iff_true; trivial end | βŠ₯' := begin existsi (0 : int), intros z hz, apply false_iff_false; intro hc; cases hc end | (A' (atom.le i ks)) := begin cases ks with k ks, inf_minus_prsv_tac, cases (lt_trichotomy k 0) with hlt heqgt, existsi (- abs (i - list.dot_prod ks zs)), intros z hz, unfold inf_minus, rewrite ite_eq_of, rewrite I_atom_le, simp, rewrite iff.symm sub_le_iff_le_add, apply true_iff_true, trivial, apply le_trans (le_abs_self _), rewrite lt_neg at hz, apply le_trans (le_of_lt hz), rewrite eq.symm (neg_neg k), rewrite neg_mul_comm, apply int.le_mul_of_pos_left, apply le_trans _ (le_of_lt hz), apply abs_nonneg, unfold gt, rewrite lt_neg, apply hlt, apply hlt, cases heqgt with heq hgt, subst heq, inf_minus_prsv_tac, rewrite ite_eq_of_not, rewrite ite_eq_of_not, intro hc, cases hc, intro hc, cases hc, existsi (- abs (i - list.dot_prod ks zs)), intros z hz, unfold inf_minus, rewrite ite_eq_of_not, rewrite ite_eq_of, rewrite I_atom_le, simp, rewrite iff.symm sub_le_iff_le_add, apply false_iff_false, intro hc, cases hc, rewrite not_le, apply @lt_of_le_of_lt _ _ _ z, rewrite iff.symm neg_le_neg_iff, rewrite neg_mul_eq_mul_neg, apply int.le_mul_of_pos_left, unfold ge, rewrite le_neg, apply le_trans, apply le_of_lt hz, rewrite neg_le_neg_iff, apply abs_nonneg, apply hgt, apply lt_of_lt_of_le hz, rewrite neg_le, apply neg_le_abs_self, apply hgt, rewrite not_lt, apply le_of_lt hgt end | (A' (atom.dvd d i ks)) := by inf_minus_prsv_tac | (A' (atom.ndvd d i ks)) := by inf_minus_prsv_tac | (p ∧' q) := begin cases (inf_minus_prsv p) with x hx, cases (inf_minus_prsv q) with y hy, cases (int.exists_lt_and_lt x y) with z hz, cases hz with hz1 hz2, existsi z, intros w hw, unfold inf_minus, rewrite exp_I_and_o, rewrite hx, rewrite hy, rewrite exp_I_and, apply lt.trans hw hz2, apply lt.trans hw hz1, end | (p ∨' q) := begin cases (inf_minus_prsv p) with x hx, cases (inf_minus_prsv q) with y hy, cases (int.exists_lt_and_lt x y) with z hz, cases hz with hz1 hz2, existsi z, intros w hw, unfold inf_minus, rewrite exp_I_or_o, rewrite hx, rewrite hy, rewrite exp_I_or, apply lt.trans hw hz2, apply lt.trans hw hz1, end | (Β¬' p) := by inf_minus_prsv_tac | (βˆƒ' p) := by inf_minus_prsv_tac lemma pos_coeffs_lcm (p : fm atom) : coeffs_lcm p > 0 := begin unfold coeffs_lcm, apply int.lcms_pos, intros z hz, rewrite list.mem_map at hz, cases hz with a ha, cases ha with ha1 ha2, subst ha2, unfold atoms_dep0 at ha1, rewrite list.mem_filter at ha1, apply ha1^.elim_right end lemma pos_divisors_lcm (p : fm atom) (hn : fnormal int p) : divisors_lcm p > 0 := begin unfold divisors_lcm, apply int.lcms_pos, intros z hz, rewrite list.mem_map at hz, cases hz with a ha, cases ha with ha1 ha2, subst ha2, unfold atoms_dep0 at ha1, rewrite list.mem_filter at ha1, cases ha1 with ha1 ha2, rewrite iff.symm normal_iff_divisor_nonzero, rewrite fnormal_iff_fnormal_alt at hn, apply hn, apply ha1 end meta def coeffs_lcm_atom_tac := `[intro hk, unfold coeffs_lcm, unfold atoms_dep0, unfold atoms, unfold list.filter, rewrite ite_eq_of, unfold list.map, unfold hd_coeff, unfold list.head_dft, unfold int.lcms, apply int.lcm_one_right, apply hk] lemma coeffs_lcm_atom_le {i k : int} {ks : list int} : k β‰  0 β†’ coeffs_lcm (A' (atom.le i (k::ks))) = abs k := by coeffs_lcm_atom_tac lemma coeffs_lcm_atom_dvd {d i k : int} {ks : list int} : k β‰  0 β†’ coeffs_lcm (A' (atom.dvd d i (k::ks))) = abs k := by coeffs_lcm_atom_tac lemma coeffs_lcm_atom_ndvd {d i k : int} {ks : list int} : k β‰  0 β†’ coeffs_lcm (A' (atom.ndvd d i (k::ks))) = abs k := by coeffs_lcm_atom_tac meta def divisors_lcm_atom_tac := `[intro hk, unfold divisors_lcm, unfold atoms_dep0, unfold atoms, unfold list.filter, rewrite ite_eq_of, unfold list.map, unfold divisor, unfold int.lcms, apply int.lcm_one_right, apply hk] lemma divisors_lcm_atom_dvd {d i k : int} {ks : list int} : k β‰  0 β†’ divisors_lcm (A' (atom.dvd d i (k::ks))) = abs d := by divisors_lcm_atom_tac lemma divisors_lcm_atom_ndvd {d i k : int} {ks : list int} : k β‰  0 β†’ divisors_lcm (A' (atom.ndvd d i (k::ks))) = abs d := by divisors_lcm_atom_tac meta def lcm_distrib_tac := `[apply int.lcms_distrib, apply list.equiv.trans, apply list.map_equiv_map_of_equiv, apply list.filter_union, apply list.map_union] lemma coeffs_lcm_and (p q) : coeffs_lcm (p ∧' q) = int.lcm (coeffs_lcm p) (coeffs_lcm q) := by lcm_distrib_tac lemma coeffs_lcm_or (p q) : coeffs_lcm (p ∨' q) = int.lcm (coeffs_lcm p) (coeffs_lcm q) := by lcm_distrib_tac lemma divisors_lcm_and (p q) : divisors_lcm (p ∧' q) = int.lcm (divisors_lcm p) (divisors_lcm q) := by lcm_distrib_tac lemma divisors_lcm_or (p q) : divisors_lcm (p ∨' q) = int.lcm (divisors_lcm p) (divisors_lcm q) := by lcm_distrib_tac lemma coeffs_lcm_pos (p) : coeffs_lcm p > 0 := begin apply int.lcms_pos, intros z hz, rewrite list.mem_map at hz, cases hz with a ha, cases ha with ha1 ha2, subst ha2, unfold atoms_dep0 at ha1, rewrite list.mem_filter at ha1, apply ha1^.elim_right end lemma divisors_lcm_pos (p) : fnormal int p β†’ divisors_lcm p > 0 := begin intro hn, apply int.lcms_pos, intros z hz, rewrite list.mem_map at hz, cases hz with a ha, cases ha with ha1 ha2, subst ha2, unfold atoms_dep0 at ha1, rewrite list.mem_filter at ha1, rewrite fnormal_iff_fnormal_alt at hn, rewrite iff.symm normal_iff_divisor_nonzero, apply hn, apply ha1^.elim_left end lemma atom_dvd_mod (m d i ks z zs) : has_dvd.dvd d m β†’ ((I (A' (atom.dvd d i ks)) (z :: zs)) ↔ (I (A' (atom.dvd d i ks)) (z % m :: zs))) := begin intro hdvd, repeat {rewrite I_atom_dvd}, cases ks with k ks; simp, repeat {rewrite add_comm i}, repeat {rewrite (add_assoc)}, apply iff.symm, apply iff.trans, apply (@dvd_add_iff_right _ _ _ (k * (z - z % m))), apply dvd_mul_of_dvd_right, rewrite int.mod_def, rewrite eq.symm (sub_add _ _ _), simp, apply dvd_mul_of_dvd_left, apply hdvd, rewrite add_comm, rewrite add_assoc, rewrite add_comm _ i, rewrite add_assoc, rewrite eq.symm (mul_add _ _ _), rewrite add_comm (z % m), rewrite sub_add_cancel, simp end lemma atom_ndvd_mod (m d i ks z zs) : has_dvd.dvd d m β†’ ((I (A' (atom.ndvd d i ks)) (z :: zs)) ↔ (I (A' (atom.ndvd d i ks)) (z % m :: zs))) := begin intro hdvd, repeat {rewrite I_atom_ndvd'}, rewrite atom_dvd_mod, apply hdvd end lemma divisors_lcm_dvd_and_left (p q) : has_dvd.dvd (divisors_lcm p) (divisors_lcm (p ∧' q)) := begin rewrite divisors_lcm_and, apply int.dvd_lcm_left end lemma divisors_lcm_dvd_and_right (p q) : has_dvd.dvd (divisors_lcm q) (divisors_lcm (p ∧' q)) := begin rewrite divisors_lcm_and, apply int.dvd_lcm_right end lemma inf_minus_mod (k z zs) : βˆ€ p, nqfree p β†’ (has_dvd.dvd (divisors_lcm p) k) β†’ ((I (inf_minus p) (z :: zs)) ↔ (I (inf_minus p) (z % k :: zs))) | ⊀' _ _ := begin apply true_iff_true; trivial end | βŠ₯' _ _ := begin apply false_iff_false; intro hc; cases hc end | (A' (atom.le i [])) hf hdvd := begin unfold inf_minus, repeat {rewrite I_not_dep0}, repeat {apply not_not_intro, refl} end | (A' (atom.le i (k'::ks'))) hf hdvd := begin cases (lt_trichotomy k' 0) with hlt heqgt; unfold inf_minus, rewrite ite_eq_of, apply true_iff_true; trivial, apply hlt, cases heqgt with heq hgt, subst heq, rewrite ite_eq_of_not, rewrite ite_eq_of_not, repeat {rewrite I_not_dep0}, repeat {apply not_not_intro, refl}, simp, simp, rewrite ite_eq_of_not, rewrite ite_eq_of, apply false_iff_false; intro hc; cases hc, apply hgt, rewrite not_lt, apply le_of_lt hgt end | (A' (atom.dvd d i ks)) hf hdvd := begin cases (dvd_dep0_split d i ks) with hd0 hd0, unfold inf_minus, repeat {rewrite I_not_dep0}, assumption, assumption, cases hd0 with k' hk', cases hk' with ks' hks', cases hks' with h1 h2, subst h2, rewrite divisors_lcm_atom_dvd at hdvd, rewrite int.abs_dvd at hdvd, apply atom_dvd_mod, apply hdvd, apply h1 end | (A' (atom.ndvd d i ks)) hf hdvd := begin cases (ndvd_dep0_split d i ks) with hd0 hd0, unfold inf_minus, repeat {rewrite I_not_dep0}, assumption, assumption, cases hd0 with k' hk', cases hk' with ks' hks', cases hks' with h1 h2, subst h2, rewrite divisors_lcm_atom_ndvd at hdvd, rewrite int.abs_dvd at hdvd, apply atom_ndvd_mod, apply hdvd, apply h1 end | (p ∧' q) hf hdvd := begin cases hf with hfp hfq, unfold inf_minus, repeat {rewrite exp_I_and_o}, repeat {rewrite inf_minus_mod; try {assumption}}, apply dvd.trans _ hdvd, apply divisors_lcm_dvd_and_right, apply dvd.trans _ hdvd, apply divisors_lcm_dvd_and_left end | (p ∨' q) hf hdvd := begin cases hf with hfp hfq, unfold inf_minus, repeat {rewrite exp_I_or_o}, repeat {rewrite inf_minus_mod; try {assumption}}, apply dvd.trans _ hdvd, apply divisors_lcm_dvd_and_right, apply dvd.trans _ hdvd, apply divisors_lcm_dvd_and_left end | (Β¬' p) hf _ := by cases hf | (βˆƒ' p) hf _ := by cases hf lemma no_lb_inf_minus (p : fm atom) (hf : nqfree p) (hn : fnormal int p) (z : int) (zs) : I (inf_minus p) (z::zs) β†’ βˆ€ y, βˆƒ x, (x < y ∧ I (inf_minus p) (x::zs)) := begin intros h y, cases lt_or_le z y with hlt hle, existsi z, apply and.intro; assumption, have hw : βˆƒ (w : int), z < y + (w * divisors_lcm p), existsi (z - y + 1), rewrite iff.symm sub_lt_iff_lt_add', apply int.lt_mul_of_nonneg_right, rewrite int.lt_add_one_iff, rewrite iff.symm sub_nonneg at hle, apply le_trans hle, apply le_of_lt, rewrite int.lt_add_one_iff, apply divisors_lcm_pos _ hn, cases hw with w hw, rewrite iff.symm sub_lt_iff_lt_add at hw, existsi (z - w * divisors_lcm p), apply and.intro hw, rewrite inf_minus_mod (divisors_lcm p), rewrite inf_minus_mod (divisors_lcm p) at h, rewrite (sub_eq_add_neg _ _), rewrite neg_mul_eq_neg_mul, rewrite int.add_mul_mod_self, apply h, repeat {assumption <|> apply dvd_refl} end lemma mod_add_eq_mod (i j k : int) : (has_dvd.dvd k j) β†’ (i + j) % k = i % k := begin intro hdvd, rewrite int.dvd_iff_exists at hdvd, cases hdvd with z hz, subst hz, rewrite int.add_mul_mod_self end lemma nqfree_inf_minus_of_nqfree : βˆ€ p, nqfree p β†’ nqfree (inf_minus p) | ⊀' h := h | βŠ₯' h := h | (A' a) h := begin cases a with i ks d i ks di ks; cases ks with k ks; unfold inf_minus, apply cases_ite; intro _, trivial, apply cases_ite; intro _; trivial end | (p ∧' q) h := begin cases h with h1 h2, unfold inf_minus, apply cases_and_o, trivial, repeat {apply nqfree_inf_minus_of_nqfree, assumption}, apply and.intro; apply nqfree_inf_minus_of_nqfree; assumption end | (p ∨' q) h := begin cases h with h1 h2, unfold inf_minus, apply cases_or_o, trivial, repeat {apply nqfree_inf_minus_of_nqfree, assumption}, apply and.intro; apply nqfree_inf_minus_of_nqfree; assumption end | (Β¬' p) h := by cases h | (βˆƒ' p) h := by cases h lemma le_hd_coeff_decr {y z i k : int} {zs ks : list int} : k < 0 β†’ y < z β†’ I (A' atom.le i (k :: ks)) (z :: zs) β†’ I (A' atom.le i (k :: ks)) (y :: zs) := begin intros hk hyz h, rewrite I_atom_le at *, simp at *, apply le_trans h, rewrite add_le_add_iff_right, rewrite int.mul_le_mul_iff_le_of_neg_left, apply le_of_lt hyz, apply hk end lemma qe_cooper_one_prsv_lb (z : β„€) (zs : list β„€) : βˆ€ (p : fm atom), nqfree p β†’ fnormal β„€ p β†’ unified p β†’ βˆ€ k, 0 < k β†’ (has_dvd.dvd (divisors_lcm p) k) β†’ Β¬ I p (z :: zs) β†’ I p ((z + k)::zs) β†’ βˆƒ (k' : int), βˆƒ iks, iks ∈ bnd_points p ∧ (0 ≀ k' ∧ k' < k ∧ z + k = (k' + (prod.fst iks) + list.dot_prod (map_neg (prod.snd iks)) zs)) | ⊀' hf hn hu k _ hk h1 h2 := by trivial | βŠ₯' hf hn hu k _ hk h1 h2 := by trivial | (A' (atom.le i ks)) hf hn hu k hkp hk h1 h2 := begin cases (atom_type.dec_dep0 atom int (atom.le i ks)) with hdep hdep, unfold I at h1, unfold interp at h1, rewrite iff.symm (atom_type.decr_prsv atom int) at h1, unfold I at h2, unfold interp at h2, rewrite iff.symm (atom_type.decr_prsv atom int) at h2, exfalso, apply h1 h2, apply hdep, apply hdep, cases ks with k' ks', exfalso, apply hdep, refl, cases (hu (atom.le i (k' :: ks')) _) with hu1 hu2, unfold hd_coeff at hu1, unfold list.head_dft at hu1, subst hu1, exfalso, apply h1, apply le_hd_coeff_decr _ _ h2, apply int.pred_self_lt, apply lt_add_of_pos_right _ hkp, cases hu2 with hu2 hu2, unfold hd_coeff at hu2, unfold list.head_dft at hu2, subst hu2, exfalso, apply hdep, refl, unfold hd_coeff at hu2, unfold list.head_dft at hu2, subst hu2, existsi ((z + k) - (i + list.dot_prod (map_neg (ks')) zs)), existsi (i,ks'), apply and.intro, apply or.inl rfl, apply and.intro, unfold map_neg, rewrite list.neg_dot_prod, rewrite sub_add_eq_sub_sub, rewrite sub_neg_eq_add, unfold I at h2, unfold interp at h2, have hv : i ≀ list.dot_prod (1::ks') ((z + k) :: zs), apply h2, rewrite list.cons_dot_prod_cons at hv, rewrite iff.symm (sub_le_sub_iff_right i) at hv, simp at hv, simp, apply hv, apply and.intro, have hv : Β¬ (i ≀ list.dot_prod (1::ks') (z:: zs)), apply h1, rewrite not_le at hv, rewrite list.cons_dot_prod_cons at hv, unfold map_neg, rewrite list.neg_dot_prod, simp at hv, have hv' := add_lt_add_right (sub_lt_sub_right hv i) k, simp at hv', simp, apply hv', simp, rewrite add_comm k (-i), rewrite eq.symm (add_assoc _ _ _), simp, apply or.inl rfl end | (A' (atom.ndvd d i ks)) hf hn hu k _ hk h1 h2 := begin cases (atom_type.dec_dep0 atom int (atom.dvd d i ks)) with hdep hdep, unfold I at h1, unfold interp at h1, rewrite iff.symm (atom_type.decr_prsv atom int) at h1, unfold I at h2, unfold interp at h2, rewrite iff.symm (atom_type.decr_prsv atom int) at h2, exfalso, apply h1 h2, apply hdep, apply hdep, rewrite atom_ndvd_mod d at h1, rewrite atom_ndvd_mod d at h2, rewrite mod_add_eq_mod at h2, exfalso, apply h1 h2, apply dvd.trans (int.dvd_lcms _) hk, rewrite list.mem_map, existsi (atom.ndvd d i ks), apply and.intro, unfold atoms_dep0, rewrite list.mem_filter, apply and.intro, apply or.inl rfl, apply hdep, refl, apply dvd_refl, apply dvd_refl end | (A' (atom.dvd d i ks)) hf hn hu k _ hk h1 h2 := begin cases (atom_type.dec_dep0 atom int (atom.dvd d i ks)) with hdep hdep, unfold I at h1, unfold interp at h1, rewrite iff.symm (atom_type.decr_prsv atom int) at h1, unfold I at h2, unfold interp at h2, rewrite iff.symm (atom_type.decr_prsv atom int) at h2, exfalso, apply h1 h2, apply hdep, apply hdep, rewrite atom_dvd_mod d at h1, rewrite atom_dvd_mod d at h2, rewrite mod_add_eq_mod at h2, exfalso, apply h1 h2, apply dvd.trans (int.dvd_lcms _) hk, rewrite list.mem_map, existsi (atom.dvd d i ks), apply and.intro, unfold atoms_dep0, rewrite list.mem_filter, apply and.intro, apply or.inl rfl, apply hdep, refl, apply dvd_refl, apply dvd_refl end | (p ∨' q) hf hn hu k hkp hk h1 h2 := begin rewrite exp_I_or at h1, rewrite not_or_distrib at h1, rewrite exp_I_or at h2, cases h1 with hp hq, cases hn with hnp hnq, cases hf with hfp hfq, unfold unified at hu, unfold atoms at hu, rewrite list.forall_mem_union at hu, cases hu with hup huq, cases h2 with h2 h2, cases (qe_cooper_one_prsv_lb p hfp hnp hup k hkp _ _ h2) with k' ik', cases ik' with iks hiks, cases hiks with hm h, existsi k', existsi iks, apply and.intro, apply mem_bnd_points_and, apply or.inl hm, apply h, apply dvd.trans _ hk, apply divisors_lcm_dvd_and_left, assumption, cases (qe_cooper_one_prsv_lb q hfq hnq huq k hkp _ _ h2) with k' ik', cases ik' with iks hiks, cases hiks with hm h, existsi k', existsi iks, apply and.intro, apply mem_bnd_points_and, apply or.inr hm, apply h, apply dvd.trans _ hk, apply divisors_lcm_dvd_and_right, assumption end | (p ∧' q) hf hn hu k hkp hk h1 h2 := begin rewrite exp_I_and at h1, rewrite (@not_and_distrib _ _ (classical.prop_decidable _)) at h1, rewrite exp_I_and at h2, cases h2 with h1p h1q, cases hn with hnp hnq, cases hf with hfp hfq, unfold unified at hu, unfold atoms at hu, rewrite list.forall_mem_union at hu, cases hu with hup huq, cases h1 with h1 h1, cases (qe_cooper_one_prsv_lb p hfp hnp hup k hkp _ h1 _) with k' ik', cases ik' with iks hiks, cases hiks with hm h, existsi k', existsi iks, apply and.intro, apply mem_bnd_points_and, apply or.inl hm, apply h, apply dvd.trans _ hk, apply divisors_lcm_dvd_and_left, assumption, cases (qe_cooper_one_prsv_lb q hfq hnq huq k hkp _ h1 _) with k' ik', cases ik' with iks hiks, cases hiks with hm h, existsi k', existsi iks, apply and.intro, apply mem_bnd_points_and, apply or.inr hm, apply h, apply dvd.trans _ hk, apply divisors_lcm_dvd_and_right, assumption end | (Β¬' p) hf hn hu k _ hk h1 h2 := by cases hf | (βˆƒ' p) hf hn hu k _ hk h1 h2 := by cases hf lemma qe_cooper_one_prsv : βˆ€ (p : fm atom), nqfree p β†’ fnormal β„€ p β†’ unified p β†’ βˆ€ (bs : list β„€), I (qe_cooper_one p) bs ↔ βˆƒ (b : β„€), I p (b :: bs) := begin intros p hf hn hu bs, unfold qe_cooper_one, simp, rewrite exp_I_or_o, apply iff.intro; intro h, cases h with h h, unfold disj at h, rewrite I_list_disj at h, cases h with q hq, cases hq with hq1 hq2, rewrite list.mem_map at hq1, cases hq1 with r hr, rewrite list.mem_map at hr, cases hr with hr1 hr2, subst hr2, cases hr1 with z hz, cases hz with hz1 hz2, subst hz2, rewrite subst_prsv at hq2, rewrite list.nil_dot_prod at hq2, rewrite add_zero at hq2, cases (inf_minus_prsv bs p) with lb hlb, cases (no_lb_inf_minus p hf hn z bs hq2 lb) with x hx, cases hx with hx1 hx2, rewrite (hlb x hx1) at hx2, existsi x, apply hx2, apply nqfree_inf_minus_of_nqfree _ hf, unfold disj at h, rewrite I_list_disj at h, cases h with q hq, rewrite list.mem_map at hq, cases hq with r hr, cases r with s hs, rewrite list.mem_map at hs, cases hs with h1 h2, cases h1 with zzs hzzs, cases hzzs with h2 h3, subst h3, subst h2, rewrite I_list_disj at hr, cases hr with t ht, rewrite list.mem_map at ht, cases ht with v hv, cases v with w hw, rewrite list.mem_map at hw, cases hw with hw1 hw2, subst hw2, cases hw1 with z hz, cases hz with hz1 hz2, subst hz2, rewrite subst_prsv at hv, constructor, apply hv, apply hf, rewrite ex_iff_inf_or_bnd at h, cases h with h h, apply or.inl, cases (inf_minus_prsv bs p) with lb hlb, cases (h lb) with x hx, cases hx with hx1 hx2, rewrite iff.symm (hlb x hx1) at hx2, unfold disj, rewrite I_list_disj, simp, unfold function.comp, existsi (I (inf_minus p) ( (int.mod x (divisors_lcm p)) :: bs)), apply and.intro, rewrite list.mem_map, existsi (int.mod x (divisors_lcm p)), apply and.intro, apply list.mem_irange, apply int.mod_nonneg, apply int.nonzero_of_pos, apply pos_divisors_lcm, apply hn, apply int.lcms_nonneg, unfold divisors_lcm, apply int.mod_lt_of_pos, apply pos_divisors_lcm, apply hn, rewrite subst_prsv, rewrite list.nil_dot_prod, rewrite add_zero, rewrite inf_minus_mod at hx2, apply nqfree_inf_minus_of_nqfree _ hf, apply hf, apply dvd_refl, rewrite inf_minus_mod at hx2, apply hx2, apply hf, apply dvd_refl, cases h with lb hlb, cases hlb with hlb1 hlb2, apply or.inr, have h := qe_cooper_one_prsv_lb (lb - (divisors_lcm p)) bs p hf hn hu (divisors_lcm p) (pos_divisors_lcm _ hn) (dvd_refl _) _ _, cases h with k' h, cases h with iks h, cases h with hiks h, cases h with h1 h, cases h with h2 h3, simp at h3, subst h3, unfold disj, rewrite I_list_disj, existsi (I (list_disj (list.map (Ξ» (n : β„€), subst (n + iks.fst) (map_neg (iks.snd)) p) (list.irange (int.lcms (list.map divisor (atoms_dep0 β„€ p)))))) bs), apply and.intro, rewrite list.mem_map, existsi (list_disj (list.map (Ξ» (n : β„€), subst (n + iks.fst) (map_neg (iks.snd)) p) (list.irange (int.lcms (list.map divisor (atoms_dep0 β„€ p)))))), apply and.intro, rewrite list.mem_map, existsi iks, apply and.intro, apply hiks, refl, refl, rewrite I_list_disj, existsi (I (subst (k' + iks.fst) (map_neg (iks.snd)) p) bs), apply and.intro, rewrite list.mem_map, existsi (subst (k' + iks.fst) (map_neg (iks.snd)) p), apply and.intro, rewrite list.mem_map, existsi k', apply and.intro, apply list.mem_irange, apply h1, apply int.lcms_nonneg, apply h2, refl, refl, rewrite subst_prsv, simp, apply hlb1, apply hf, apply hlb2, rewrite sub_lt_self_iff, apply pos_divisors_lcm, apply hn, simp, apply hlb1 end lemma I_hco_le (lcm z i : β„€) (zs ks : list β„€) (hpos : lcm > 0) (hdvd : coeffs_lcm (A' atom.le i ks) ∣ lcm) : I (A' hd_coeff_one lcm (atom.le i ks)) (lcm * z :: zs) ↔ I (A' atom.le i ks) (z :: zs) := begin cases (le_dep0_split i ks) with hdep0 hdep0, rewrite hco_not_dep0 _ _ hdep0, repeat {rewrite I_not_dep0 _ _ _ hdep0}, cases hdep0 with k hk, cases hk with ks' hks', cases hks' with hk hks', subst hks', rewrite coeffs_lcm_atom_le hk at hdvd, rewrite hco_le_nonzero, simp, repeat {rewrite I_atom_le}, simp, apply iff.trans _ (int.mul_le_mul_iff_le_of_pos_left _ _ (has_div.div lcm (abs k)) _), simp, rewrite mul_add, simp, rewrite eq.symm (mul_assoc _ k z), rewrite int.div_mul_comm lcm _ k, rewrite int.mul_div_assoc, rewrite eq.symm (int.sign_eq_div_abs _), --int.div_abs_self, rewrite mul_comm lcm (int.sign k), simp, rewrite mul_assoc, rewrite int.abs_dvd, apply dvd_refl, apply hdvd, apply int.div_pos_of_pos_of_dvd, apply hpos, apply abs_nonneg, apply hdvd, apply hk end lemma I_hco_dvd (lcm z d i : β„€) (zs ks : list β„€) (hpos : lcm > 0) (hdvd : coeffs_lcm (A' atom.dvd d i ks) ∣ lcm) : I (A' hd_coeff_one lcm (atom.dvd d i ks)) (lcm * z :: zs) ↔ I (A' atom.dvd d i ks) (z :: zs) := begin cases (dvd_dep0_split d i ks) with hdep0 hdep0, rewrite hco_not_dep0 _ _ hdep0, repeat {rewrite I_not_dep0 _ _ _ hdep0}, cases hdep0 with k hk, cases hk with ks' hks', cases hks' with hk hks', subst hks', rewrite coeffs_lcm_atom_dvd hk at hdvd, rewrite int.abs_dvd at hdvd, rewrite hco_dvd_nonzero, simp, repeat {rewrite I_atom_dvd}, simp, apply iff.trans _ (@mul_dvd_mul_iff_left _ _ (has_div.div lcm k) _ _ _), rewrite mul_add, rewrite mul_add, rewrite eq.symm (mul_assoc _ _ _), rewrite int.div_mul_cancel, simp, apply hdvd, apply int.div_nonzero, apply int.nonzero_of_pos hpos, apply hdvd, apply hk end lemma I_hco_ndvd (lcm z d i : β„€) (zs ks : list β„€) (hpos : lcm > 0) (hdvd : coeffs_lcm (A' atom.ndvd d i ks) ∣ lcm) : I (A' hd_coeff_one lcm (atom.ndvd d i ks)) (lcm * z :: zs) ↔ I (A' atom.ndvd d i ks) (z :: zs) := begin cases (ndvd_dep0_split d i ks) with hdep0 hdep0, rewrite hco_not_dep0 _ _ hdep0, repeat {rewrite I_not_dep0 _ _ _ hdep0}, cases hdep0 with k hk, cases hk with ks' hks', cases hks' with hk hks', subst hks', rewrite coeffs_lcm_atom_ndvd hk at hdvd, rewrite int.abs_dvd at hdvd, rewrite hco_ndvd_nonzero, simp, repeat {rewrite I_atom_ndvd}, simp, rewrite (@not_iff_not _ _ (classical.dec _) (classical.dec _)), apply iff.trans _ (@mul_dvd_mul_iff_left _ _ (has_div.div lcm k) _ _ _), rewrite mul_add, rewrite mul_add, rewrite eq.symm (mul_assoc _ _ _), rewrite int.div_mul_cancel, simp, apply hdvd, apply int.div_nonzero, apply int.nonzero_of_pos hpos, apply hdvd, apply hk end lemma hcso_prsv_2 (lcm z : int) (zs) (hpos : lcm > 0) : βˆ€ (p : fm atom), nqfree p β†’ fnormal β„€ p β†’ has_dvd.dvd (coeffs_lcm p) lcm β†’ I p (z::zs) β†’ I (map_fm (hd_coeff_one lcm) p) ((lcm * z)::zs) | ⊀' hf hn hdvd h := trivial | βŠ₯' hf hn hdvd h := by cases h | (A' (atom.le i ks)) hf hn hdvd h := begin unfold map_fm, rewrite I_hco_le, apply h, apply hpos, apply hdvd end | (A' (atom.dvd d i ks)) hf hn hdvd h := begin unfold map_fm, rewrite I_hco_dvd, apply h, apply hpos, apply hdvd end | (A' (atom.ndvd d i ks)) hf hn hdvd h := begin unfold map_fm, rewrite I_hco_ndvd, apply h, apply hpos, apply hdvd end | (p ∧' q) hf hn hdvd h := begin unfold map_fm, rewrite exp_I_and, rewrite exp_I_and at h, cases h with hp hq, cases hn with hnp hnq, cases hf with hfp hfq, rewrite coeffs_lcm_and at hdvd, apply and.intro; apply hcso_prsv_2; try {assumption}, apply dvd.trans _ hdvd, apply int.dvd_lcm_left, apply dvd.trans _ hdvd, apply int.dvd_lcm_right end | (p ∨' q) hf hn hdvd h := begin unfold map_fm, rewrite exp_I_or, rewrite exp_I_or at h, cases hn with hnp hnq, cases hf with hfp hfq, rewrite coeffs_lcm_or at hdvd, cases h with hp hq, apply or.inl, apply hcso_prsv_2; try {assumption}, apply dvd.trans _ hdvd, apply int.dvd_lcm_left, apply or.inr, apply hcso_prsv_2; try {assumption}, apply dvd.trans _ hdvd, apply int.dvd_lcm_right end | (Β¬' p) hf hn hdvd h := by cases hf | (βˆƒ' p) hf hn hdvd h := by cases hf meta def hcso_prsv_tac := `[rewrite int.dvd_iff_exists at hdvd, cases hdvd with w hw, rewrite eq.symm hw, rewrite int.mul_div_assoc, rewrite int.div_self, rewrite mul_one, rewrite eq.symm hw at h, rewrite mul_comm at h] lemma hcso_prsv_1 (lcm z : int) (zs) (hlcm1 : lcm > 0) (hdvd : has_dvd.dvd lcm z) : βˆ€ (p : fm atom), nqfree p β†’ fnormal β„€ p β†’ (has_dvd.dvd (coeffs_lcm p) lcm) β†’ I (map_fm (hd_coeff_one lcm) p) (z::zs) β†’ I p ((has_div.div z lcm)::zs) | ⊀' hf hn _ h := trivial | βŠ₯' hf hn _ h := begin exfalso, apply h end | (A' (atom.le i ks)) hf hn hlcm2 h := begin hcso_prsv_tac, unfold map_fm at h, rewrite I_hco_le at h; try {assumption}, apply int.nonzero_of_pos hlcm1, apply dvd_refl end | (A' (atom.dvd d i ks)) hf hn hlcm2 h := begin hcso_prsv_tac, unfold map_fm at h, rewrite I_hco_dvd at h; try {assumption}, apply int.nonzero_of_pos hlcm1, apply dvd_refl end | (A' (atom.ndvd d i ks)) hf hn hlcm2 h := begin unfold map_fm at h, cases (ndvd_dep0_split d i ks) with hc hc, rewrite hco_not_dep0 _ _ hc at h, rewrite I_not_dep0, rewrite I_not_dep0 at h, apply h, apply hc, apply hc, cases hc with k hk, cases hk with ks hks, cases hks with hks1 hks2, subst hks2, rewrite hco_ndvd_nonzero at h, simp at h, rewrite coeffs_lcm_atom_ndvd at hlcm2, rewrite int.abs_dvd at hlcm2, rewrite I_atom_ndvd, rewrite I_atom_ndvd at h, intro hc, exfalso, apply h, rewrite iff.symm (@mul_dvd_mul_iff_left _ _ (has_div.div lcm k) _ _ _) at hc, simp, simp at hc, rewrite mul_add at hc, rewrite mul_add at hc, simp at hc, rewrite eq.symm (mul_assoc _ _ _) at hc, rewrite int.div_mul_cancel at hc, rewrite mul_comm lcm at hc, rewrite int.div_mul_cancel at hc, simp at hc, apply hc, apply hdvd, apply hlcm2, apply int.div_nonzero, apply int.nonzero_of_pos, apply hlcm1, apply hlcm2, apply hks1, apply hks1 end | (p ∧' q) hf hn hlcm2 h := begin rewrite exp_I_and, cases hf with hfp hfq, cases hn with hnp hnq, unfold map_fm at h, cases h with hp hq, rewrite coeffs_lcm_and at hlcm2, apply and.intro; apply hcso_prsv_1; try {assumption}, apply dvd.trans _ hlcm2, apply int.dvd_lcm_left, apply dvd.trans _ hlcm2, apply int.dvd_lcm_right, end | (p ∨' q) hf hn hlcm2 h := begin rewrite coeffs_lcm_or at hlcm2, rewrite exp_I_or, cases hf with hfp hfq, cases hn with hnp hnq, unfold map_fm at h, rewrite exp_I_or at h, cases h with hp hq, apply or.inl, apply hcso_prsv_1; try {assumption}, apply dvd.trans _ hlcm2, apply int.dvd_lcm_left, apply or.inr, apply hcso_prsv_1; try {assumption}, apply dvd.trans _ hlcm2, apply int.dvd_lcm_right end | (Β¬' p) hf hn _ h := by cases hf | (βˆƒ' p) hf hn _ h := by cases hf lemma hcso_prsv : βˆ€ (p : fm atom) (hf : nqfree p) (hn : fnormal β„€ p) (bs : list β„€), (βˆƒ (b : β„€), I (hd_coeffs_one p) (b :: bs)) ↔ βˆƒ (b : β„€), I p (b :: bs) := begin intros p hf hn bs, apply iff.intro; intro h; cases h with z hz, unfold hd_coeffs_one at hz, rewrite exp_I_and at hz, existsi (has_div.div z (coeffs_lcm p)), cases hz with hz1 hz2, apply hcso_prsv_1; try {assumption}, rewrite I_atom_dvd at hz1, rewrite zero_add at hz1, rewrite list.cons_dot_prod_cons at hz1, rewrite list.nil_dot_prod at hz1, rewrite add_zero at hz1, rewrite one_mul at hz1, apply coeffs_lcm_pos, rewrite I_atom_dvd at hz1, simp at hz1, apply hz1, apply dvd_refl, existsi (coeffs_lcm p * z), unfold hd_coeffs_one, rewrite exp_I_and, apply and.intro, rewrite I_atom_dvd, rewrite zero_add, rewrite list.cons_dot_prod_cons, rewrite list.nil_dot_prod, rewrite add_zero, rewrite one_mul, apply dvd_mul_right, apply hcso_prsv_2; try {assumption}, apply coeffs_lcm_pos, apply dvd_refl end lemma sqe_cooper_prsv : βˆ€ (p : fm atom), nqfree p β†’ fnormal β„€ p β†’ βˆ€ (bs : list β„€), I (sqe_cooper p) bs ↔ βˆƒ (b : β„€), I p (b :: bs) := begin intros p hf hn bs, unfold sqe_cooper, rewrite qe_cooper_one_prsv, apply hcso_prsv p hf hn bs, apply nqfree_hcso_of_nqfree p hf, apply hd_coeffs_one_normal_prsv _ hn, apply unified_hd_coeffs_one, apply hf end lemma qe_cooper_prsv : βˆ€ p, fnormal int p β†’ βˆ€ (bs : list int), I (qe_cooper p) bs ↔ I p bs := @lia.lnq_prsv sqe_cooper sqe_cooper_normal_prsv qfree_sqe_cooper_of_nqfree sqe_cooper_prsv
9e750e2ce7aa62048d415ce715260d233653f249
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/constr_tac.hlean
23a04519242ddd742308622d2239b3a1d1c23947
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
527
hlean
open prod example (a b c : Type) : a β†’ b β†’ c β†’ a Γ— b Γ— c := begin intro Ha Hb Hc, repeat (split | assumption) end example (a b : Type) : a β†’ sum a b := begin intro Ha, left, assumption end example (a b : Type) : b β†’ sum a b := begin intro Ha, right, assumption end open nat example (a : nat) : a > 0 β†’ Ξ£(x : β„•), x > 0 := begin intro Ha, existsi a, apply Ha end example : nat := begin constructor 1 end example : nat := begin constructor 2, constructor 2, constructor 1 end
a6c6799f1109adfb6e0a8db7496b8da57560e511
367134ba5a65885e863bdc4507601606690974c1
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
ef71048d200d33fcc3cb8fc7847a4399cc891b56
[ "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
3,598
lean
import topology.category.Top.limits import category_theory.limits.shapes import topology.instances.real import topology.tactic /-! This file contains some demos of using the (co)limits API to do topology. -/ noncomputable theory open category_theory open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit section MappingCylinder -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟢ pt := { to_fun := Ξ» _, unit.star, } -- We don't need to prove continuity: this is done automatically. def Iβ‚€ : pt ⟢ I := { to_fun := Ξ» _, ⟨(0 : ℝ), by norm_num [set.left_mem_Icc]⟩, } def I₁ : pt ⟢ I := { to_fun := Ξ» _, ⟨(1 : ℝ), by norm_num [set.right_mem_Icc]⟩, } def cylinder (X : Top) : Top := prod X I -- To define a map to the cylinder, we give a map to each factor. -- `prod.lift` is a helper method, providing a wrapper around `limit.lift` for binary products. def cylinderβ‚€ (X : Top) : X ⟢ cylinder X := prod.lift (πŸ™ X) (to_pt X ≫ Iβ‚€) def cylinder₁ (X : Top) : X ⟢ cylinder X := prod.lift (πŸ™ X) (to_pt X ≫ I₁) -- The mapping cylinder is the pushout of the diagram -- X -- ↙ β†˜ -- Y (X x I) -- (`pushout` is implemented just as a wrapper around `colimit`) is def mapping_cylinder {X Y : Top} (f : X ⟢ Y) : Top := pushout f (cylinder₁ X) /-- We construct the map from `X` into the "bottom" of the mapping cylinder for `f : X ⟢ Y`, as the composition of the inclusion of `X` into the bottom of the cylinder `prod X I`, followed by the map `pushout.inr` of `prod X I` into `mapping_cylinder f`. -/ def mapping_cylinderβ‚€ {X Y : Top} (f : X ⟢ Y) : X ⟢ mapping_cylinder f := cylinderβ‚€ X ≫ pushout.inr /-- The mapping cone is defined as the pushout of ``` X ↙ β†˜ (Cyl f) pt ``` (where the left arrow is `mapping_cylinderβ‚€`). This makes it an iterated colimit; one could also define it in one step as the colimit of ``` -- X X -- ↙ β†˜ ↙ β†˜ -- Y (X x I) pt ``` -/ def mapping_cone {X Y : Top} (f : X ⟢ Y) : Top := pushout (mapping_cylinderβ‚€ f) (to_pt X) -- TODO Hopefully someone will write a nice tactic for generating diagrams quickly, -- and we'll be able to verify that this iterated construction is the same as the colimit -- over a single diagram. end MappingCylinder section Gluing -- Here's two copies of the real line glued together at a point. def f : pt ⟢ R := { to_fun := Ξ» _, (0 : ℝ), } /-- Two copies of the real line glued together at 0. -/ def X : Top := pushout f f -- To define a map out of it, we define maps out of each copy of the line, -- and check the maps agree at 0. def g : X ⟢ R := pushout.desc (πŸ™ _) (πŸ™ _) rfl end Gluing universes v u w section Products /-- The countably infinite product of copies of `ℝ`. -/ def Y : Top := ∏ (Ξ» n : β„•, R) /-- We can define a point in this infinite product by specifying its coordinates. Let's define the point whose `n`-th coordinate is `n + 1` (as a real number). -/ def q : pt ⟢ Y := pi.lift (Ξ» (n : β„•), ⟨λ (_ : pt), (n + 1 : ℝ), by continuity⟩) -- Note that writing `Y := ∏ (Ξ» n : β„•, R)` gives us *some* topological space which satisfies the -- universal property of the product, not some explicit construction of the product, so we cannot -- rely on any definitional properties of `Y` or `q`. -- If we really want to talk about a specific construction of the limit, we have to work directly -- with the corresponding limit cones. In this case, `Top.limit_cone`. end Products
890f51cbb3001bf15a2d965ac64468daeb181d47
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/abelianization.lean
3c45fff95f2b746852ad2d1e5ee3cf402e473474
[ "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
1,934
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Michael Howes The functor Grp β†’ Ab which is the left adjoint of the forgetful functor Ab β†’ Grp. -/ import group_theory.quotient_group universes u v variables (Ξ± : Type u) [group Ξ±] def commutator : set Ξ± := group.normal_closure {x | βˆƒ p q, p * q * p⁻¹ * q⁻¹ = x} instance : normal_subgroup (commutator Ξ±) := group.normal_closure.is_normal def abelianization : Type u := quotient_group.quotient $ commutator Ξ± namespace abelianization local attribute [instance] quotient_group.left_rel normal_subgroup.to_is_subgroup instance : comm_group (abelianization Ξ±) := { mul_comm := Ξ» x y, quotient.induction_onβ‚‚ x y $ Ξ» a b, quotient.sound (group.subset_normal_closure ⟨b⁻¹,a⁻¹, by simp [mul_inv_rev, inv_inv, mul_assoc]⟩), .. quotient_group.group _} instance : inhabited (abelianization Ξ±) := ⟨1⟩ variable {Ξ±} def of (x : Ξ±) : abelianization Ξ± := quotient.mk x instance of.is_group_hom : is_group_hom (@of Ξ± _) := { map_mul := Ξ» _ _, rfl } section lift variables {Ξ² : Type v} [comm_group Ξ²] (f : Ξ± β†’ Ξ²) [is_group_hom f] lemma commutator_subset_ker : commutator Ξ± βŠ† is_group_hom.ker f := group.normal_closure_subset (Ξ» x ⟨p,q,w⟩, (is_group_hom.mem_ker f).2 (by {rw ←w, simp [is_mul_hom.map_mul f, is_group_hom.map_inv f, mul_comm]})) def lift : abelianization Ξ± β†’ Ξ² := quotient_group.lift _ f (Ξ» x h, (is_group_hom.mem_ker f).1 (commutator_subset_ker f h)) instance lift.is_group_hom : is_group_hom (lift f) := quotient_group.is_group_hom_quotient_lift _ _ _ @[simp] lemma lift.of (x : Ξ±) : lift f (of x) = f x := rfl theorem lift.unique (g : abelianization Ξ± β†’ Ξ²) [is_group_hom g] (hg : βˆ€ x, g (of x) = f x) {x} : g x = lift f x := quotient_group.induction_on x hg end lift end abelianization
8e632e144cbb2f93ff885b835a6cc10d00a2b2d5
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/aevb/graph.lean
c4f9fedff1d62029b209e97077923d71bb82610a
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
3,865
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam The actual graph produced by the naive variational auto-encoder code in aevb/prog.lean. Note: we include this file as an optimization, to avoid repeatedly simplifying the program into the graph. -/ import ..program ..prove_model_ok .util .prog namespace certigrad namespace aevb section nodes open det rand.op label tactic certigrad.tactic #print "Defining graph_naive..." def graph_naive : Ξ  (a : arch) (x_data : T [a^.n_in, a^.n_x]), graph | a x_data := graph.mk [⟨(ID.nat 0, [a^.ne, a^.bs]), [(ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str x, [a^.n_in, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 1, [a^.ne, a^.bs]), [(ID.nat 0, [a^.ne, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 2, [a^.ne, a^.bs]), [(ID.str W_encodeβ‚‚, [a^.ne, a^.ne]), (ID.nat 1, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str h_encode, [a^.ne, a^.bs]), [(ID.nat 2, [a^.ne, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.str ΞΌ, [a^.nz, a^.bs]), [(ID.str W_encode_ΞΌ, [a^.nz, a^.ne]), (ID.str h_encode, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 5, [a^.nz, a^.bs]), [(ID.str W_encode_logΟƒβ‚‚, [a^.nz, a^.ne]), (ID.str h_encode, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 6, [a^.nz, a^.bs]), [(ID.nat 5, [a^.nz, a^.bs])], operator.det $ ops.exp _⟩, ⟨(ID.str Οƒ, [a^.nz, a^.bs]), [(ID.nat 6, [a^.nz, a^.bs])], operator.det $ ops.sqrt _⟩, ⟨(ID.str z, [a^.nz, a^.bs]), [(ID.str ΞΌ, [a^.nz, a^.bs]), (ID.str Οƒ, [a^.nz, a^.bs])], operator.rand $ mvn_iso _⟩, ⟨(ID.str encoding_loss, []), [(ID.str ΞΌ, [a^.nz, a^.bs]), (ID.str Οƒ, [a^.nz, a^.bs]), (ID.str z, [a^.nz, a^.bs])], operator.det $ op.mvn_iso_empirical_kl _⟩, ⟨(ID.nat 10, [a^.nd, a^.bs]), [(ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str z, [a^.nz, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 11, [a^.nd, a^.bs]), [(ID.nat 10, [a^.nd, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 12, [a^.nd, a^.bs]), [(ID.str W_decodeβ‚‚, [a^.nd, a^.nd]), (ID.nat 11, [a^.nd, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str h_decode, [a^.nd, a^.bs]), [(ID.nat 12, [a^.nd, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 14, [a^.n_in, a^.bs]), [(ID.str W_decode_p, [a^.n_in, a^.nd]), (ID.str h_decode, [a^.nd, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str p, [a^.n_in, a^.bs]), [(ID.nat 14, [a^.n_in, a^.bs])], operator.det $ ops.sigmoid _⟩, ⟨(ID.str decoding_loss, []), [(ID.str p, [a^.n_in, a^.bs]), (ID.str x, [a^.n_in, a^.bs])], operator.det $ ops.bernoulli_neglogpdf _⟩] [ID.str encoding_loss, ID.str decoding_loss] [(ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str W_encodeβ‚‚, [a^.ne, a^.ne]), (ID.str W_encode_ΞΌ, [a^.nz, a^.ne]), (ID.str W_encode_logΟƒβ‚‚, [a^.nz, a^.ne]), (ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str W_decodeβ‚‚, [a^.nd, a^.nd]), (ID.str W_decode_p, [a^.n_in, a^.nd])] [(ID.str x, [a^.n_in, a^.bs]), (ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str W_encodeβ‚‚, [a^.ne, a^.ne]), (ID.str W_encode_ΞΌ, [a^.nz, a^.ne]), (ID.str W_encode_logΟƒβ‚‚, [a^.nz, a^.ne]), (ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str W_decodeβ‚‚, [a^.nd, a^.nd]), (ID.str W_decode_p, [a^.n_in, a^.nd])] attribute [cgsimp] graph_naive open tactic certigrad.tactic #print "proving naive_aevb_as_graph..." @[cgsimp] lemma naive_aevb_as_graph (a : arch) (x_data : T [a^.n_in, a^.n_x]) : naive_aevb a x_data = graph_naive a x_data := by { dunfold naive_aevb, cgsimp, dcgsimp, cgsimp, reflexivity } end nodes end aevb end certigrad
7aab7857e6838009e9d5933b32e4d27578c659be
dd24e6c3b8dc14dc504f8a906fc04c51e4312e6b
/src/mywork/lecture_1b.lean
897572d167042a1eedbe1c0e9ad206b46207a454
[]
no_license
njeyasingh/CS-2120
dd781a90dd0645b74e61cee1813483fb7cb4a111
b3356f665a246f295b3f1e6d61901bfca331810d
refs/heads/main
1,693,294,711,274
1,635,188,659,000
1,635,188,659,000
399,945,420
0
0
null
null
null
null
UTF-8
Lean
false
false
7,987
lean
# Truth and Reasoning ## Truth We do better on the whole when we act on what is _true_ than when we don't. ## Reasoning - Cognitive paths to truths - Important styles of reasoning include inductive, abductive, deductive. - Inductive: - The sun has always come up in the morning, so (generalizing from these observations leads one to predict that) it will come up again tomorrow, too. - Idea: derive generalized predictive models from given sets of observations - choose/use a reasonable form of model (e.g., y = mx + b) - calibrate m and b coefficients to get a minimum-error fit of line to data - test model by using it to predict results for previously unseen inputs - measure model prediction errors (e.g., |predicted_price - selling_price|) - update generalization: feed back error to improve the model coefficients - Is this form of reasoning *sound* or *not sound*? Briefly explain. - Abductive - An example from class: - On trying to clone repo in container, no GitHub URL was requested - We did online search then guessed it was that git was missing but required - Experiment: Install Git for Windows; reboot; expect problem to be solved - Outcome: - Problem was solved! - Hypothesis appears confirmed. (That's abductive reasoning.) - Based on whatever information you have or can get, *guess* a good hypothesis - Test your hypothesis experimentally and adjust your trust in it accordingly - Deductive - Assume that certain given propositions (axioms) are true (or have proofs) - Combine truths/proofs of smaller propositions into truths/proofs of bigger ones - Formal rules of inference define how truth or proof values can be combined# Truth and Reasoning ## Truth We do better on the whole when we act on what is _true_ than when we don't. ## Reasoning - Cognitive paths to truths - Important styles of reasoning include inductive, abductive, deductive. - Inductive: - The sun has always come up in the morning, so (generalizing from these observations leads one to predict that) it will come up again tomorrow, too. - Idea: derive generalized predictive models from given sets of observations - choose/use a reasonable form of model (e.g., y = mx + b) - calibrate m and b coefficients to get a minimum-error fit of line to data - test model by using it to predict results for previously unseen inputs - measure model prediction errors (e.g., |predicted_price - selling_price|) - update generalization: feed back error to improve the model coefficients - Is this form of reasoning *sound* or *not sound*? Briefly explain. - Abductive - An example from class: - On trying to clone repo in container, no GitHub URL was requested - We did online search then guessed it was that git was missing but required - Experiment: Install Git for Windows; reboot; expect problem to be solved - Outcome: - Problem was solved! - Hypothesis appears confirmed. (That's abductive reasoning.) - Based on whatever information you have or can get, *guess* a good hypothesis - Test your hypothesis experimentally and adjust your trust in it accordingly - Deductive - Assume that certain given propositions (axioms) are true (or have proofs) - Combine truths/proofs of smaller propositions into truths/proofs of bigger ones - Formal rules of inference define how truth or proof values can be combined - Examples: - If you know propositions P, Q, are true, you can deduce "P AND Q" is too - If you have proofs of P, Q, you can construct a bigger proof: of "P AND Q" - A proof shows a proposition to be true, but also explains _why_ it's true - A truth value provides a single binary digit (bit) of information, the smallest amount possible; while a proof can provide petabits of explanation - The deductive style is at the heart of mathematics and classical computer science - Their rules of evidence require _proofs_ to decide the truths of propositions - Inductive reasoning is at the heart of various *deep learning* methods in AI - Debugging is rooted in abductive reasoning: *guess* the bug then test the guess ## Example: Prove 1 = 1 Theorem: 1 = 1 (where 1 is a natural number) Proof: By application of the *reflexive axiom of equality*. This axiom, part of most definitions of predicate logics, states that every object, t, of every type, T, is equal to itself. We write this formally in the syntax of the predicate logic we will use in this class, as follows: ``` lean βˆ€ (T : Type) (t : T), t = t . ``` Given that the axiom stipulates that every object of every type is equal to itself, and given that 1 is an object of some type (β„•), it must be that 1, _in particular_, is equal to itself. This reasoning allows us to deduce not only that 1 = 1 is true, but we now also have a precise explanation why that is the case. This particular example of reasoning is called *universal elimination*. ## The rest of this lesson The rest of this lesson is in the file, lecture_1.lean. There, we further discuss and give examples of formal proofs and quasi-formal (natural language) "proof descriptions." We take proofs of equality propositions, such as 1 = 1 or 1 = 2, as examples. We'll go deeper into the concepts of propositions, axioms, proofs, logical truth, and the idea that we can understand logical reasoning as a form of computation involving propositions and proofs as types and data values, respectively. We also briefly review number systems as well as styles of reasoning and the concept of soundness. Part of this review is in the form of a short quiz at the end of the next file. - Examples: - If you know propositions P, Q, are true, you can deduce "P AND Q" is too - If you have proofs of P, Q, you can construct a bigger proof: of "P AND Q" - A proof shows a proposition to be true, but also explains _why_ it's true - A truth value provides a single binary digit (bit) of information, the smallest amount possible; while a proof can provide petabits of explanation - The deductive style is at the heart of mathematics and classical computer science - Their rules of evidence require _proofs_ to decide the truths of propositions - Inductive reasoning is at the heart of various *deep learning* methods in AI - Debugging is rooted in abductive reasoning: *guess* the bug then test the guess ## Example: Prove 1 = 1 Theorem: 1 = 1 (where 1 is a natural number) Proof: By application of the *reflexive axiom of equality*. This axiom, part of most definitions of predicate logics, states that every object, t, of every type, T, is equal to itself. We write this formally in the syntax of the predicate logic we will use in this class, as follows: ``` lean βˆ€ (T : Type) (t : T), t = t . ``` Given that the axiom stipulates that every object of every type is equal to itself, and given that 1 is an object of some type (β„•), it must be that 1, _in particular_, is equal to itself. This reasoning allows us to deduce not only that 1 = 1 is true, but we now also have a precise explanation why that is the case. This particular example of reasoning is called *universal elimination*. ## The rest of this lesson The rest of this lesson is in the file, lecture_1.lean. There, we further discuss and give examples of formal proofs and quasi-formal (natural language) "proof descriptions." We take proofs of equality propositions, such as 1 = 1 or 1 = 2, as examples. We'll go deeper into the concepts of propositions, axioms, proofs, logical truth, and the idea that we can understand logical reasoning as a form of computation involving propositions and proofs as types and data values, respectively. We also briefly review number systems as well as styles of reasoning and the concept of soundness. Part of this review is in the form of a short quiz at the end of the next file.
f6fa8fbd927d841138e0acb24eab7719f0327a24
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/rat/big_operators.lean
d1ca121dbdf3cc3612aabd6849e8ba9f7d45c963
[ "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
1,380
lean
/- Copyright (c) 2019 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Mario Carneiro -/ import data.rat.cast import algebra.big_operators.basic /-! # Casting lemmas for rational numbers involving sums and products -/ open_locale big_operators variables {ΞΉ Ξ± : Type*} namespace rat section with_div_ring variables [division_ring Ξ±] [char_zero Ξ±] @[simp, norm_cast] lemma cast_list_sum (s : list β„š) : (↑(s.sum) : Ξ±) = (s.map coe).sum := map_list_sum (rat.cast_hom Ξ±) _ @[simp, norm_cast] lemma cast_multiset_sum (s : multiset β„š) : (↑(s.sum) : Ξ±) = (s.map coe).sum := map_multiset_sum (rat.cast_hom Ξ±) _ @[simp, norm_cast] lemma cast_sum (s : finset ΞΉ) (f : ΞΉ β†’ β„š) : (↑(βˆ‘ i in s, f i) : Ξ±) = βˆ‘ i in s, f i := map_sum (rat.cast_hom Ξ±) _ _ @[simp, norm_cast] lemma cast_list_prod (s : list β„š) : (↑(s.prod) : Ξ±) = (s.map coe).prod := map_list_prod (rat.cast_hom Ξ±) _ end with_div_ring section field variables [field Ξ±] [char_zero Ξ±] @[simp, norm_cast] lemma cast_multiset_prod (s : multiset β„š) : (↑(s.prod) : Ξ±) = (s.map coe).prod := map_multiset_prod (rat.cast_hom Ξ±) _ @[simp, norm_cast] lemma cast_prod (s : finset ΞΉ) (f : ΞΉ β†’ β„š) : (↑(∏ i in s, f i) : Ξ±) = ∏ i in s, f i := map_prod (rat.cast_hom Ξ±) _ _ end field end rat
c0276baec36b64f7c51bc002a4089c018a75c6db
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/star/exponential.lean
1c07409b88ab5aeec95c124415f8b87a21d30012
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,996
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.exponential /-! # The exponential map from selfadjoint to unitary > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we establish various propreties related to the map `Ξ» a, exp β„‚ A (I β€’ a)` between the subtypes `self_adjoint A` and `unitary A`. ## TODO * Show that any exponential unitary is path-connected in `unitary A` to `1 : unitary A`. * Prove any unitary whose distance to `1 : unitary A` is less than `1` can be expressed as an exponential unitary. * A unitary is in the path component of `1` if and only if it is a finite product of exponential unitaries. -/ section star variables {A : Type*} [normed_ring A] [normed_algebra β„‚ A] [star_ring A] [has_continuous_star A] [complete_space A] [star_module β„‚ A] open complex /-- The map from the selfadjoint real subspace to the unitary group. This map only makes sense over β„‚. -/ @[simps] noncomputable def self_adjoint.exp_unitary (a : self_adjoint A) : unitary A := ⟨exp β„‚ (I β€’ a), exp_mem_unitary_of_mem_skew_adjoint _ (a.prop.smul_mem_skew_adjoint conj_I)⟩ open self_adjoint lemma commute.exp_unitary_add {a b : self_adjoint A} (h : commute (a : A) (b : A)) : exp_unitary (a + b) = exp_unitary a * exp_unitary b := begin ext, have hcomm : commute (I β€’ (a : A)) (I β€’ (b : A)), calc _ = _ : by simp only [h.eq, algebra.smul_mul_assoc, algebra.mul_smul_comm], simpa only [exp_unitary_coe, add_subgroup.coe_add, smul_add] using exp_add_of_commute hcomm, end lemma commute.exp_unitary {a b : self_adjoint A} (h : commute (a : A) (b : A)) : commute (exp_unitary a) (exp_unitary b) := calc (exp_unitary a) * (exp_unitary b) = (exp_unitary b) * (exp_unitary a) : by rw [←h.exp_unitary_add, ←h.symm.exp_unitary_add, add_comm] end star
781f7532554588bb96e162fef712d98109786a5b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/ring.lean
db225e74a45123e295627a7238ca4021395614db
[ "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
29,916
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num import data.int.range /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {Ξ±} [comm_semiring Ξ±] (a x : Ξ±) (n : β„•) (b : Ξ±) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (Ξ± : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (Ξ± : Type) : Type := reader_t cache tactic Ξ± /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : β„•) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m β„• := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (Ξ» n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {Ξ±} (m : tactic Ξ±) : ring_m Ξ± := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := do Ξ± ← infer_type e, u ← mk_meta_univ, infer_type Ξ± >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache Ξ±, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(β„•), using_new_ref ic $ Ξ» r, using_new_ref nc $ Ξ» nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := using_new_ref mk_buffer $ Ξ» atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `Ξ±`, or `β„•` for exponents). -/ @[inline] meta def ic_lift' (icf : cache β†’ ref instance_cache) {Ξ±} (f : instance_cache β†’ tactic (instance_cache Γ— Ξ±)) : ring_m Ξ± := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `Ξ±`. -/ @[inline] meta def ic_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `β„•`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {Ξ±} : (instance_cache β†’ tactic (instance_cache Γ— Ξ±)) β†’ ring_m Ξ± := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr β†’ expr := (@expr.const tt n [c.univ] c.Ξ± c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `β„•` and `β„š` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : β„š) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr β†’ expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr β†’ bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr (Ξ» _, expr β†’ expr) := ⟨λ e, ⇑(e : expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr β†’ string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr β†’ tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr Γ— expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {Ξ±} [comm_semiring Ξ±] (x n b) : @horner Ξ± _ 0 x n b = b := by simp [horner] theorem horner_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ nβ‚‚ b n') (h : n₁ + nβ‚‚ = n') : @horner Ξ± _ (horner a₁ x n₁ 0) x nβ‚‚ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr β†’ expr Γ— β„• β†’ expr Γ— β„• β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ Ξ» nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {Ξ±} [comm_semiring Ξ±] (k a x n b b') (h : k + b = b') : k + @horner Ξ± _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {Ξ±} [comm_semiring Ξ±] (a x n b k b') (h : b + k = b') : @horner Ξ± _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : n₁ + k = nβ‚‚) (hβ‚‚ : (a₁ + horner aβ‚‚ x k 0 : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x n₁ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : nβ‚‚ + k = n₁) (hβ‚‚ : (horner a₁ x k 0 + aβ‚‚ : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x nβ‚‚ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {Ξ±} [comm_semiring Ξ±] (a₁ x n b₁ aβ‚‚ bβ‚‚ a' b' t) (h₁ : a₁ + aβ‚‚ = a') (hβ‚‚ : b₁ + bβ‚‚ = b') (h₃ : horner a' x n b' = t) : @horner Ξ± _ a₁ x n b₁ + horner aβ‚‚ x n bβ‚‚ = t := by simp [h₃.symm, hβ‚‚.symm, h₁.symm, horner, add_mul, mul_comm (x ^ n)]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := ic_lift $ Ξ» ic, do let n := c₁ + cβ‚‚, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ eβ‚‚ e c₁ cβ‚‚ n, return (ic, const e n, p) | he₁@(const e₁ c₁) heβ‚‚@(xadd eβ‚‚ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``zero_add [eβ‚‚], return (ic, heβ‚‚, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) heβ‚‚@(const eβ‚‚ cβ‚‚) := do c ← get_cache, if cβ‚‚ = 0 then ic_lift $ Ξ» ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b heβ‚‚, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, eβ‚‚, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (b', h) ← eval_add b₁ heβ‚‚, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, b', h]) else if x₁.2 β‰  xβ‚‚.2 then do (b', h) ← eval_add he₁ bβ‚‚, return (xadd' c aβ‚‚ xβ‚‚ nβ‚‚ b', c.cs_app ``const_add_horner [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, b', h]) else if n₁.2 < nβ‚‚.2 then do let k := nβ‚‚.2 - n₁.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek nβ‚‚.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add a₁ (xadd' c aβ‚‚ x₁ (ek, k) (const Ξ±0 0)), (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else if n₁.2 β‰  nβ‚‚.2 then do let k := n₁.2 - nβ‚‚.2, (ek, h₁) ← nc_lift (Ξ» nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc nβ‚‚.1 ek n₁.1, return (nc, ek, h₁)), Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (a', hβ‚‚) ← eval_add (xadd' c a₁ x₁ (ek, k) (const Ξ±0 0)) aβ‚‚, (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ nβ‚‚ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else do (a', h₁) ← eval_add a₁ aβ‚‚, (b', hβ‚‚) ← eval_add b₁ bβ‚‚, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, aβ‚‚, bβ‚‚, a', b', t, h₁, hβ‚‚, h₃]) theorem horner_neg {Ξ±} [comm_ring Ξ±] (a x n b a' b') (h₁ : -a = a') (hβ‚‚ : -b = b') : -@horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', hβ‚‚) ← eval_neg b, p ← ic_lift $ Ξ» ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, hβ‚‚], return (xadd' c a' x n b', p) theorem horner_const_mul {Ξ±} [comm_semiring Ξ±] (c a x n b a' b') (h₁ : c * a = a') (hβ‚‚ : c * b = b') : c * @horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {Ξ±} [comm_semiring Ξ±] (a x n b c a' b') (h₁ : a * c = a') (hβ‚‚ : b * c = b') : @horner Ξ± _ a x n b * c = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr Γ— β„š) : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e coeff) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', hβ‚‚) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, hβ‚‚]) theorem horner_mul_horner_zero {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ aa t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ 0 = t := by rw [← hβ‚‚, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ aa haa ab bb t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = haa) (h₃ : a₁ * bβ‚‚ = ab) (hβ‚„ : b₁ * bβ‚‚ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ bβ‚‚ = t := by rw [← H, ← hβ‚‚, ← h₁, ← h₃, ← hβ‚„]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁ c₁) (const eβ‚‚ cβ‚‚) := do (e', p) ← ic_lift $ Ξ» ic, norm_num.prove_mul_rat ic e₁ eβ‚‚ c₁ cβ‚‚, return (const e' (c₁ * cβ‚‚), p) | (const e₁ c₁) eβ‚‚ := if c₁ = 0 then do c ← get_cache, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ Ξ» ic, ic.mk_app ``zero_mul [eβ‚‚], return (const Ξ±0 0, p) else if c₁ = 1 then do p ← ic_lift $ Ξ» ic, ic.mk_app ``one_mul [eβ‚‚], return (eβ‚‚, p) else eval_const_mul (e₁, c₁) eβ‚‚ | e₁ heβ‚‚@(const eβ‚‚ cβ‚‚) := do p₁ ← ic_lift $ Ξ» ic, ic.mk_app ``mul_comm [e₁, eβ‚‚], (e', pβ‚‚) ← eval_mul heβ‚‚ e₁, p ← lift $ mk_eq_trans p₁ pβ‚‚, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (a', h₁) ← eval_mul a₁ heβ‚‚, (b', hβ‚‚) ← eval_mul b₁ heβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, a', b', h₁, hβ‚‚]) else if x₁.2 β‰  xβ‚‚.2 then do (a', h₁) ← eval_mul he₁ aβ‚‚, (b', hβ‚‚) ← eval_mul he₁ bβ‚‚, return (xadd' c a' xβ‚‚ nβ‚‚ b', c.cs_app ``horner_const_mul [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, a', b', h₁, hβ‚‚]) else do (aa, h₁) ← eval_mul he₁ aβ‚‚, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], (haa, hβ‚‚) ← eval_horner aa x₁ nβ‚‚ (const Ξ±0 0), if bβ‚‚.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, aa, haa, h₁, hβ‚‚]) else do (ab, h₃) ← eval_mul a₁ bβ‚‚, (bb, hβ‚„) ← eval_mul b₁ bβ‚‚, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, aa, haa, ab, bb, t, h₁, hβ‚‚, h₃, hβ‚„, H]) theorem horner_pow {Ξ±} [comm_semiring Ξ±] (a x n m n' a') (h₁ : n * m = n') (hβ‚‚ : a ^ m = a') : @horner Ξ± _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, hβ‚‚.symm, horner, mul_pow, pow_mul] theorem pow_succ {Ξ±} [comm_semiring Ξ±] (a n b c) (h₁ : (a:Ξ±) ^ n = b) (hβ‚‚ : b * a = c) : a ^ (n + 1) = c := by rw [← hβ‚‚, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr β†’ expr Γ— β„• β†’ ring_m (horner_expr Γ— expr) | e (_, 0) := do c ← get_cache, Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_zero [e], return (const Ξ±1 1, p) | e (_, 1) := do p ← ic_lift $ Ξ» ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (eβ‚‚, m) := ic_lift $ Ξ» ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic eβ‚‚, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ Ξ» nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', hβ‚‚) ← eval_pow a m, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const Ξ±0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, hβ‚‚]) | _ := do eβ‚‚ ← nc_lift $ Ξ» nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (eβ‚‚, m.2-1), (t, pβ‚‚) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, eβ‚‚, tl, t, hl, pβ‚‚]) end theorem horner_atom {Ξ±} [comm_semiring Ξ±] (x : Ξ±) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr Γ— expr) := do c ← get_cache, i ← add_atom e, Ξ±0 ← ic_lift $ Ξ» ic, ic.mk_app ``has_zero.zero [], Ξ±1 ← ic_lift $ Ξ» ic, ic.mk_app ``has_one.one [], return (xadd' c (const Ξ±1 1) (e, i) (`(1), 1) (const Ξ±0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {Ξ±} [monoid Ξ±] (l r tl tr t) (prl : (l : Ξ±) = tl) (prr : (r : β„•) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {Ξ±} [division_ring Ξ±] (a b c : Ξ±) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr β†’ ring_m (horner_expr Γ— expr) | `(%%e₁ + %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_add e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_add [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(@has_sub.sub %%Ξ± %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (lift $ mk_app ``comm_ring [Ξ±] >>= mk_instance)) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_neg.neg [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_add.add [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_sub [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (eβ‚‚, pβ‚‚) ← eval_neg e₁, p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, eβ‚‚, p₁, pβ‚‚], return (eβ‚‚, p) | `(%%e₁ * %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_mul e₁' eβ‚‚', p ← ic_lift $ Ξ» ic, ic.mk_app ``norm_num.subst_into_mul [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (do inst' ← ic_lift $ Ξ» ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do eβ‚‚' ← ic_lift $ Ξ» ic, ic.mk_app ``has_inv.inv [eβ‚‚], e ← ic_lift $ Ξ» ic, ic.mk_app ``has_mul.mul [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ic_lift $ Ξ» ic, ic.mk_app ``unfold_div [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%eβ‚‚) := do (eβ‚‚', pβ‚‚) ← lift $ norm_num.derive eβ‚‚ <|> refl_conv eβ‚‚, match eβ‚‚'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (eβ‚‚, k), p ← ic_lift $ Ξ» ic, ic.mk_app ``subst_into_pow [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (e : expr) : tactic (expr Γ— expr) := ring_m.run' red atoms e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {Ξ±} [comm_semiring Ξ±] (a x n b) : @horner Ξ± _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {Ξ±} [semigroup Ξ±] (a b c : Ξ±) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {Ξ±} [monoid Ξ±] (a : Ξ±) (m n : β„•) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {Ξ±} [monoid Ξ±] (a b : Ξ±) (m n : β„•) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {Ξ±} [add_group Ξ±] (a b : Ξ±) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ— expr) := using_new_ref mk_buffer $ Ξ» atoms, do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (Ξ» _, failed) (Ξ» _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red atoms | normalize_mode.horner := trans_conv (eval' red atoms) (Ξ» e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) | normalize_mode.SOP := trans_conv (eval' red atoms) $ trans_conv (Ξ» e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) $ simp_bottom_up' (Ξ» e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (Β¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (Ξ» _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open tactic.ring setup_tactic_parser /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%eβ‚‚) ← target, ((e₁', p₁), (eβ‚‚', pβ‚‚)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval eβ‚‚, is_def_eq e₁' eβ‚‚', p ← mk_eq_symm pβ‚‚ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring_nf`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. When writing a normal form, `ring_nf SOP` will use sum-of-products form instead of horner form. `ring_nf!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring_nf (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring_nf failed to simplify", when loc.include_goal $ try tactic.reflexivity /-- Tactic for solving equations in the language of *commutative* (semi)rings. `ring!` will use a more aggressive reducibility setting to identify atoms. If the goal is not solvable, it falls back to rewriting all ring expressions into a normal form, with a suggestion to use `ring_nf` instead, if this is the intent. See also `ring1`, which is the same as `ring` but without the fallback behavior. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin GrΓ©goire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) : tactic unit := ring1 red <|> (ring_nf red normalize_mode.horner (loc.ns [none]) >> trace "Try this: ring_nf") add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [``ring, ``ring_nf, ``ring1], inherit_description_from := ``ring, tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize normalize_mode.horner) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring_nf (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in replace_lhs (normalize transp SOP) <|> fail "ring_nf failed to simplify" /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> (replace_lhs (normalize transp normalize_mode.horner) >> trace "Try this: ring_nf") <|> fail "ring failed to simplify" end conv.interactive
b0801647dab1074ead433459e2c4aa868ec6debd
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/pnat/factors.lean
c0d98690df2804c1c26db25ccae33c7a28b9e564
[ "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
13,966
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import data.pnat.basic import data.multiset.sort import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and β„•+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≀ v β†’ u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset β†’ multiset β„• := Ξ» v, v.map (Ξ» p, (p : β„•)) instance coe_nat : has_coe prime_multiset (multiset β„•) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset β†’ multiset β„•) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_injective : function.injective (coe : prime_multiset β†’ multiset β„•) := multiset.map_injective nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset β„•) = (p : β„•) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : β„•) (h : p ∈ (v : multiset β„•)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp' } def to_pnat_multiset : prime_multiset β†’ multiset β„•+ := Ξ» v, v.map (Ξ» p, (p : β„•+)) instance coe_pnat : has_coe prime_multiset (multiset β„•+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset β†’ multiset β„•+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_injective : function.injective (coe : prime_multiset β†’ multiset β„•+) := multiset.map_injective nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset β„•+) = (p : β„•+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : β„•+) (h : p ∈ (v : multiset β„•+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp' } instance coe_multiset_pnat_nat : has_coe (multiset β„•+) (multiset β„•) := ⟨λ v, v.map (Ξ» n, (n : β„•))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset β„•+)) : (multiset β„•)) = (v : multiset β„•) := by { change (v.map (coe : nat.primes β†’ β„•+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : β„•+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : β„•) = (v : multiset β„•).prod := begin let h : (v.prod : β„•) = ((v.map coe).map coe).prod := ((monoid_hom.of coe).map_multiset_prod v.to_pnat_multiset), rw [multiset.map_map] at h, have : (coe : β„•+ β†’ β„•) ∘ (coe : nat.primes β†’ β„•+) = coe := funext (Ξ» p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : β„•+) := by { change multiset.prod ((p : β„•+) :: 0) = (p : β„•+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset β„•) (h : βˆ€ (p : β„•), p ∈ v β†’ p.prime) : prime_multiset := @multiset.pmap β„• nat.primes nat.prime (Ξ» p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset β„•) (h) : ((of_nat_multiset v h) : multiset β„•) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (Ξ» (p : β„•) (h : p.prime), ((⟨p, h⟩ : nat.primes) : β„•)) = (Ξ» p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset β„•) (h) : ((of_nat_multiset v h).prod : β„•) = (v.prod : β„•) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset β„•+) (h : βˆ€ (p : β„•+), p ∈ v β†’ p.prime) : prime_multiset := @multiset.pmap β„•+ nat.primes pnat.prime (Ξ» p hp, ⟨(p : β„•), hp⟩) v h theorem to_of_pnat_multiset (v : multiset β„•+) (h) : ((of_pnat_multiset v h) : multiset β„•+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (Ξ» (p : β„•+) (h : p.prime), ((coe : nat.primes β†’ β„•+) ⟨p, h⟩)) = (Ξ» p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset β„•+) (h) : ((of_pnat_multiset v h).prod : β„•+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list β„•) (h : βˆ€ (p : β„•), p ∈ l β†’ p.prime) : prime_multiset := of_nat_multiset (l : multiset β„•) h theorem prod_of_nat_list (l : list β„•) (h) : ((of_nat_list l h).prod : β„•) = l.prod := by { have := prod_of_nat_multiset (l : multiset β„•) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list β„•+) (h : βˆ€ (p : β„•+), p ∈ l β†’ p.prime) : prime_multiset := of_pnat_multiset (l : multiset β„•+) h theorem prod_of_pnat_list (l : list β„•+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset β„•+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid β„•+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset β†’ multiset β„•+)], rw [multiset.prod_add] } theorem prod_smul (d : β„•) (u : prime_multiset) : (d β€’β„• u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : β„•+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : β„•+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : β„•+) : ((factor_multiset n) : (multiset β„•)) = ((nat.factors n) : multiset β„•) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_injective, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with ⟨l⟩, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes β†’ β„•), have : βˆ€ (p : β„•), p ∈ l' β†’ p.prime := Ξ» p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : β„•+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid β„•+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : β„•+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : β„•+) (m : β„•) : factor_multiset (n ^ m) = m β€’β„• (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : β„•+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : β„•+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : β„•+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : β„•+} : factor_multiset m ≀ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd.intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : β„•+} {v : prime_multiset}: factor_multiset m ≀ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≀ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : β„•+} : u.prod ∣ n ↔ u ≀ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : β„•+) : factor_multiset (gcd m n) = (factor_multiset m) βŠ“ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : β„•+) : factor_multiset (lcm m n) = (factor_multiset m) βŠ” (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : β„•+) (p : nat.primes) (k : β„•) : (p : β„•+) ^ k ∣ m ↔ k ≀ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : βˆ€ (m : β„•), m β€’β„• (p::0) = multiset.repeat p m := Ξ» m, by {induction m with m ih, { refl }, rw [succ_nsmul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u βŠ“ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u βŠ“ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u βŠ” v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u βŠ” v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
3c596c69d37093209c4da39ff4502e53b2d172b3
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/rat/basic.lean
bf9c2dab2de6f9fb81c0ca100a34366de6985cab
[ "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
24,183
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The rational numbers as a field generated by the integers, defined as the usual quotient. -/ import data.int algebra.field open int quot eq.ops open algebra record prerat : Type := (num : β„€) (denom : β„€) (denom_pos : denom > 0) /- prerat: the representations of the rationals as integers num, denom, with denom > 0. note: names are not protected, because it is not expected that users will open prerat. -/ namespace prerat /- the equivalence relation -/ definition equiv (a b : prerat) : Prop := num a * denom b = num b * denom a infix ≑ := equiv theorem equiv.refl [refl] (a : prerat) : a ≑ a := rfl theorem equiv.symm [symm] {a b : prerat} (H : a ≑ b) : b ≑ a := !eq.symm H theorem num_eq_zero_of_equiv {a b : prerat} (H : a ≑ b) (na_zero : num a = 0) : num b = 0 := have num a * denom b = 0, from !zero_mul β–Έ na_zero β–Έ rfl, have num b * denom a = 0, from H β–Έ this, show num b = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) (ne_of_gt (denom_pos a)) theorem num_pos_of_equiv {a b : prerat} (H : a ≑ b) (na_pos : num a > 0) : num b > 0 := have num a * denom b > 0, from mul_pos na_pos (denom_pos b), have num b * denom a > 0, from H β–Έ this, show num b > 0, from pos_of_mul_pos_right this (le_of_lt (denom_pos a)) theorem num_neg_of_equiv {a b : prerat} (H : a ≑ b) (na_neg : num a < 0) : num b < 0 := assert H₁ : num a * denom b = num b * denom a, from H, assert num a * denom b < 0, from mul_neg_of_neg_of_pos na_neg (denom_pos b), have -(-num b * denom a) < 0, begin rewrite [neg_mul_eq_neg_mul, neg_neg, -H₁], exact this end, have -num b > 0, from pos_of_mul_pos_right (pos_of_neg_neg this) (le_of_lt (denom_pos a)), neg_of_neg_pos this theorem equiv_of_num_eq_zero {a b : prerat} (H1 : num a = 0) (H2 : num b = 0) : a ≑ b := by rewrite [↑equiv, H1, H2, *zero_mul] theorem equiv.trans [trans] {a b c : prerat} (H1 : a ≑ b) (H2 : b ≑ c) : a ≑ c := decidable.by_cases (suppose num b = 0, have num a = 0, from num_eq_zero_of_equiv (equiv.symm H1) `num b = 0`, have num c = 0, from num_eq_zero_of_equiv H2 `num b = 0`, equiv_of_num_eq_zero `num a = 0` `num c = 0`) (suppose num b β‰  0, have H3 : num b * denom b β‰  0, from mul_ne_zero this (ne_of_gt (denom_pos b)), have H4 : (num b * denom b) * (num a * denom c) = (num b * denom b) * (num c * denom a), from calc (num b * denom b) * (num a * denom c) = (num a * denom b) * (num b * denom c) : by rewrite [*mul.assoc, *mul.left_comm (num a), *mul.left_comm (num b)] ... = (num b * denom a) * (num b * denom c) : {H1} ... = (num b * denom a) * (num c * denom b) : {H2} ... = (num b * denom b) * (num c * denom a) : by rewrite [*mul.assoc, *mul.left_comm (denom a), *mul.left_comm (denom b), mul.comm (denom a)], eq_of_mul_eq_mul_left H3 H4) theorem equiv.is_equivalence : equivalence equiv := mk_equivalence equiv equiv.refl @equiv.symm @equiv.trans definition setoid : setoid prerat := setoid.mk equiv equiv.is_equivalence /- field operations -/ definition of_int (i : int) : prerat := prerat.mk i 1 !of_nat_succ_pos definition zero : prerat := of_int 0 definition one : prerat := of_int 1 private theorem mul_denom_pos (a b : prerat) : denom a * denom b > 0 := mul_pos (denom_pos a) (denom_pos b) definition add (a b : prerat) : prerat := prerat.mk (num a * denom b + num b * denom a) (denom a * denom b) (mul_denom_pos a b) definition mul (a b : prerat) : prerat := prerat.mk (num a * num b) (denom a * denom b) (mul_denom_pos a b) definition neg (a : prerat) : prerat := prerat.mk (- num a) (denom a) (denom_pos a) definition smul (a : β„€) (b : prerat) (H : a > 0) : prerat := prerat.mk (a * num b) (a * denom b) (mul_pos H (denom_pos b)) theorem of_int_add (a b : β„€) : of_int (a + b) ≑ add (of_int a) (of_int b) := by esimp [equiv, num, denom, one, add, of_int]; rewrite [*int.mul_one] theorem of_int_mul (a b : β„€) : of_int (a * b) ≑ mul (of_int a) (of_int b) := !equiv.refl theorem of_int_neg (a : β„€) : of_int (-a) ≑ neg (of_int a) := !equiv.refl theorem of_int.inj {a b : β„€} : of_int a ≑ of_int b β†’ a = b := by rewrite [↑of_int, ↑equiv, *mul_one]; intros; assumption definition inv : prerat β†’ prerat | inv (prerat.mk nat.zero d dp) := zero | inv (prerat.mk (nat.succ n) d dp) := prerat.mk d (nat.succ n) !of_nat_succ_pos | inv (prerat.mk -[1+n] d dp) := prerat.mk (-d) (nat.succ n) !of_nat_succ_pos theorem equiv_zero_of_num_eq_zero {a : prerat} (H : num a = 0) : a ≑ zero := by rewrite [↑equiv, H, ↑zero, ↑num, ↑of_int, *zero_mul] theorem num_eq_zero_of_equiv_zero {a : prerat} : a ≑ zero β†’ num a = 0 := by rewrite [↑equiv, ↑zero, ↑of_int, mul_one, zero_mul]; intro H; exact H theorem inv_zero {d : int} (dp : d > 0) : inv (mk nat.zero d dp) = zero := begin rewrite [↑inv, β–Έ*] end theorem inv_zero' : inv zero = zero := inv_zero (of_nat_succ_pos nat.zero) open nat theorem inv_of_pos {n d : int} (np : n > 0) (dp : d > 0) : inv (mk n d dp) ≑ mk d n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' β–Έ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have d * n = d * nat.succ k, by rewrite [Hn', Hk], Hn'⁻¹ β–Έ (Hk⁻¹ β–Έ this) theorem inv_neg {n d : int} (np : n > 0) (dp : d > 0) : inv (mk (-n) d dp) ≑ mk (-d) n np := obtain (n' : nat) (Hn' : n = of_nat n'), from exists_eq_of_nat (le_of_lt np), have (n' > nat.zero), from lt_of_of_nat_lt_of_nat (Hn' β–Έ np), obtain (k : nat) (Hk : n' = nat.succ k), from nat.exists_eq_succ_of_lt this, have -d * n = -d * nat.succ k, by rewrite [Hn', Hk], have H3 : inv (mk -[1+k] d dp) ≑ mk (-d) n np, from this, have H4 : -[1+k] = -n, from calc -[1+k] = -(nat.succ k) : rfl ... = -n : by rewrite [Hk⁻¹, Hn'], H4 β–Έ H3 theorem inv_of_neg {n d : int} (nn : n < 0) (dp : d > 0) : inv (mk n d dp) ≑ mk (-d) (-n) (neg_pos_of_neg nn) := have inv (mk (-(-n)) d dp) ≑ mk (-d) (-n) (neg_pos_of_neg nn), from inv_neg (neg_pos_of_neg nn) dp, !neg_neg β–Έ this /- operations respect equiv -/ theorem add_equiv_add {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≑ a2) (eqv2 : b1 ≑ b2) : add a1 b1 ≑ add a2 b2 := calc (num a1 * denom b1 + num b1 * denom a1) * (denom a2 * denom b2) = num a1 * denom a2 * denom b1 * denom b2 + num b1 * denom b2 * denom a1 * denom a2 : by rewrite [right_distrib, *mul.assoc, mul.left_comm (denom b1), mul.comm (denom b2), *mul.assoc] ... = num a2 * denom a1 * denom b1 * denom b2 + num b2 * denom b1 * denom a1 * denom a2 : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * denom b2 + num b2 * denom a2) * (denom a1 * denom b1) : by rewrite [right_distrib, *mul.assoc, *mul.left_comm (denom b2), *mul.comm (denom b1), *mul.assoc, mul.left_comm (denom a2)] theorem mul_equiv_mul {a1 b1 a2 b2 : prerat} (eqv1 : a1 ≑ a2) (eqv2 : b1 ≑ b2) : mul a1 b1 ≑ mul a2 b2 := calc (num a1 * num b1) * (denom a2 * denom b2) = (num a1 * denom a2) * (num b1 * denom b2) : by rewrite [*mul.assoc, mul.left_comm (num b1)] ... = (num a2 * denom a1) * (num b2 * denom b1) : by rewrite [↑equiv at *, eqv1, eqv2] ... = (num a2 * num b2) * (denom a1 * denom b1) : by rewrite [*mul.assoc, mul.left_comm (num b2)] theorem neg_equiv_neg {a b : prerat} (eqv : a ≑ b) : neg a ≑ neg b := calc -num a * denom b = -(num a * denom b) : neg_mul_eq_neg_mul ... = -(num b * denom a) : {eqv} ... = -num b * denom a : neg_mul_eq_neg_mul theorem inv_equiv_inv : βˆ€{a b : prerat}, a ≑ b β†’ inv a ≑ inv b | (mk an ad adp) (mk bn bd bdp) := assume H, lt.by_cases (assume an_neg : an < 0, have bn_neg : bn < 0, from num_neg_of_equiv H an_neg, calc inv (mk an ad adp) ≑ mk (-ad) (-an) (neg_pos_of_neg an_neg) : inv_of_neg an_neg adp ... ≑ mk (-bd) (-bn) (neg_pos_of_neg bn_neg) : by rewrite [↑equiv at *, β–Έ*, *neg_mul_neg, mul.comm ad, mul.comm bd, H] ... ≑ inv (mk bn bd bdp) : (inv_of_neg bn_neg bdp)⁻¹) (assume an_zero : an = 0, have bn_zero : bn = 0, from num_eq_zero_of_equiv H an_zero, eq.subst (calc inv (mk an ad adp) = inv (mk 0 ad adp) : {an_zero} ... = zero : inv_zero adp ... = inv (mk 0 bd bdp) : inv_zero bdp ... = inv (mk bn bd bdp) : bn_zero) !equiv.refl) (assume an_pos : an > 0, have bn_pos : bn > 0, from num_pos_of_equiv H an_pos, calc inv (mk an ad adp) ≑ mk ad an an_pos : inv_of_pos an_pos adp ... ≑ mk bd bn bn_pos : by rewrite [↑equiv at *, β–Έ*, mul.comm ad, mul.comm bd, H] ... ≑ inv (mk bn bd bdp) : (inv_of_pos bn_pos bdp)⁻¹) theorem smul_equiv {a : β„€} {b : prerat} (H : a > 0) : smul a b H ≑ b := by esimp[equiv, smul]; rewrite[mul.assoc, mul.left_comm] /- properties -/ theorem add.comm (a b : prerat) : add a b ≑ add b a := by rewrite [↑add, ↑equiv, β–Έ*, add.comm, mul.comm (denom a)] theorem add.assoc (a b c : prerat) : add (add a b) c ≑ add a (add b c) := by rewrite [↑add, ↑equiv, β–Έ*, *(mul.comm (num c)), *(Ξ»y, mul.comm y (denom a)), *left_distrib, *right_distrib, *mul.assoc, *add.assoc] theorem add_zero (a : prerat) : add a zero ≑ a := by rewrite [↑add, ↑equiv, ↑zero, ↑of_int, β–Έ*, *mul_one, zero_mul, add_zero] theorem add.left_inv (a : prerat) : add (neg a) a ≑ zero := by rewrite [↑add, ↑equiv, ↑neg, ↑zero, ↑of_int, β–Έ*, -neg_mul_eq_neg_mul, add.left_inv, *zero_mul] theorem mul.comm (a b : prerat) : mul a b ≑ mul b a := by rewrite [↑mul, ↑equiv, mul.comm (num a), mul.comm (denom a)] theorem mul.assoc (a b c : prerat) : mul (mul a b) c ≑ mul a (mul b c) := by rewrite [↑mul, ↑equiv, *mul.assoc] theorem mul_one (a : prerat) : mul a one ≑ a := by rewrite [↑mul, ↑one, ↑of_int, ↑equiv, β–Έ*, *mul_one] theorem mul.left_distrib (a b c : prerat) : mul a (add b c) ≑ add (mul a b) (mul a c) := have H : smul (denom a) (mul a (add b c)) (denom_pos a) = add (mul a b) (mul a c), from begin rewrite[↑smul, ↑mul, ↑add], congruence, rewrite[*left_distrib, *right_distrib, -+(int.mul_assoc)], have T : βˆ€ {x y z w : β„€}, x*y*z*w=y*z*x*w, from Ξ»x y z w, (!int.mul_assoc ⬝ !int.mul_comm) β–Έ rfl, exact !congr_arg2 T T, rewrite [mul.left_comm (denom a) (denom b) (denom c)], rewrite int.mul_assoc end, equiv.symm (H β–Έ smul_equiv (denom_pos a)) theorem mul_inv_cancel : βˆ€{a : prerat}, Β¬ a ≑ zero β†’ mul a (inv a) ≑ one | (mk an ad adp) := assume H, let a := mk an ad adp in lt.by_cases (assume an_neg : an < 0, let ia := mk (-ad) (-an) (neg_pos_of_neg an_neg) in calc mul a (inv a) ≑ mul a ia : mul_equiv_mul !equiv.refl (inv_of_neg an_neg adp) ... ≑ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, algebra.mul.comm, neg_mul_comm] end) (assume an_zero : an = 0, absurd (equiv_zero_of_num_eq_zero an_zero) H) (assume an_pos : an > 0, let ia := mk ad an an_pos in calc mul a (inv a) ≑ mul a ia : mul_equiv_mul !equiv.refl (inv_of_pos an_pos adp) ... ≑ one : begin esimp [equiv, num, denom, one, mul, of_int], rewrite [*int.mul_one, *int.one_mul, algebra.mul.comm] end) theorem zero_not_equiv_one : Β¬ zero ≑ one := begin esimp [equiv, zero, one, of_int], rewrite [zero_mul, int.mul_one], exact zero_ne_one end theorem mul_denom_equiv (a : prerat) : mul a (of_int (denom a)) ≑ of_int (num a) := by esimp [mul, of_int, equiv]; rewrite [*int.mul_one] /- Reducing a fraction to lowest terms. Needed to choose a canonical representative of rat, and define numerator and denominator. -/ definition reduce : prerat β†’ prerat | (mk an ad adpos) := have pos : ad / gcd an ad > 0, from div_pos_of_pos_of_dvd adpos !gcd_nonneg !gcd_dvd_right, if an = 0 then prerat.zero else mk (an / gcd an ad) (ad / gcd an ad) pos protected theorem eq {a b : prerat} (Hn : num a = num b) (Hd : denom a = denom b) : a = b := begin cases a with [an, ad, adpos], cases b with [bn, bd, bdpos], generalize adpos, generalize bdpos, esimp at *, rewrite [Hn, Hd], intros, apply rfl end theorem reduce_equiv : βˆ€ a : prerat, reduce a ≑ a | (mk an ad adpos) := decidable.by_cases (assume anz : an = 0, begin rewrite [↑reduce, if_pos anz, ↑equiv, anz], krewrite zero_mul end) (assume annz : an β‰  0, by rewrite [↑reduce, if_neg annz, ↑equiv, algebra.mul.comm, -!int.mul_div_assoc !gcd_dvd_left, -!int.mul_div_assoc !gcd_dvd_right, algebra.mul.comm]) theorem reduce_eq_reduce : βˆ€ {a b : prerat}, a ≑ b β†’ reduce a = reduce b | (mk an ad adpos) (mk bn bd bdpos) := assume H : an * bd = bn * ad, decidable.by_cases (assume anz : an = 0, have H' : bn * ad = 0, by rewrite [-H, anz, zero_mul], assert bnz : bn = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt adpos), by rewrite [↑reduce, if_pos anz, if_pos bnz]) (assume annz : an β‰  0, assert bnnz : bn β‰  0, from assume bnz, have H' : an * bd = 0, by rewrite [H, bnz, zero_mul], have anz : an = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero H') (ne_of_gt bdpos), show false, from annz anz, begin rewrite [↑reduce, if_neg annz, if_neg bnnz], apply prerat.eq, {apply div_gcd_eq_div_gcd H adpos bdpos}, {esimp, rewrite [gcd.comm, gcd.comm bn], apply div_gcd_eq_div_gcd_of_nonneg, rewrite [algebra.mul.comm, -H, algebra.mul.comm], apply annz, apply bnnz, apply le_of_lt adpos, apply le_of_lt bdpos}, end) end prerat /- the rationals -/ definition rat : Type.{1} := quot prerat.setoid notation `β„š` := rat local attribute prerat.setoid [instance] namespace rat /- operations -/ definition of_int [coercion] (i : β„€) : β„š := ⟦prerat.of_int i⟧ definition of_nat [coercion] (n : β„•) : β„š := nat.to.rat n definition of_num [coercion] [reducible] (n : num) : β„š := num.to.rat n protected definition prio := num.pred int.prio definition rat_has_zero [reducible] [instance] [priority rat.prio] : has_zero rat := has_zero.mk (of_int 0) definition rat_has_one [reducible] [instance] [priority rat.prio] : has_one rat := has_one.mk (of_int 1) theorem of_int_zero : of_int (0:int) = (0:rat) := rfl theorem of_int_one : of_int (1:int) = (1:rat) := rfl protected definition add : β„š β†’ β„š β†’ β„š := quot.liftβ‚‚ (Ξ» a b : prerat, ⟦prerat.add a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.add_equiv_add H1 H2)) protected definition mul : β„š β†’ β„š β†’ β„š := quot.liftβ‚‚ (Ξ» a b : prerat, ⟦prerat.mul a b⟧) (take a1 a2 b1 b2, assume H1 H2, quot.sound (prerat.mul_equiv_mul H1 H2)) protected definition neg : β„š β†’ β„š := quot.lift (Ξ» a : prerat, ⟦prerat.neg a⟧) (take a1 a2, assume H, quot.sound (prerat.neg_equiv_neg H)) protected definition inv : β„š β†’ β„š := quot.lift (Ξ» a : prerat, ⟦prerat.inv a⟧) (take a1 a2, assume H, quot.sound (prerat.inv_equiv_inv H)) definition reduce : β„š β†’ prerat := quot.lift (Ξ» a : prerat, prerat.reduce a) @prerat.reduce_eq_reduce definition num (a : β„š) : β„€ := prerat.num (reduce a) definition denom (a : β„š) : β„€ := prerat.denom (reduce a) theorem denom_pos (a : β„š): denom a > 0 := prerat.denom_pos (reduce a) definition rat_has_add [reducible] [instance] [priority rat.prio] : has_add rat := has_add.mk rat.add definition rat_has_mul [reducible] [instance] [priority rat.prio] : has_mul rat := has_mul.mk rat.mul definition rat_has_neg [reducible] [instance] [priority rat.prio] : has_neg rat := has_neg.mk rat.neg definition rat_has_inv [reducible] [instance] [priority rat.prio] : has_inv rat := has_inv.mk rat.inv protected definition sub [reducible] (a b : β„š) : rat := a + (-b) definition rat_has_sub [reducible] [instance] [priority rat.prio] : has_sub rat := has_sub.mk rat.sub lemma sub.def (a b : β„š) : a - b = a + (-b) := rfl /- properties -/ theorem of_int_add (a b : β„€) : of_int (a + b) = of_int a + of_int b := quot.sound (prerat.of_int_add a b) theorem of_int_mul (a b : β„€) : of_int (a * b) = of_int a * of_int b := quot.sound (prerat.of_int_mul a b) theorem of_int_neg (a : β„€) : of_int (-a) = -(of_int a) := quot.sound (prerat.of_int_neg a) theorem of_int_sub (a b : β„€) : of_int (a - b) = of_int a - of_int b := calc of_int (a - b) = of_int a + of_int (-b) : of_int_add ... = of_int a - of_int b : {of_int_neg b} theorem of_int.inj {a b : β„€} (H : of_int a = of_int b) : a = b := prerat.of_int.inj (quot.exact H) theorem eq_of_of_int_eq_of_int {a b : β„€} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : β„€) : of_int a = of_int b ↔ a = b := iff.intro eq_of_of_int_eq_of_int !congr_arg theorem of_nat_eq (a : β„•) : of_nat a = of_int (int.of_nat a) := rfl open nat theorem of_nat_add (a b : β„•) : of_nat (a + b) = of_nat a + of_nat b := by rewrite [of_nat_eq, int.of_nat_add, rat.of_int_add] theorem of_nat_mul (a b : β„•) : of_nat (a * b) = of_nat a * of_nat b := by rewrite [of_nat_eq, int.of_nat_mul, rat.of_int_mul] theorem of_nat_sub {a b : β„•} (H : a β‰₯ b) : of_nat (a - b) = of_nat a - of_nat b := begin rewrite of_nat_eq, rewrite [int.of_nat_sub H], rewrite [rat.of_int_sub] end theorem of_nat.inj {a b : β„•} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : β„•} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : β„•) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg protected theorem add_comm (a b : β„š) : a + b = b + a := quot.induction_onβ‚‚ a b (take u v, quot.sound !prerat.add.comm) protected theorem add_assoc (a b c : β„š) : a + b + c = a + (b + c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.add.assoc) protected theorem add_zero (a : β„š) : a + 0 = a := quot.induction_on a (take u, quot.sound !prerat.add_zero) protected theorem zero_add (a : β„š) : 0 + a = a := !rat.add_comm β–Έ !rat.add_zero protected theorem add_left_inv (a : β„š) : -a + a = 0 := quot.induction_on a (take u, quot.sound !prerat.add.left_inv) protected theorem mul_comm (a b : β„š) : a * b = b * a := quot.induction_onβ‚‚ a b (take u v, quot.sound !prerat.mul.comm) protected theorem mul_assoc (a b c : β„š) : a * b * c = a * (b * c) := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.assoc) protected theorem mul_one (a : β„š) : a * 1 = a := quot.induction_on a (take u, quot.sound !prerat.mul_one) protected theorem one_mul (a : β„š) : 1 * a = a := !rat.mul_comm β–Έ !rat.mul_one protected theorem left_distrib (a b c : β„š) : a * (b + c) = a * b + a * c := quot.induction_on₃ a b c (take u v w, quot.sound !prerat.mul.left_distrib) protected theorem right_distrib (a b c : β„š) : (a + b) * c = a * c + b * c := by rewrite [rat.mul_comm, rat.left_distrib, *rat.mul_comm c] protected theorem mul_inv_cancel {a : β„š} : a β‰  0 β†’ a * a⁻¹ = 1 := quot.induction_on a (take u, assume H, quot.sound (!prerat.mul_inv_cancel (assume H1, H (quot.sound H1)))) protected theorem inv_mul_cancel {a : β„š} (H : a β‰  0) : a⁻¹ * a = 1 := !rat.mul_comm β–Έ rat.mul_inv_cancel H protected theorem zero_ne_one : (0 : β„š) β‰  1 := assume H, prerat.zero_not_equiv_one (quot.exact H) definition has_decidable_eq [instance] : decidable_eq β„š := take a b, quot.rec_on_subsingletonβ‚‚ a b (take u v, if H : prerat.num u * prerat.denom v = prerat.num v * prerat.denom u then decidable.inl (quot.sound H) else decidable.inr (assume H1, H (quot.exact H1))) protected theorem inv_zero : inv 0 = (0 : β„š) := quot.sound (prerat.inv_zero' β–Έ !prerat.equiv.refl) theorem quot_reduce (a : β„š) : ⟦reduce a⟧ = a := quot.induction_on a (take u, quot.sound !prerat.reduce_equiv) section local attribute rat [reducible] theorem mul_denom (a : β„š) : a * denom a = num a := have H : ⟦reduce a⟧ * of_int (denom a) = of_int (num a), from quot.sound (!prerat.mul_denom_equiv), quot_reduce a β–Έ H end theorem coprime_num_denom (a : β„š) : coprime (num a) (denom a) := decidable.by_cases (suppose a = 0, by substvars) (quot.induction_on a (take u H, assert H' : prerat.num u β‰  0, from take H'', H (quot.sound (prerat.equiv_zero_of_num_eq_zero H'')), begin cases u with un ud udpos, rewrite [β–Έ*, ↑num, ↑denom, ↑reduce, ↑prerat.reduce, if_neg H', β–Έ*], have gcd un ud β‰  0, from ne_of_gt (!gcd_pos_of_ne_zero_left H'), apply coprime_div_gcd_div_gcd this end)) protected definition discrete_field [reducible] [trans_instance] : algebra.discrete_field rat := ⦃algebra.discrete_field, add := rat.add, add_assoc := rat.add_assoc, zero := 0, zero_add := rat.zero_add, add_zero := rat.add_zero, neg := rat.neg, add_left_inv := rat.add_left_inv, add_comm := rat.add_comm, mul := rat.mul, mul_assoc := rat.mul_assoc, one := 1, one_mul := rat.one_mul, mul_one := rat.mul_one, left_distrib := rat.left_distrib, right_distrib := rat.right_distrib, mul_comm := rat.mul_comm, mul_inv_cancel := @rat.mul_inv_cancel, inv_mul_cancel := @rat.inv_mul_cancel, zero_ne_one := rat.zero_ne_one, inv_zero := rat.inv_zero, has_decidable_eq := has_decidable_eq⦄ definition rat_has_div [instance] [reducible] [priority rat.prio] : has_div rat := has_div.mk has_div.div definition rat_has_pow_nat [instance] [reducible] [priority rat.prio] : has_pow_nat rat := has_pow_nat.mk has_pow_nat.pow_nat theorem eq_num_div_denom (a : β„š) : a = num a / denom a := have H : of_int (denom a) β‰  0, from assume H', ne_of_gt (denom_pos a) (of_int.inj H'), iff.mpr (!eq_div_iff_mul_eq H) (mul_denom a) theorem of_int_div {a b : β„€} (H : b ∣ a) : of_int (a / b) = of_int a / of_int b := decidable.by_cases (assume bz : b = 0, by rewrite [bz, int.div_zero, of_int_zero, algebra.div_zero]) (assume bnz : b β‰  0, have bnz' : of_int b β‰  0, from assume oibz, bnz (of_int.inj oibz), have H' : of_int (a / b) * of_int b = of_int a, from dvd.elim H (take c, assume Hc : a = b * c, by rewrite [Hc, !int.mul_div_cancel_left bnz, mul.comm]), iff.mpr (!eq_div_iff_mul_eq bnz') H') theorem of_nat_div {a b : β„•} (H : b ∣ a) : of_nat (a / b) = of_nat a / of_nat b := have H' : (int.of_nat b ∣ int.of_nat a), by rewrite [int.of_nat_dvd_of_nat_iff]; exact H, by+ rewrite [of_nat_eq, int.of_nat_div, of_int_div H'] theorem of_int_pow (a : β„€) (n : β„•) : of_int (a^n) = (of_int a)^n := begin induction n with n ih, apply eq.refl, rewrite [pow_succ, pow_succ, of_int_mul, ih] end theorem of_nat_pow (a : β„•) (n : β„•) : of_nat (a^n) = (of_nat a)^n := by rewrite [of_nat_eq, int.of_nat_pow, of_int_pow] end rat
90a66da238a64841946a89af04af42a1168a6028
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/measure_theory/measure_space.lean
2d065db49eb8599db17f11f19b98d3c6e2dca241
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
93,452
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 measure_theory.outer_measure import order.filter.countable_Inter import data.set.accumulate /-! # Measure spaces Given a measurable space `Ξ±`, a measure on `Ξ±` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `ΞΌ βˆ… = 0`; 2. `ΞΌ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `Ξ±` form a complete lattice, and are closed under scalar multiplication with `ennreal`. We introduce the following typeclasses for measures: * `probability_measure ΞΌ`: `ΞΌ univ = 1`; * `finite_measure ΞΌ`: `ΞΌ univ < ⊀`; * `sigma_finite ΞΌ`: there exists a countable collection of measurable sets that cover `univ` where `ΞΌ` is finite; * `locally_finite_measure ΞΌ` : `βˆ€ x, βˆƒ s ∈ 𝓝 x, ΞΌ s < ⊀`; * `has_no_atoms ΞΌ` : `βˆ€ x, ΞΌ {x} = 0`; possibly should be redefined as `βˆ€ s, 0 < ΞΌ s β†’ βˆƒ t βŠ† s, 0 < ΞΌ t ∧ ΞΌ t < ΞΌ s`. Given a measure, the null sets are the sets where `ΞΌ s = 0`, where `ΞΌ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `ΞΌ` as the measure on the least `Οƒ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `ΞΌ : measure Ξ±`, `ΞΌ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are CarathΓ©odory measurable. To prove that two measures are equal, there are multiple options: * `ext`: two measures are equal if they are equal on all measurable sets. * `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a Ο€-system generating the measurable sets, if the Ο€-system contains a spanning increasing sequence of sets where the measures take finite value (in particular the measures are Οƒ-finite). This is a special case of the more general `ext_of_generate_from_of_cover` * `ext_of_generate_finite`: two finite measures are equal if they are equal on a Ο€-system generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using `C βˆͺ {univ}`, but is easier to work with. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter function measurable_space open_locale classical topological_space big_operators filter variables {Ξ± Ξ² Ξ³ Ξ΄ ΞΉ : Type*} namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (Ξ± : Type*) [measurable_space Ξ±] extends outer_measure Ξ± := (m_Union ⦃f : β„• β†’ set α⦄ : (βˆ€ i, is_measurable (f i)) β†’ pairwise (disjoint on f) β†’ measure_of (⋃ i, f i) = (βˆ‘' i, measure_of (f i))) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun [measurable_space Ξ±] : has_coe_to_fun (measure Ξ±) := ⟨λ _, set Ξ± β†’ ennreal, Ξ» m, m.to_outer_measure⟩ section variables [measurable_space Ξ±] {ΞΌ μ₁ ΞΌβ‚‚ : measure Ξ±} {s s₁ sβ‚‚ t : set Ξ±} namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `βˆ…` to `0`. -/ def of_measurable (m : Ξ  (s : set Ξ±), is_measurable s β†’ ennreal) (m0 : m βˆ… is_measurable.empty = 0) (mU : βˆ€ {{f : β„• β†’ set Ξ±}} (h : βˆ€ i, is_measurable (f i)), pairwise (disjoint on f) β†’ m (⋃ i, f i) (is_measurable.Union h) = (βˆ‘' i, m (f i) (h i))) : measure Ξ± := { m_Union := Ξ» f hf hd, show induced_outer_measure m _ m0 (Union f) = βˆ‘' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {m : Ξ  (s : set Ξ±), is_measurable s β†’ ennreal} {m0 : m βˆ… is_measurable.empty = 0} {mU : βˆ€ {{f : β„• β†’ set Ξ±}} (h : βˆ€ i, is_measurable (f i)), pairwise (disjoint on f) β†’ m (⋃ i, f i) (is_measurable.Union h) = (βˆ‘' i, m (f i) (h i))} (s : set Ξ±) (hs : is_measurable s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective : injective (to_outer_measure : measure Ξ± β†’ outer_measure Ξ±) := Ξ» ⟨m₁, u₁, hβ‚βŸ© ⟨mβ‚‚, uβ‚‚, hβ‚‚βŸ© h, by { congr, exact h } @[ext] lemma ext (h : βˆ€ s, is_measurable s β†’ μ₁ s = ΞΌβ‚‚ s) : μ₁ = ΞΌβ‚‚ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff : μ₁ = ΞΌβ‚‚ ↔ βˆ€ s, is_measurable s β†’ μ₁ s = ΞΌβ‚‚ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = ΞΌ := rfl lemma to_outer_measure_apply (s : set Ξ±) : ΞΌ.to_outer_measure s = ΞΌ s := rfl lemma measure_eq_trim (s : set Ξ±) : ΞΌ s = ΞΌ.to_outer_measure.trim s := by rw ΞΌ.trimmed; refl lemma measure_eq_infi (s : set Ξ±) : ΞΌ s = β¨… t (st : s βŠ† t) (ht : is_measurable t), ΞΌ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl /-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a lemma next that only works for non-empty infima, in which case you can use `nonempty_measurable_superset`. -/ lemma measure_eq_infi' (ΞΌ : measure Ξ±) (s : set Ξ±) : ΞΌ s = β¨… t : { t // s βŠ† t ∧ is_measurable t}, ΞΌ t := by simp_rw [infi_subtype, infi_and, subtype.coe_mk, ← measure_eq_infi] lemma measure_eq_induced_outer_measure : ΞΌ s = induced_outer_measure (Ξ» s _, ΞΌ s) is_measurable.empty ΞΌ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : ΞΌ.to_outer_measure = induced_outer_measure (Ξ» s _, ΞΌ s) is_measurable.empty ΞΌ.empty := ΞΌ.trimmed.symm lemma measure_eq_extend (hs : is_measurable s) : ΞΌ s = extend (Ξ» t (ht : is_measurable t), ΞΌ t) s := by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact ΞΌ.m_Union } @[simp] lemma measure_empty : ΞΌ βˆ… = 0 := ΞΌ.empty lemma nonempty_of_measure_ne_zero (h : ΞΌ s β‰  0) : s.nonempty := ne_empty_iff_nonempty.1 $ Ξ» h', h $ h'.symm β–Έ measure_empty lemma measure_mono (h : s₁ βŠ† sβ‚‚) : ΞΌ s₁ ≀ ΞΌ sβ‚‚ := ΞΌ.mono h lemma measure_mono_null (h : s₁ βŠ† sβ‚‚) (hβ‚‚ : ΞΌ sβ‚‚ = 0) : ΞΌ s₁ = 0 := le_zero_iff_eq.1 $ hβ‚‚ β–Έ measure_mono h lemma measure_mono_top (h : s₁ βŠ† sβ‚‚) (h₁ : ΞΌ s₁ = ⊀) : ΞΌ sβ‚‚ = ⊀ := top_unique $ h₁ β–Έ measure_mono h lemma exists_is_measurable_superset_of_measure_eq_zero (h : ΞΌ s = 0) : βˆƒ t, s βŠ† t ∧ is_measurable t ∧ ΞΌ t = 0 := outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_is_measurable_superset_iff_measure_eq_zero : (βˆƒ t, s βŠ† t ∧ is_measurable t ∧ ΞΌ t = 0) ↔ ΞΌ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩ theorem measure_Union_le [encodable Ξ²] (s : Ξ² β†’ set Ξ±) : ΞΌ (⋃ i, s i) ≀ (βˆ‘' i, ΞΌ (s i)) := ΞΌ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set Ξ²} (hs : countable s) (f : Ξ² β†’ set Ξ±) : ΞΌ (⋃ b ∈ s, f b) ≀ βˆ‘' p : s, ΞΌ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset Ξ²) (f : Ξ² β†’ set Ξ±) : ΞΌ (⋃ b ∈ s, f b) ≀ βˆ‘ p in s, ΞΌ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_bUnion_lt_top {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : finite s) (hfin : βˆ€ i ∈ s, ΞΌ (f i) < ⊀) : ΞΌ (⋃ i ∈ s, f i) < ⊀ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null [encodable Ξ²] {s : Ξ² β†’ set Ξ±} : (βˆ€ i, ΞΌ (s i) = 0) β†’ ΞΌ (⋃ i, s i) = 0 := ΞΌ.to_outer_measure.Union_null lemma measure_Union_null_iff [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} : ΞΌ (⋃ i, s i) = 0 ↔ βˆ€ i, ΞΌ (s i) = 0 := ⟨λ h i, measure_mono_null (subset_Union _ _) h, measure_Union_null⟩ theorem measure_union_le (s₁ sβ‚‚ : set Ξ±) : ΞΌ (s₁ βˆͺ sβ‚‚) ≀ ΞΌ s₁ + ΞΌ sβ‚‚ := ΞΌ.to_outer_measure.union _ _ lemma measure_union_null : ΞΌ s₁ = 0 β†’ ΞΌ sβ‚‚ = 0 β†’ ΞΌ (s₁ βˆͺ sβ‚‚) = 0 := ΞΌ.to_outer_measure.union_null lemma measure_union_null_iff : ΞΌ (s₁ βˆͺ sβ‚‚) = 0 ↔ ΞΌ s₁ = 0 ∧ ΞΌ sβ‚‚ = 0:= ⟨λ h, ⟨measure_mono_null (subset_union_left _ _) h, measure_mono_null (subset_union_right _ _) h⟩, Ξ» h, measure_union_null h.1 h.2⟩ lemma measure_Union [encodable Ξ²] {f : Ξ² β†’ set Ξ±} (hn : pairwise (disjoint on f)) (h : βˆ€ i, is_measurable (f i)) : ΞΌ (⋃ i, f i) = (βˆ‘' i, ΞΌ (f i)) := begin rw [measure_eq_extend (is_measurable.Union h), extend_Union is_measurable.empty _ is_measurable.Union _ hn h], { simp [measure_eq_extend, h] }, { exact ΞΌ.empty }, { exact ΞΌ.m_Union } end lemma measure_union (hd : disjoint s₁ sβ‚‚) (h₁ : is_measurable s₁) (hβ‚‚ : is_measurable sβ‚‚) : ΞΌ (s₁ βˆͺ sβ‚‚) = ΞΌ s₁ + ΞΌ sβ‚‚ := begin rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [pairwise_disjoint_on_bool.2 hd, Ξ» b, bool.cases_on b hβ‚‚ h₁] end lemma measure_bUnion {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : βˆ€ b ∈ s, is_measurable (f b)) : ΞΌ (⋃ b ∈ s, f b) = βˆ‘' p : s, ΞΌ (f p) := begin haveI := hs.to_encodable, rw bUnion_eq_Union, exact measure_Union (hd.on_injective subtype.coe_injective $ Ξ» x, x.2) (Ξ» x, h x x.2) end lemma measure_sUnion {S : set (set Ξ±)} (hs : countable S) (hd : pairwise_on S disjoint) (h : βˆ€ s ∈ S, is_measurable s) : ΞΌ (⋃₀ S) = βˆ‘' s : S, ΞΌ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ΞΉ} {f : ΞΉ β†’ set Ξ±} (hd : pairwise_on ↑s (disjoint on f)) (hm : βˆ€ b ∈ s, is_measurable (f b)) : ΞΌ (⋃ b ∈ s, f b) = βˆ‘ p in s, ΞΌ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set Ξ²} (hs : countable s) {f : Ξ± β†’ Ξ²} (hf : βˆ€ y ∈ s, is_measurable (f ⁻¹' {y})) : (βˆ‘' b : s, ΞΌ (f ⁻¹' {↑b})) = ΞΌ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset Ξ²) {f : Ξ± β†’ Ξ²} (hf : βˆ€ y ∈ s, is_measurable (f ⁻¹' {y})) : βˆ‘ b in s, ΞΌ (f ⁻¹' {b}) = ΞΌ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.bUnion_preimage_singleton] lemma measure_diff (h : sβ‚‚ βŠ† s₁) (h₁ : is_measurable s₁) (hβ‚‚ : is_measurable sβ‚‚) (h_fin : ΞΌ sβ‚‚ < ⊀) : ΞΌ (s₁ \ sβ‚‚) = ΞΌ s₁ - ΞΌ sβ‚‚ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff hβ‚‚ (h₁.diff hβ‚‚), union_diff_cancel h] end lemma measure_compl (h₁ : is_measurable s) (h_fin : ΞΌ s < ⊀) : ΞΌ (sᢜ) = ΞΌ univ - ΞΌ s := by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) is_measurable.univ h₁ h_fin } lemma sum_measure_le_measure_univ {s : finset ΞΉ} {t : ΞΉ β†’ set Ξ±} (h : βˆ€ i ∈ s, is_measurable (t i)) (H : pairwise_on ↑s (disjoint on t)) : βˆ‘ i in s, ΞΌ (t i) ≀ ΞΌ (univ : set Ξ±) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ΞΉ β†’ set Ξ±} (hs : βˆ€ i, is_measurable (s i)) (H : pairwise (disjoint on s)) : (βˆ‘' i, ΞΌ (s i)) ≀ ΞΌ (univ : set Ξ±) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (Ξ» s, sum_measure_le_measure_univ (Ξ» i hi, hs i) (Ξ» i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `βˆ‘' i, ΞΌ (s i) > ΞΌ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (ΞΌ : measure Ξ±) {s : ΞΉ β†’ set Ξ±} (hs : βˆ€ i, is_measurable (s i)) (H : ΞΌ (univ : set Ξ±) < βˆ‘' i, ΞΌ (s i)) : βˆƒ i j (h : i β‰  j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact Ξ» i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `βˆ‘ i in s, ΞΌ (t i) > ΞΌ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (ΞΌ : measure Ξ±) {s : finset ΞΉ} {t : ΞΉ β†’ set Ξ±} (h : βˆ€ i ∈ s, is_measurable (t i)) (H : ΞΌ (univ : set Ξ±) < βˆ‘ i in s, ΞΌ (t i)) : βˆƒ (i ∈ s) (j ∈ s) (h : i β‰  j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact Ξ» i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- Continuity from below: the measure of the union of a directed sequence of measurable sets is the supremum of the measures. -/ lemma measure_Union_eq_supr [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (h : βˆ€ i, is_measurable (s i)) (hd : directed (βŠ†) s) : ΞΌ (⋃ i, s i) = ⨆ i, ΞΌ (s i) := begin by_cases hΞΉ : nonempty ΞΉ, swap, { simp only [supr_of_empty hΞΉ, Union], exact measure_empty }, resetI, refine le_antisymm _ (supr_le $ Ξ» i, measure_mono $ subset_Union _ _), have : βˆ€ n, is_measurable (disjointed (Ξ» n, ⋃ b ∈ encodable.decode2 ΞΉ n, s b) n) := is_measurable.disjointed (is_measurable.bUnion_decode2 h), rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this, ennreal.tsum_eq_supr_nat], simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (Ξ» n _, this n)], refine supr_le (Ξ» n, _), refine le_trans (_ : _ ≀ ΞΌ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ΞΉ k), s i)) _, exact measure_mono (bUnion_subset_bUnion_right (Ξ» k hk, disjointed_subset)), simp only [← finset.bUnion_option_to_finset, ← finset.bUnion_bind], generalize : (finset.range n).bind (Ξ» k, (encodable.decode2 ΞΉ k).to_finset) = t, rcases hd.finset_le t with ⟨i, hi⟩, exact le_supr_of_le i (measure_mono $ bUnion_subset hi) end lemma measure_bUnion_eq_supr {s : ΞΉ β†’ set Ξ±} {t : set ΞΉ} (ht : countable t) (h : βˆ€ i ∈ t, is_measurable (s i)) (hd : directed_on ((βŠ†) on s) t) : ΞΌ (⋃ i ∈ t, s i) = ⨆ i ∈ t, ΞΌ (s i) := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe, supr_subtype'], refl end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the infimum of the measures. -/ lemma measure_Inter_eq_infi [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (h : βˆ€ i, is_measurable (s i)) (hd : directed (βŠ‡) s) (hfin : βˆƒ i, ΞΌ (s i) < ⊀) : ΞΌ (β‹‚ i, s i) = (β¨… i, ΞΌ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr], { congr' 1, refine le_antisymm (supr_le_supr2 $ Ξ» i, _) (supr_le_supr $ Ξ» i, _), { rcases hd i k with ⟨j, hji, hjk⟩, use j, rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)], exact measure_mono (diff_subset_diff_right hji) }, { rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i), set.union_comm], exact measure_mono (diff_subset_iff.1 $ subset.refl _) } }, { exact Ξ» i, (h k).diff (h i) }, { exact hd.mono_comp _ (Ξ» _ _, diff_subset_diff_right) } end lemma measure_eq_inter_diff (hs : is_measurable s) (ht : is_measurable t) : ΞΌ s = ΞΌ (s ∩ t) + ΞΌ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma measure_union_add_inter (hs : is_measurable s) (ht : is_measurable t) : ΞΌ (s βˆͺ t) + ΞΌ (s ∩ t) = ΞΌ s + ΞΌ t := by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right, union_diff_right, measure_eq_inter_diff hs ht], ac_refl } /-- Continuity from below: the measure of the union of an increasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Union {s : β„• β†’ set Ξ±} (hs : βˆ€ n, is_measurable (s n)) (hm : monotone s) : tendsto (ΞΌ ∘ s) at_top (𝓝 (ΞΌ (⋃ n, s n))) := begin rw measure_Union_eq_supr hs (directed_of_sup hm), exact tendsto_at_top_supr (assume n m hnm, measure_mono $ hm hnm) end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Inter {s : β„• β†’ set Ξ±} (hs : βˆ€ n, is_measurable (s n)) (hm : βˆ€ ⦃n m⦄, n ≀ m β†’ s m βŠ† s n) (hf : βˆƒ i, ΞΌ (s i) < ⊀) : tendsto (ΞΌ ∘ s) at_top (𝓝 (ΞΌ (β‹‚ n, s n))) := begin rw measure_Inter_eq_infi hs (directed_of_sup hm) hf, exact tendsto_at_top_infi (assume n m hnm, measure_mono $ hm hnm), end /-- One direction of the Borel-Cantelli lemma: if (sα΅’) is a sequence of measurable sets such that βˆ‘ ΞΌ sα΅’ exists, then the limit superior of the sα΅’ is a null set. -/ lemma measure_limsup_eq_zero {s : β„• β†’ set Ξ±} (hs : βˆ€ i, is_measurable (s i)) (hs' : (βˆ‘' i, ΞΌ (s i)) β‰  ⊀) : ΞΌ (limsup at_top s) = 0 := begin rw limsup_eq_infi_supr_of_nat', -- We will show that both `ΞΌ (β¨… n, ⨆ i, s (i + n))` and `0` are the limit of `ΞΌ (βŠ” i, s (i + n))` -- as `n` tends to infinity. For the former, we use continuity from above. refine tendsto_nhds_unique (tendsto_measure_Inter (Ξ» i, is_measurable.Union (Ξ» b, hs (b + i))) _ ⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _, { intros n m hnm x, simp only [set.mem_Union], exact Ξ» ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ }, { -- For the latter, notice that, `ΞΌ (⨆ i, s (i + n)) ≀ βˆ‘' s (i + n)`. Since the right hand side -- converges to `0` by hypothesis, so does the former and the proof is complete. exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (ennreal.tendsto_sum_nat_add (ΞΌ ∘ s) hs') (eventually_of_forall (by simp only [forall_const, zero_le])) (eventually_of_forall (Ξ» i, measure_Union_le _))) } end lemma measure_if {x : Ξ²} {t : set Ξ²} {s : set Ξ±} {ΞΌ : measure Ξ±} : ΞΌ (if x ∈ t then s else βˆ…) = indicator t (Ξ» _, ΞΌ s) x := by { split_ifs; simp [h] } end section outer_measure variables [ms : measurable_space Ξ±] {s t : set Ξ±} include ms /-- Obtain a measure by giving an outer measure where all sets in the Οƒ-algebra are CarathΓ©odory measurable. -/ def outer_measure.to_measure (m : outer_measure Ξ±) (h : ms ≀ m.caratheodory) : measure Ξ± := measure.of_measurable (Ξ» s _, m s) m.empty (Ξ» f hf hd, m.Union_eq_of_caratheodory (Ξ» i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory (ΞΌ : measure Ξ±) : ms ≀ ΞΌ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_induced_outer_measure, refine outer_measure.of_function_caratheodory (Ξ» t, le_infi $ Ξ» ht, _), rw [← measure_eq_extend (ht.inter hs), ← measure_eq_extend (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact Ξ» x ⟨⟨_, hβ‚βŸ©, _, hβ‚‚βŸ©, hβ‚‚ h₁ end @[simp] lemma to_measure_to_outer_measure (m : outer_measure Ξ±) (h : ms ≀ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply (m : outer_measure Ξ±) (h : ms ≀ m.caratheodory) {s : set Ξ±} (hs : is_measurable s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply (m : outer_measure Ξ±) (h : ms ≀ m.caratheodory) (s : set Ξ±) : m s ≀ m.to_measure h s := m.le_trim s @[simp] lemma to_outer_measure_to_measure {ΞΌ : measure Ξ±} : ΞΌ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = ΞΌ := measure.ext $ Ξ» s, ΞΌ.to_outer_measure.trim_eq end outer_measure variables [measurable_space Ξ±] [measurable_space Ξ²] [measurable_space Ξ³] variables {ΞΌ μ₁ ΞΌβ‚‚ Ξ½ Ξ½' ν₁ Ξ½β‚‚ : measure Ξ±} {s s' t : set Ξ±} namespace measure protected lemma caratheodory (ΞΌ : measure Ξ±) (hs : is_measurable s) : ΞΌ (t ∩ s) + ΞΌ (t \ s) = ΞΌ t := (le_to_outer_measure_caratheodory ΞΌ s hs t).symm /-! ### The `ennreal`-module of measures -/ instance : has_zero (measure Ξ±) := ⟨{ to_outer_measure := 0, m_Union := Ξ» f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure Ξ±).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure Ξ±) = 0 := rfl lemma eq_zero_of_not_nonempty (h : Β¬nonempty Ξ±) (ΞΌ : measure Ξ±) : ΞΌ = 0 := ext $ Ξ» s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure Ξ±) := ⟨0⟩ instance : has_add (measure Ξ±) := ⟨λ μ₁ ΞΌβ‚‚, { to_outer_measure := μ₁.to_outer_measure + ΞΌβ‚‚.to_outer_measure, m_Union := Ξ» s hs hd, show μ₁ (⋃ i, s i) + ΞΌβ‚‚ (⋃ i, s i) = βˆ‘' i, μ₁ (s i) + ΞΌβ‚‚ (s i), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, ΞΌβ‚‚.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ ΞΌβ‚‚ : measure Ξ±) : (μ₁ + ΞΌβ‚‚).to_outer_measure = μ₁.to_outer_measure + ΞΌβ‚‚.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ ΞΌβ‚‚ : measure Ξ±) : ⇑(μ₁ + ΞΌβ‚‚) = μ₁ + ΞΌβ‚‚ := rfl theorem add_apply (μ₁ ΞΌβ‚‚ : measure Ξ±) (s : set Ξ±) : (μ₁ + ΞΌβ‚‚) s = μ₁ s + ΞΌβ‚‚ s := rfl instance add_comm_monoid : add_comm_monoid (measure Ξ±) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ennreal (measure Ξ±) := ⟨λ c ΞΌ, { to_outer_measure := c β€’ ΞΌ.to_outer_measure, m_Union := Ξ» s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, ΞΌ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ennreal) (ΞΌ : measure Ξ±) : (c β€’ ΞΌ).to_outer_measure = c β€’ ΞΌ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ennreal) (ΞΌ : measure Ξ±) : ⇑(c β€’ ΞΌ) = c β€’ ΞΌ := rfl theorem smul_apply (c : ennreal) (ΞΌ : measure Ξ±) (s : set Ξ±) : (c β€’ ΞΌ) s = c * ΞΌ s := rfl instance : semimodule ennreal (measure Ξ±) := injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure /-! ### The complete lattice of measures -/ instance : partial_order (measure Ξ±) := { le := Ξ» m₁ mβ‚‚, βˆ€ s, is_measurable s β†’ m₁ s ≀ mβ‚‚ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ mβ‚‚ m₃ h₁ hβ‚‚ s hs, le_trans (h₁ s hs) (hβ‚‚ s hs), le_antisymm := assume m₁ mβ‚‚ h₁ hβ‚‚, ext $ assume s hs, le_antisymm (h₁ s hs) (hβ‚‚ s hs) } theorem le_iff : μ₁ ≀ ΞΌβ‚‚ ↔ βˆ€ s, is_measurable s β†’ μ₁ s ≀ ΞΌβ‚‚ s := iff.rfl theorem to_outer_measure_le : μ₁.to_outer_measure ≀ ΞΌβ‚‚.to_outer_measure ↔ μ₁ ≀ ΞΌβ‚‚ := by rw [← ΞΌβ‚‚.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' : μ₁ ≀ ΞΌβ‚‚ ↔ βˆ€ s, μ₁ s ≀ ΞΌβ‚‚ s := to_outer_measure_le.symm theorem lt_iff : ΞΌ < Ξ½ ↔ ΞΌ ≀ Ξ½ ∧ βˆƒ s, is_measurable s ∧ ΞΌ s < Ξ½ s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' : ΞΌ < Ξ½ ↔ ΞΌ ≀ Ξ½ ∧ βˆƒ s, ΞΌ s < Ξ½ s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] -- TODO: add typeclasses for `βˆ€ c, monotone ((*) c)` and `βˆ€ c, monotone ((+) c)` protected lemma add_le_add_left (Ξ½ : measure Ξ±) (hΞΌ : μ₁ ≀ ΞΌβ‚‚) : Ξ½ + μ₁ ≀ Ξ½ + ΞΌβ‚‚ := Ξ» s hs, add_le_add_left (hΞΌ s hs) _ protected lemma add_le_add_right (hΞΌ : μ₁ ≀ ΞΌβ‚‚) (Ξ½ : measure Ξ±) : μ₁ + Ξ½ ≀ ΞΌβ‚‚ + Ξ½ := Ξ» s hs, add_le_add_right (hΞΌ s hs) _ protected lemma add_le_add (hΞΌ : μ₁ ≀ ΞΌβ‚‚) (hΞ½ : ν₁ ≀ Ξ½β‚‚) : μ₁ + ν₁ ≀ ΞΌβ‚‚ + Ξ½β‚‚ := Ξ» s hs, add_le_add (hΞΌ s hs) (hΞ½ s hs) protected lemma le_add_left (h : ΞΌ ≀ Ξ½) : ΞΌ ≀ Ξ½' + Ξ½ := Ξ» s hs, le_add_left (h s hs) protected lemma le_add_right (h : ΞΌ ≀ Ξ½) : ΞΌ ≀ Ξ½ + Ξ½' := Ξ» s hs, le_add_right (h s hs) section Inf variables {m : set (measure Ξ±)} lemma Inf_caratheodory (s : set Ξ±) (hs : is_measurable s) : (Inf (to_outer_measure '' m)).caratheodory.is_measurable' s := begin rw [outer_measure.Inf_eq_bounded_by_Inf_gen], refine outer_measure.bounded_by_caratheodory (Ξ» t, _), simp only [outer_measure.Inf_gen, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], intros ΞΌ hΞΌ u htu hu, have hm : βˆ€ {s t}, s βŠ† t β†’ outer_measure.Inf_gen (to_outer_measure '' m) s ≀ ΞΌ t, { intros s t hst, rw [outer_measure.Inf_gen_def], refine infi_le_of_le (ΞΌ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hΞΌ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure Ξ±) := ⟨λ m, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma measure_Inf_le (h : ΞΌ ∈ m) : Inf m ≀ ΞΌ := have Inf (to_outer_measure '' m) ≀ ΞΌ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma measure_le_Inf (h : βˆ€ ΞΌ' ∈ m, ΞΌ ≀ ΞΌ') : ΞΌ ≀ Inf m := have ΞΌ.to_outer_measure ≀ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume ΞΌ hΞΌ, to_outer_measure_le.2 $ h _ hΞΌ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure Ξ±) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊀ : outer_measure Ξ±).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊀ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure Ξ±) (Ξ» ms, ⟨λ _, measure_Inf_le, Ξ» _, measure_le_Inf⟩) } end Inf protected lemma zero_le (ΞΌ : measure Ξ±) : 0 ≀ ΞΌ := bot_le lemma le_zero_iff_eq' : ΞΌ ≀ 0 ↔ ΞΌ = 0 := ΞΌ.zero_le.le_iff_eq @[simp] lemma measure_univ_eq_zero : ΞΌ univ = 0 ↔ ΞΌ = 0 := ⟨λ h, bot_unique $ Ξ» s hs, trans_rel_left (≀) (measure_mono (subset_univ s)) h, Ξ» h, h.symm β–Έ rfl⟩ /-! ### Pushforward and pullback -/ /-- Lift a linear map between `outer_measure` spaces such that for each measure `ΞΌ` every measurable set is caratheodory-measurable w.r.t. `f ΞΌ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure Ξ± β†’β‚—[ennreal] outer_measure Ξ²) (hf : βˆ€ ΞΌ : measure Ξ±, β€Ή_β€Ί ≀ (f ΞΌ.to_outer_measure).caratheodory) : measure Ξ± β†’β‚—[ennreal] measure Ξ² := { to_fun := Ξ» ΞΌ, (f ΞΌ.to_outer_measure).to_measure (hf ΞΌ), map_add' := Ξ» μ₁ ΞΌβ‚‚, ext $ Ξ» s hs, by simp [hs], map_smul' := Ξ» c ΞΌ, ext $ Ξ» s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure Ξ± β†’β‚—[ennreal] outer_measure Ξ²} (hf) {s : set Ξ²} (hs : is_measurable s) : lift_linear f hf ΞΌ s = f ΞΌ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure Ξ± β†’β‚—[ennreal] outer_measure Ξ²} (hf) (s : set Ξ²) : f ΞΌ.to_outer_measure s ≀ lift_linear f hf ΞΌ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : Ξ± β†’ Ξ²) : measure Ξ± β†’β‚—[ennreal] measure Ξ² := if hf : measurable f then lift_linear (outer_measure.map f) $ Ξ» ΞΌ s hs t, le_to_outer_measure_caratheodory ΞΌ _ (hf hs) (f ⁻¹' t) else 0 /-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see `measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/ @[simp] theorem map_apply {f : Ξ± β†’ Ξ²} (hf : measurable f) {s : set Ξ²} (hs : is_measurable s) : map f ΞΌ s = ΞΌ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id ΞΌ = ΞΌ := ext $ Ξ» s, map_apply measurable_id lemma map_map {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : measurable g) (hf : measurable f) : map g (map f ΞΌ) = map (g ∘ f) ΞΌ := ext $ Ξ» s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] lemma map_mono {f : Ξ± β†’ Ξ²} (hf : measurable f) (h : ΞΌ ≀ Ξ½) : map f ΞΌ ≀ map f Ξ½ := Ξ» s hs, by simp [hf, hs, h _ (hf hs)] /-- Even if `s` is not measurable, we can bound `map f ΞΌ s` from below. See also `measurable_equiv.map_apply`. -/ theorem le_map_apply {f : Ξ± β†’ Ξ²} (hf : measurable f) (s : set Ξ²) : ΞΌ (f ⁻¹' s) ≀ map f ΞΌ s := begin rw [measure_eq_infi' (map f ΞΌ)], refine le_infi _, rintro ⟨t, hst, ht⟩, convert measure_mono (preimage_mono hst), exact map_apply hf ht end /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f ΞΌ s = ΞΌ (f '' s)`. -/ def comap (f : Ξ± β†’ Ξ²) : measure Ξ² β†’β‚—[ennreal] measure Ξ± := if hf : injective f ∧ βˆ€ s, is_measurable s β†’ is_measurable (f '' s) then lift_linear (outer_measure.comap f) $ Ξ» ΞΌ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : Ξ± β†’ Ξ²) (hfi : injective f) (hf : βˆ€ s, is_measurable s β†’ is_measurable (f '' s)) (ΞΌ : measure Ξ²) (hs : is_measurable s) : comap f ΞΌ s = ΞΌ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-! ### Restricting a measure -/ /-- Restrict a measure `ΞΌ` to a set `s` as an `ennreal`-linear map. -/ def restrictβ‚— (s : set Ξ±) : measure Ξ± β†’β‚—[ennreal] measure Ξ± := lift_linear (outer_measure.restrict s) $ Ξ» ΞΌ s' hs' t, begin suffices : ΞΌ (s ∩ t) = ΞΌ (s ∩ t ∩ s') + ΞΌ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `ΞΌ` to a set `s`. -/ def restrict (ΞΌ : measure Ξ±) (s : set Ξ±) : measure Ξ± := restrictβ‚— s ΞΌ @[simp] lemma restrictβ‚—_apply (s : set Ξ±) (ΞΌ : measure Ξ±) : restrictβ‚— s ΞΌ = ΞΌ.restrict s := rfl @[simp] lemma restrict_apply (ht : is_measurable t) : ΞΌ.restrict s t = ΞΌ (t ∩ s) := by simp [← restrictβ‚—_apply, restrictβ‚—, ht] lemma restrict_apply_univ (s : set Ξ±) : ΞΌ.restrict s univ = ΞΌ s := by rw [restrict_apply is_measurable.univ, set.univ_inter] lemma le_restrict_apply (s t : set Ξ±) : ΞΌ (t ∩ s) ≀ ΞΌ.restrict s t := by { rw [restrict, restrictβ‚—], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (ΞΌ Ξ½ : measure Ξ±) (s : set Ξ±) : (ΞΌ + Ξ½).restrict s = ΞΌ.restrict s + Ξ½.restrict s := (restrictβ‚— s).map_add ΞΌ Ξ½ @[simp] lemma restrict_zero (s : set Ξ±) : (0 : measure Ξ±).restrict s = 0 := (restrictβ‚— s).map_zero @[simp] lemma restrict_smul (c : ennreal) (ΞΌ : measure Ξ±) (s : set Ξ±) : (c β€’ ΞΌ).restrict s = c β€’ ΞΌ.restrict s := (restrictβ‚— s).map_smul c ΞΌ @[simp] lemma restrict_restrict (hs : is_measurable s) : (ΞΌ.restrict t).restrict s = ΞΌ.restrict (s ∩ t) := ext $ Ξ» u hu, by simp [*, set.inter_assoc] lemma restrict_apply_eq_zero (ht : is_measurable t) : ΞΌ.restrict s t = 0 ↔ ΞΌ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma restrict_apply_eq_zero' (hs : is_measurable s) : ΞΌ.restrict s t = 0 ↔ ΞΌ (t ∩ s) = 0 := begin refine ⟨λ h, le_zero_iff_eq.1 (h β–Έ le_restrict_apply _ _), Ξ» h, _⟩, rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_eq_zero : ΞΌ.restrict s = 0 ↔ ΞΌ s = 0 := by rw [← measure_univ_eq_zero, restrict_apply_univ] @[simp] lemma restrict_empty : ΞΌ.restrict βˆ… = 0 := ext $ Ξ» s hs, by simp [hs] @[simp] lemma restrict_univ : ΞΌ.restrict univ = ΞΌ := ext $ Ξ» s hs, by simp [hs] lemma restrict_union_apply (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s) (hs' : is_measurable s') (ht : is_measurable t) : ΞΌ.restrict (s βˆͺ s') t = ΞΌ.restrict s t + ΞΌ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union (h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) : ΞΌ.restrict (s βˆͺ t) = ΞΌ.restrict s + ΞΌ.restrict t := ext $ Ξ» t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_add_inter (hs : is_measurable s) (ht : is_measurable t) : ΞΌ.restrict (s βˆͺ t) + ΞΌ.restrict (s ∩ t) = ΞΌ.restrict s + ΞΌ.restrict t := begin ext1 u hu, simp only [add_apply, restrict_apply hu, inter_union_distrib_left], convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3, rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self] end @[simp] lemma restrict_add_restrict_compl (hs : is_measurable s) : ΞΌ.restrict s + ΞΌ.restrict sᢜ = ΞΌ := by rw [← restrict_union disjoint_compl_right hs hs.compl, union_compl_self, restrict_univ] @[simp] lemma restrict_compl_add_restrict (hs : is_measurable s) : ΞΌ.restrict sᢜ + ΞΌ.restrict s = ΞΌ := by rw [add_comm, restrict_add_restrict_compl hs] lemma restrict_union_le (s s' : set Ξ±) : ΞΌ.restrict (s βˆͺ s') ≀ ΞΌ.restrict s + ΞΌ.restrict s' := begin intros t ht, suffices : ΞΌ (t ∩ s βˆͺ t ∩ s') ≀ ΞΌ (t ∩ s) + ΞΌ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (hd : pairwise (disjoint on s)) (hm : βˆ€ i, is_measurable (s i)) {t : set Ξ±} (ht : is_measurable t) : ΞΌ.restrict (⋃ i, s i) t = βˆ‘' i, ΞΌ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (Ξ» i j hij, (hd i j hij).mono inf_le_right inf_le_right) (Ξ» i, ht.inter (hm i)) end lemma restrict_Union_apply_eq_supr [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (hm : βˆ€ i, is_measurable (s i)) (hd : directed (βŠ†) s) {t : set Ξ±} (ht : is_measurable t) : ΞΌ.restrict (⋃ i, s i) t = ⨆ i, ΞΌ.restrict (s i) t := begin simp only [restrict_apply ht, inter_Union], rw [measure_Union_eq_supr], exacts [Ξ» i, ht.inter (hm i), hd.mono_comp _ (Ξ» s₁ sβ‚‚, inter_subset_inter_right _)] end lemma restrict_map {f : Ξ± β†’ Ξ²} (hf : measurable f) {s : set Ξ²} (hs : is_measurable s) : (map f ΞΌ).restrict s = map f (ΞΌ.restrict $ f ⁻¹' s) := ext $ Ξ» t ht, by simp [*, hf ht] lemma map_comap_subtype_coe (hs : is_measurable s) : (map (coe : s β†’ Ξ±)).comp (comap coe) = restrictβ‚— s := linear_map.ext $ Ξ» ΞΌ, ext $ Ξ» t ht, by rw [restrictβ‚—_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s β†’ Ξ±) subtype.val_injective (Ξ» _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s βŠ† s') ⦃μ Ξ½ : measure α⦄ (hΞΌΞ½ : ΞΌ ≀ Ξ½) : ΞΌ.restrict s ≀ Ξ½.restrict s' := assume t ht, calc ΞΌ.restrict s t = ΞΌ (t ∩ s) : restrict_apply ht ... ≀ ΞΌ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≀ Ξ½ (t ∩ s') : le_iff'.1 hΞΌΞ½ (t ∩ s') ... = Ξ½.restrict s' t : (restrict_apply ht).symm lemma restrict_le_self : ΞΌ.restrict s ≀ ΞΌ := assume t ht, calc ΞΌ.restrict s t = ΞΌ (t ∩ s) : restrict_apply ht ... ≀ ΞΌ t : measure_mono $ inter_subset_left t s lemma restrict_congr_meas (hs : is_measurable s) : ΞΌ.restrict s = Ξ½.restrict s ↔ βˆ€ t βŠ† s, is_measurable t β†’ ΞΌ t = Ξ½ t := ⟨λ H t hts ht, by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], Ξ» H, ext $ Ξ» t ht, by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩ lemma restrict_congr_mono (hs : s βŠ† t) (hm : is_measurable s) (h : ΞΌ.restrict t = Ξ½.restrict t) : ΞΌ.restrict s = Ξ½.restrict s := by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm] /-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all measurable subsets of `s βˆͺ t`. -/ lemma restrict_union_congr (hsm : is_measurable s) (htm : is_measurable t) : ΞΌ.restrict (s βˆͺ t) = Ξ½.restrict (s βˆͺ t) ↔ ΞΌ.restrict s = Ξ½.restrict s ∧ ΞΌ.restrict t = Ξ½.restrict t := begin refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h, restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩, simp only [restrict_congr_meas, hsm, htm, hsm.union htm], rintros ⟨hs, ht⟩ u hu hum, rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm, hs _ (inter_subset_right _ _) (hum.inter hsm), ht _ (diff_subset_iff.2 hu) (hum.diff hsm)] end lemma restrict_finset_bUnion_congr {s : finset ΞΉ} {t : ΞΉ β†’ set Ξ±} (htm : βˆ€ i ∈ s, is_measurable (t i)) : ΞΌ.restrict (⋃ i ∈ s, t i) = Ξ½.restrict (⋃ i ∈ s, t i) ↔ βˆ€ i ∈ s, ΞΌ.restrict (t i) = Ξ½.restrict (t i) := begin induction s using finset.induction_on with i s hi hs, { simp }, simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊒, simp only [finset.bUnion_insert, ← hs htm.2], exact restrict_union_congr htm.1 (s.is_measurable_bUnion htm.2) end lemma restrict_Union_congr [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (hm : βˆ€ i, is_measurable (s i)) : ΞΌ.restrict (⋃ i, s i) = Ξ½.restrict (⋃ i, s i) ↔ βˆ€ i, ΞΌ.restrict (s i) = Ξ½.restrict (s i) := begin refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, Ξ» h, _⟩, ext1 t ht, have M : βˆ€ t : finset ΞΉ, is_measurable (⋃ i ∈ t, s i) := Ξ» t, t.is_measurable_bUnion (Ξ» i _, hm i), have D : directed (βŠ†) (Ξ» t : finset ΞΉ, ⋃ i ∈ t, s i) := directed_of_sup (Ξ» t₁ tβ‚‚ ht, bUnion_subset_bUnion_left ht), rw [Union_eq_Union_finset], simp only [restrict_Union_apply_eq_supr M D ht, (restrict_finset_bUnion_congr (Ξ» i hi, hm i)).2 (Ξ» i hi, h i)], end lemma restrict_bUnion_congr {s : set ΞΉ} {t : ΞΉ β†’ set Ξ±} (hc : countable s) (htm : βˆ€ i ∈ s, is_measurable (t i)) : ΞΌ.restrict (⋃ i ∈ s, t i) = Ξ½.restrict (⋃ i ∈ s, t i) ↔ βˆ€ i ∈ s, ΞΌ.restrict (t i) = Ξ½.restrict (t i) := begin simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊒, haveI := hc.to_encodable, exact restrict_Union_congr htm end lemma restrict_sUnion_congr {S : set (set Ξ±)} (hc : countable S) (hm : βˆ€ s ∈ S, is_measurable s) : ΞΌ.restrict (⋃₀ S) = Ξ½.restrict (⋃₀ S) ↔ βˆ€ s ∈ S, ΞΌ.restrict s = Ξ½.restrict s := by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm] /-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a restrict on measures and the RHS has a restrict on outer measures. -/ lemma restrict_to_outer_measure_eq_to_outer_measure_restrict (h : is_measurable s) : (ΞΌ.restrict s).to_outer_measure = outer_measure.restrict s ΞΌ.to_outer_measure := by simp_rw [restrict, restrictβ‚—, lift_linear, linear_map.coe_mk, to_measure_to_outer_measure, outer_measure.restrict_trim h, ΞΌ.trimmed] /-- This lemma shows that `Inf` and `restrict` commute for measures. -/ lemma restrict_Inf_eq_Inf_restrict {m : set (measure Ξ±)} (hm : m.nonempty) (ht : is_measurable t) : (Inf m).restrict t = Inf ((Ξ» ΞΌ : measure Ξ±, ΞΌ.restrict t) '' m) := begin ext1 s hs, simp_rw [Inf_apply hs, restrict_apply hs, Inf_apply (is_measurable.inter hs ht), set.image_image, restrict_to_outer_measure_eq_to_outer_measure_restrict ht, ← set.image_image _ to_outer_measure, ← outer_measure.restrict_Inf_eq_Inf_restrict _ (hm.image _), outer_measure.restrict_apply] end /-! ### Extensionality results -/ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `Union`). -/ lemma ext_iff_of_Union_eq_univ [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (hm : βˆ€ i, is_measurable (s i)) (hs : (⋃ i, s i) = univ) : ΞΌ = Ξ½ ↔ βˆ€ i, ΞΌ.restrict (s i) = Ξ½.restrict (s i) := by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `bUnion`). -/ lemma ext_iff_of_bUnion_eq_univ {S : set ΞΉ} {s : ΞΉ β†’ set Ξ±} (hc : countable S) (hm : βˆ€ i ∈ S, is_measurable (s i)) (hs : (⋃ i ∈ S, s i) = univ) : ΞΌ = Ξ½ ↔ βˆ€ i ∈ S, ΞΌ.restrict (s i) = Ξ½.restrict (s i) := by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `sUnion`). -/ lemma ext_iff_of_sUnion_eq_univ {S : set (set Ξ±)} (hc : countable S) (hm : βˆ€ s ∈ S, is_measurable s) (hs : (⋃₀ S) = univ) : ΞΌ = Ξ½ ↔ βˆ€ s ∈ S, ΞΌ.restrict s = Ξ½.restrict s := ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ lemma ext_of_generate_from_of_cover {S T : set (set Ξ±)} (h_gen : β€Ή_β€Ί = generate_from S) (hc : countable T) (h_inter : is_pi_system S) (hm : βˆ€ t ∈ T, is_measurable t) (hU : ⋃₀ T = univ) (htop : βˆ€ t ∈ T, ΞΌ t < ⊀) (ST_eq : βˆ€ (t ∈ T) (s ∈ S), ΞΌ (s ∩ t) = Ξ½ (s ∩ t)) (T_eq : βˆ€ t ∈ T, ΞΌ t = Ξ½ t) : ΞΌ = Ξ½ := begin refine ext_of_sUnion_eq_univ hc hm hU (Ξ» t ht, _), ext1 u hu, simp only [restrict_apply hu], refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu, { simp only [set.empty_inter, measure_empty] }, { intros v hv hvt, have := T_eq t ht, rw [set.inter_comm] at hvt ⊒, rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt, ennreal.add_right_inj] at this, exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) }, { intros f hfd hfm h_eq, have : pairwise (disjoint on Ξ» n, f n ∩ t) := Ξ» m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _), simp only [Union_inter, measure_Union this (Ξ» n, is_measurable.inter (hfm n) (hm t ht)), h_eq] } end /-- Two measures are equal if they are equal on the Ο€-system generating the Οƒ-algebra, and they are both finite on a increasing spanning sequence of sets in the Ο€-system. This lemma is formulated using `sUnion`. -/ lemma ext_of_generate_from_of_cover_subset {S T : set (set Ξ±)} (h_gen : β€Ή_β€Ί = generate_from S) (h_inter : is_pi_system S) (h_sub : T βŠ† S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : βˆ€ s ∈ T, ΞΌ s < ⊀) (h_eq : βˆ€ s ∈ S, ΞΌ s = Ξ½ s) : ΞΌ = Ξ½ := begin refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (Ξ» t ht, h_eq t (h_sub ht)), { intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) }, { intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H, { simp only [H, measure_empty] }, { exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } } end /-- Two measures are equal if they are equal on the Ο€-system generating the Οƒ-algebra, and they are both finite on a increasing spanning sequence of sets in the Ο€-system. This lemma is formulated using `Union`. `finite_spanning_sets_in.ext` is a reformulation of this lemma. -/ lemma ext_of_generate_from_of_Union (C : set (set Ξ±)) (B : β„• β†’ set Ξ±) (hA : β€Ή_β€Ί = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ) (h2B : βˆ€ i, B i ∈ C) (hΞΌB : βˆ€ i, ΞΌ (B i) < ⊀) (h_eq : βˆ€ s ∈ C, ΞΌ s = Ξ½ s) : ΞΌ = Ξ½ := begin refine ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq, { rintro _ ⟨i, rfl⟩, apply h2B }, { rintro _ ⟨i, rfl⟩, apply hΞΌB } end /-- The dirac measure. -/ def dirac (a : Ξ±) : measure Ξ± := (outer_measure.dirac a).to_measure (by simp) lemma dirac_apply' (a : Ξ±) (hs : is_measurable s) : dirac a s = ⨆ h : a ∈ s, 1 := to_measure_apply _ _ hs @[simp] lemma dirac_apply (a : Ξ±) (hs : is_measurable s) : dirac a s = s.indicator 1 a := (dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] } lemma dirac_apply_of_mem {a : Ξ±} (h : a ∈ s) : dirac a s = 1 := begin rw [measure_eq_infi, infi_subtype', infi_subtype'], convert infi_const, { ext1 ⟨⟨t, hst⟩, ht⟩, dsimp only [subtype.coe_mk] at *, simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] }, { exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ } end /-- Sum of an indexed family of measures. -/ def sum (f : ΞΉ β†’ measure Ξ±) : measure Ξ± := (outer_measure.sum (Ξ» i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (Ξ» i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) @[simp] lemma sum_apply (f : ΞΉ β†’ measure Ξ±) {s : set Ξ±} (hs : is_measurable s) : sum f s = βˆ‘' i, f i s := to_measure_apply _ _ hs lemma le_sum (ΞΌ : ΞΉ β†’ measure Ξ±) (i : ΞΉ) : ΞΌ i ≀ sum ΞΌ := Ξ» s hs, by simp only [sum_apply ΞΌ hs, ennreal.le_tsum i] lemma restrict_Union [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} (hd : pairwise (disjoint on s)) (hm : βˆ€ i, is_measurable (s i)) : ΞΌ.restrict (⋃ i, s i) = sum (Ξ» i, ΞΌ.restrict (s i)) := ext $ Ξ» t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le [encodable ΞΉ] {s : ΞΉ β†’ set Ξ±} : ΞΌ.restrict (⋃ i, s i) ≀ sum (Ξ» i, ΞΌ.restrict (s i)) := begin intros t ht, suffices : ΞΌ (⋃ i, t ∩ s i) ≀ βˆ‘' i, ΞΌ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool β†’ measure Ξ±) : sum f = f tt + f ff := ext $ Ξ» s hs, by simp [hs, tsum_fintype] @[simp] lemma sum_cond (ΞΌ Ξ½ : measure Ξ±) : sum (Ξ» b, cond b ΞΌ Ξ½) = ΞΌ + Ξ½ := sum_bool _ @[simp] lemma restrict_sum (ΞΌ : ΞΉ β†’ measure Ξ±) {s : set Ξ±} (hs : is_measurable s) : (sum ΞΌ).restrict s = sum (Ξ» i, (ΞΌ i).restrict s) := ext $ Ξ» t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure Ξ± := sum dirac lemma count_apply (hs : is_measurable s) : count s = βˆ‘' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class Ξ±] (s : finset Ξ±) : count (↑s : set Ξ±) = s.card := calc count (↑s : set Ξ±) = βˆ‘' i : (↑s : set Ξ±), (1 : Ξ± β†’ ennreal) i : count_apply s.is_measurable ... = βˆ‘ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp lemma count_apply_finite [measurable_singleton_class Ξ±] (s : set Ξ±) (hs : finite s) : count s = hs.to_finset.card := by rw [← count_apply_finset, finite.coe_to_finset] /-- `count` measure evaluates to infinity at infinite sets. -/ lemma count_apply_infinite [measurable_singleton_class Ξ±] (hs : s.infinite) : count s = ⊀ := begin by_contra H, rcases ennreal.exists_nat_gt H with ⟨n, hn⟩, rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩, have := lt_of_le_of_lt (measure_mono ht) hn, simpa [lt_irrefl] using this end @[simp] lemma count_apply_eq_top [measurable_singleton_class Ξ±] : count s = ⊀ ↔ s.infinite := begin by_cases hs : s.finite, { simp [set.infinite, hs, count_apply_finite] }, { change s.infinite at hs, simp [hs, count_apply_infinite] } end @[simp] lemma count_apply_lt_top [measurable_singleton_class Ξ±] : count s < ⊀ ↔ s.finite := calc count s < ⊀ ↔ count s β‰  ⊀ : lt_top_iff_ne_top ... ↔ Β¬s.infinite : not_congr count_apply_eq_top ... ↔ s.finite : not_not /-! ### The almost everywhere filter -/ /-- The β€œalmost everywhere” filter of co-null sets. -/ def ae (ΞΌ : measure Ξ±) : filter Ξ± := { sets := {s | ΞΌ sᢜ = 0}, univ_sets := by simp, inter_sets := Ξ» s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := Ξ» s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } /-- The filter of sets `s` such that `sᢜ` has finite measure. -/ def cofinite (ΞΌ : measure Ξ±) : filter Ξ± := { sets := {s | ΞΌ sᢜ < ⊀}, univ_sets := by simp, inter_sets := Ξ» s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc ΞΌ (sᢜ βˆͺ tᢜ) ≀ ΞΌ sᢜ + ΞΌ tᢜ : measure_union_le _ _ ... < ⊀ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := Ξ» s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite : s ∈ ΞΌ.cofinite ↔ ΞΌ sᢜ < ⊀ := iff.rfl lemma compl_mem_cofinite : sᢜ ∈ ΞΌ.cofinite ↔ ΞΌ s < ⊀ := by rw [mem_cofinite, compl_compl] lemma eventually_cofinite {p : Ξ± β†’ Prop} : (βˆ€αΆ  x in ΞΌ.cofinite, p x) ↔ ΞΌ {x | Β¬p x} < ⊀ := iff.rfl end measure open measure notation `βˆ€α΅` binders ` βˆ‚` ΞΌ `, ` r:(scoped P, filter.eventually P (measure.ae ΞΌ)) := r notation f ` =ᡐ[`:50 ΞΌ:50 `] `:0 g:50 := f =αΆ [measure.ae ΞΌ] g notation f ` ≀ᡐ[`:50 ΞΌ:50 `] `:0 g:50 := f ≀ᢠ[measure.ae ΞΌ] g lemma mem_ae_iff {s : set Ξ±} : s ∈ ΞΌ.ae ↔ ΞΌ sᢜ = 0 := iff.rfl lemma ae_iff {p : Ξ± β†’ Prop} : (βˆ€α΅ a βˆ‚ ΞΌ, p a) ↔ ΞΌ { a | Β¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set Ξ±} : sᢜ ∈ ΞΌ.ae ↔ ΞΌ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma measure_zero_iff_ae_nmem {s : set Ξ±} : ΞΌ s = 0 ↔ βˆ€α΅ a βˆ‚ ΞΌ, a βˆ‰ s := compl_mem_ae_iff.symm @[simp] lemma ae_eq_bot : ΞΌ.ae = βŠ₯ ↔ ΞΌ = 0 := by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure_univ_eq_zero] lemma ae_of_all {p : Ξ± β†’ Prop} (ΞΌ : measure Ξ±) : (βˆ€ a, p a) β†’ βˆ€α΅ a βˆ‚ ΞΌ, p a := eventually_of_forall @[mono] lemma ae_mono {ΞΌ Ξ½ : measure Ξ±} (h : ΞΌ ≀ Ξ½) : ΞΌ.ae ≀ Ξ½.ae := Ξ» s hs, bot_unique $ trans_rel_left (≀) (measure.le_iff'.1 h _) hs instance : countable_Inter_filter ΞΌ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊒, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ instance ae_is_measurably_generated : is_measurably_generated ΞΌ.ae := ⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_is_measurable_superset_of_measure_eq_zero hs in ⟨tᢜ, compl_mem_ae_iff.2 htΞΌ, htm.compl, compl_subset_comm.1 hst⟩⟩ lemma ae_all_iff [encodable ΞΉ] {p : Ξ± β†’ ΞΉ β†’ Prop} : (βˆ€α΅ a βˆ‚ ΞΌ, βˆ€ i, p a i) ↔ (βˆ€ i, βˆ€α΅ a βˆ‚ ΞΌ, p a i) := eventually_countable_forall lemma ae_ball_iff {S : set ΞΉ} (hS : countable S) {p : Ξ  (x : Ξ±) (i ∈ S), Prop} : (βˆ€α΅ x βˆ‚ ΞΌ, βˆ€ i ∈ S, p x i β€Ή_β€Ί) ↔ βˆ€ i ∈ S, βˆ€α΅ x βˆ‚ ΞΌ, p x i β€Ή_β€Ί := eventually_countable_ball hS lemma ae_eq_refl (f : Ξ± β†’ Ξ΄) : f =ᡐ[ΞΌ] f := eventually_eq.refl _ _ lemma ae_eq_symm {f g : Ξ± β†’ Ξ΄} (h : f =ᡐ[ΞΌ] g) : g =ᡐ[ΞΌ] f := h.symm lemma ae_eq_trans {f g h: Ξ± β†’ Ξ΄} (h₁ : f =ᡐ[ΞΌ] g) (hβ‚‚ : g =ᡐ[ΞΌ] h) : f =ᡐ[ΞΌ] h := h₁.trans hβ‚‚ lemma ae_eq_empty : s =ᡐ[ΞΌ] (βˆ… : set Ξ±) ↔ ΞΌ s = 0 := eventually_eq_empty.trans $ by simp [ae_iff] lemma ae_le_set : s ≀ᡐ[ΞΌ] t ↔ ΞΌ (s \ t) = 0 := calc s ≀ᡐ[ΞΌ] t ↔ βˆ€α΅ x βˆ‚ΞΌ, x ∈ s β†’ x ∈ t : iff.rfl ... ↔ ΞΌ (s \ t) = 0 : by simp [ae_iff]; refl lemma union_ae_eq_right : (s βˆͺ t : set Ξ±) =ᡐ[ΞΌ] t ↔ ΞΌ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self : (s \ t : set Ξ±) =ᡐ[ΞΌ] s ↔ ΞΌ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma ae_eq_set {s t : set Ξ±} : s =ᡐ[ΞΌ] t ↔ ΞΌ (s \ t) = 0 ∧ ΞΌ (t \ s) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set] lemma mem_ae_map_iff {f : Ξ± β†’ Ξ²} (hf : measurable f) {s : set Ξ²} (hs : is_measurable s) : s ∈ (map f ΞΌ).ae ↔ (f ⁻¹' s) ∈ ΞΌ.ae := by simp only [mem_ae_iff, map_apply hf hs.compl, preimage_compl] lemma ae_map_iff {f : Ξ± β†’ Ξ²} (hf : measurable f) {p : Ξ² β†’ Prop} (hp : is_measurable {x | p x}) : (βˆ€α΅ y βˆ‚ (map f ΞΌ), p y) ↔ βˆ€α΅ x βˆ‚ ΞΌ, p (f x) := mem_ae_map_iff hf hp lemma ae_restrict_iff {p : Ξ± β†’ Prop} (hp : is_measurable {x | p x}) : (βˆ€α΅ x βˆ‚(ΞΌ.restrict s), p x) ↔ βˆ€α΅ x βˆ‚ΞΌ, x ∈ s β†’ p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply hp.compl], congr' with x, simp [and_comm] end lemma ae_restrict_iff' {s : set Ξ±} {p : Ξ± β†’ Prop} (hp : is_measurable s) : (βˆ€α΅ x βˆ‚(ΞΌ.restrict s), p x) ↔ βˆ€α΅ x βˆ‚ΞΌ, x ∈ s β†’ p x := begin simp only [ae_iff, ← compl_set_of, restrict_apply_eq_zero' hp], congr' with x, simp [and_comm] end lemma ae_smul_measure {p : Ξ± β†’ Prop} (h : βˆ€α΅ x βˆ‚ΞΌ, p x) (c : ennreal) : βˆ€α΅ x βˆ‚(c β€’ ΞΌ), p x := ae_iff.2 $ by rw [smul_apply, ae_iff.1 h, mul_zero] lemma ae_smul_measure_iff {p : Ξ± β†’ Prop} {c : ennreal} (hc : c β‰  0) : (βˆ€α΅ x βˆ‚(c β€’ ΞΌ), p x) ↔ βˆ€α΅ x βˆ‚ΞΌ, p x := by simp [ae_iff, hc] lemma ae_add_measure_iff {p : Ξ± β†’ Prop} {Ξ½} : (βˆ€α΅ x βˆ‚ΞΌ + Ξ½, p x) ↔ (βˆ€α΅ x βˆ‚ΞΌ, p x) ∧ βˆ€α΅ x βˆ‚Ξ½, p x := add_eq_zero_iff lemma ae_eq_comp {f : Ξ± β†’ Ξ²} {g g' : Ξ² β†’ Ξ΄} (hf : measurable f) (h : g =ᡐ[measure.map f ΞΌ] g') : g ∘ f =ᡐ[ΞΌ] g' ∘ f := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, ht, tmeas, tzero⟩, refine le_antisymm _ bot_le, calc ΞΌ {x | g (f x) β‰  g' (f x)} ≀ ΞΌ (f⁻¹' t) : measure_mono (Ξ» x hx, ht hx) ... = 0 : by rwa ← measure.map_apply hf tmeas end @[simp] lemma ae_restrict_eq (hs : is_measurable s) : (ΞΌ.restrict s).ae = ΞΌ.ae βŠ“ π“Ÿ s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end @[simp] lemma ae_restrict_eq_bot {s} : (ΞΌ.restrict s).ae = βŠ₯ ↔ ΞΌ s = 0 := ae_eq_bot.trans restrict_eq_zero @[simp] lemma ae_restrict_ne_bot {s} : (ΞΌ.restrict s).ae.ne_bot ↔ 0 < ΞΌ s := (not_congr ae_restrict_eq_bot).trans zero_lt_iff_ne_zero.symm /-- A version of the Borel-Cantelli lemma: if sα΅’ is a sequence of measurable sets such that βˆ‘ ΞΌ sα΅’ exists, then for almost all x, x does not belong to almost all sα΅’. -/ lemma ae_eventually_not_mem {s : β„• β†’ set Ξ±} (hs : βˆ€ i, is_measurable (s i)) (hs' : (βˆ‘' i, ΞΌ (s i)) β‰  ⊀) : βˆ€α΅ x βˆ‚ ΞΌ, βˆ€αΆ  n in at_top, x βˆ‰ s n := begin refine measure_mono_null _ (measure_limsup_eq_zero hs hs'), rw ←set.le_eq_subset, refine le_Inf (Ξ» t ht x hx, _), simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq, eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht, rcases ht with ⟨i, hi⟩, rcases hx i with ⟨j, ⟨hj, hj'⟩⟩, exact hi j hj hj' end lemma mem_dirac_ae_iff {a : Ξ±} (hs : is_measurable s) : s ∈ (dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, dirac_apply, hs.compl, indicator_apply, *] lemma eventually_dirac {a : Ξ±} {p : Ξ± β†’ Prop} (hp : is_measurable {x | p x}) : (βˆ€α΅ x βˆ‚(dirac a), p x) ↔ p a := mem_dirac_ae_iff hp lemma eventually_eq_dirac [measurable_singleton_class Ξ²] {a : Ξ±} {f : Ξ± β†’ Ξ²} (hf : measurable f) : f =ᡐ[dirac a] const Ξ± (f a) := (eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl lemma dirac_ae_eq [measurable_singleton_class Ξ±] (a : Ξ±) : (dirac a).ae = pure a := begin ext s, simp only [mem_ae_iff, mem_pure_sets], by_cases ha : a ∈ s, { simp only [ha, iff_true], rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha, refine measure_mono_null ha _, simp [dirac_apply a (is_measurable_singleton a).compl] }, { simp only [ha, iff_false, dirac_apply_of_mem (mem_compl ha)], exact one_ne_zero } end lemma eventually_eq_dirac' [measurable_singleton_class Ξ±] {a : Ξ±} (f : Ξ± β†’ Ξ΄) : f =ᡐ[dirac a] const Ξ± (f a) := by { rw [dirac_ae_eq], show f a = f a, refl } /-- If `s βŠ† t` modulo a set of measure `0`, then `ΞΌ s ≀ ΞΌ t`. -/ lemma measure_mono_ae (H : s ≀ᡐ[ΞΌ] t) : ΞΌ s ≀ ΞΌ t := calc ΞΌ s ≀ ΞΌ (s βˆͺ t) : measure_mono $ subset_union_left s t ... = ΞΌ (t βˆͺ s \ t) : by rw [union_diff_self, set.union_comm] ... ≀ ΞΌ t + ΞΌ (s \ t) : measure_union_le _ _ ... = ΞΌ t : by rw [ae_le_set.1 H, add_zero] alias measure_mono_ae ← filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `ΞΌ s = ΞΌ t`. -/ lemma measure_congr (H : s =ᡐ[ΞΌ] t) : ΞΌ s = ΞΌ t := le_antisymm H.le.measure_le H.symm.le.measure_le lemma restrict_mono_ae (h : s ≀ᡐ[ΞΌ] t) : ΞΌ.restrict s ≀ ΞΌ.restrict t := begin intros u hu, simp only [restrict_apply hu], exact measure_mono_ae (h.mono $ Ξ» x hx, and.imp id hx) end lemma restrict_congr_set (H : s =ᡐ[ΞΌ] t) : ΞΌ.restrict s = ΞΌ.restrict t := le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le) /-- A measure `ΞΌ` is called a probability measure if `ΞΌ univ = 1`. -/ class probability_measure (ΞΌ : measure Ξ±) : Prop := (measure_univ : ΞΌ univ = 1) instance measure.dirac.probability_measure {x : Ξ±} : probability_measure (dirac x) := ⟨dirac_apply_of_mem $ mem_univ x⟩ /-- A measure `ΞΌ` is called finite if `ΞΌ univ < ⊀`. -/ class finite_measure (ΞΌ : measure Ξ±) : Prop := (measure_univ_lt_top : ΞΌ univ < ⊀) instance restrict.finite_measure (ΞΌ : measure Ξ±) [hs : fact (ΞΌ s < ⊀)] : finite_measure (ΞΌ.restrict s) := ⟨by simp [hs.elim]⟩ /-- Measure `ΞΌ` *has no atoms* if the measure of each singleton is zero. NB: Wikipedia assumes that for any measurable set `s` with positive `ΞΌ`-measure, there exists a measurable `t βŠ† s` such that `0 < ΞΌ t < ΞΌ s`. While this implies `ΞΌ {x} = 0`, the converse is not true. -/ class has_no_atoms (ΞΌ : measure Ξ±) : Prop := (measure_singleton : βˆ€ x, ΞΌ {x} = 0) export probability_measure (measure_univ) has_no_atoms (measure_singleton) attribute [simp] measure_singleton lemma measure_lt_top (ΞΌ : measure Ξ±) [finite_measure ΞΌ] (s : set Ξ±) : ΞΌ s < ⊀ := (measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top lemma measure_ne_top (ΞΌ : measure Ξ±) [finite_measure ΞΌ] (s : set Ξ±) : ΞΌ s β‰  ⊀ := ne_of_lt (measure_lt_top ΞΌ s) /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds for measures with the additional assumption that ΞΌ is finite. -/ lemma measure.le_of_add_le_add_left {ΞΌ ν₁ Ξ½β‚‚ : measure Ξ±} [finite_measure ΞΌ] (A2 : ΞΌ + ν₁ ≀ ΞΌ + Ξ½β‚‚) : ν₁ ≀ Ξ½β‚‚ := Ξ» S B1, ennreal.le_of_add_le_add_left (measure_theory.measure_lt_top ΞΌ S) (A2 S B1) @[priority 100] instance probability_measure.to_finite_measure (ΞΌ : measure Ξ±) [probability_measure ΞΌ] : finite_measure ΞΌ := ⟨by simp only [measure_univ, ennreal.one_lt_top]⟩ lemma probability_measure.ne_zero (ΞΌ : measure Ξ±) [probability_measure ΞΌ] : ΞΌ β‰  0 := mt measure_univ_eq_zero.2 $ by simp [measure_univ] section no_atoms variables [has_no_atoms ΞΌ] lemma measure_countable (h : countable s) : ΞΌ s = 0 := begin rw [← bUnion_of_singleton s, ← le_zero_iff_eq], refine le_trans (measure_bUnion_le h _) _, simp end lemma measure_finite (h : s.finite) : ΞΌ s = 0 := measure_countable h.countable lemma measure_finset (s : finset Ξ±) : ΞΌ ↑s = 0 := measure_finite s.finite_to_set lemma insert_ae_eq_self (a : Ξ±) (s : set Ξ±) : (insert a s : set Ξ±) =ᡐ[ΞΌ] s := union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _) variables [partial_order Ξ±] {a b : Ξ±} lemma Iio_ae_eq_Iic : Iio a =ᡐ[ΞΌ] Iic a := by simp only [← Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)] lemma Ioi_ae_eq_Ici : Ioi a =ᡐ[ΞΌ] Ici a := @Iio_ae_eq_Iic (order_dual Ξ±) β€Ή_β€Ί β€Ή_β€Ί _ _ _ lemma Ioo_ae_eq_Ioc : Ioo a b =ᡐ[ΞΌ] Ioc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ioc_ae_eq_Icc : Ioc a b =ᡐ[ΞΌ] Icc a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Ico : Ioo a b =ᡐ[ΞΌ] Ico a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Icc : Ioo a b =ᡐ[ΞΌ] Icc a b := Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic lemma Ico_ae_eq_Icc : Ico a b =ᡐ[ΞΌ] Icc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ico_ae_eq_Ioc : Ico a b =ᡐ[ΞΌ] Ioc a b := Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc end no_atoms namespace measure /-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`. Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/ def finite_at_filter (ΞΌ : measure Ξ±) (f : filter Ξ±) : Prop := βˆƒ s ∈ f, ΞΌ s < ⊀ lemma finite_at_filter_of_finite (ΞΌ : measure Ξ±) [finite_measure ΞΌ] (f : filter Ξ±) : ΞΌ.finite_at_filter f := ⟨univ, univ_mem_sets, measure_lt_top ΞΌ univ⟩ lemma finite_at_bot (ΞΌ : measure Ξ±) : ΞΌ.finite_at_filter βŠ₯ := βŸ¨βˆ…, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩ /-- `ΞΌ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have finite measures. This structure is a type, which is useful if we want to record extra properties about the sets, such as that they are monotone. `sigma_finite` is defined in terms of this: `ΞΌ` is Οƒ-finite if there exists a sequence of finite spanning sets in the collection of all measurable sets. -/ @[protect_proj, nolint has_inhabited_instance] structure finite_spanning_sets_in (ΞΌ : measure Ξ±) (C : set (set Ξ±)) := (set : β„• β†’ set Ξ±) (set_mem : βˆ€ i, set i ∈ C) (finite : βˆ€ i, ΞΌ (set i) < ⊀) (spanning : (⋃ i, set i) = univ) end measure open measure /-- A measure `ΞΌ` is called Οƒ-finite if there is a countable collection of sets `{ A i | i ∈ β„• }` such that `ΞΌ (A i) < ⊀` and `⋃ i, A i = s`. -/ @[class] def sigma_finite (ΞΌ : measure Ξ±) : Prop := nonempty (ΞΌ.finite_spanning_sets_in {s | is_measurable s}) /-- If `ΞΌ` is Οƒ-finite it has finite spanning sets in the collection of all measurable sets. -/ def measure.to_finite_spanning_sets_in (ΞΌ : measure Ξ±) [h : sigma_finite ΞΌ] : ΞΌ.finite_spanning_sets_in {s | is_measurable s} := classical.choice h /-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite measure using `classical.some`. This definition satisfies monotonicity in addition to all other properties in `sigma_finite`. -/ def spanning_sets (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] (i : β„•) : set Ξ± := accumulate ΞΌ.to_finite_spanning_sets_in.set i lemma monotone_spanning_sets (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] : monotone (spanning_sets ΞΌ) := monotone_accumulate lemma is_measurable_spanning_sets (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] (i : β„•) : is_measurable (spanning_sets ΞΌ i) := is_measurable.Union $ Ξ» j, is_measurable.Union_Prop $ Ξ» hij, ΞΌ.to_finite_spanning_sets_in.set_mem j lemma measure_spanning_sets_lt_top (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] (i : β„•) : ΞΌ (spanning_sets ΞΌ i) < ⊀ := measure_bUnion_lt_top (finite_le_nat i) $ Ξ» j _, ΞΌ.to_finite_spanning_sets_in.finite j lemma Union_spanning_sets (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] : (⋃ i : β„•, spanning_sets ΞΌ i) = univ := by simp_rw [spanning_sets, Union_accumulate, ΞΌ.to_finite_spanning_sets_in.spanning] lemma is_countably_spanning_spanning_sets (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] : is_countably_spanning (range (spanning_sets ΞΌ)) := ⟨spanning_sets ΞΌ, mem_range_self, Union_spanning_sets μ⟩ namespace measure lemma supr_restrict_spanning_sets [sigma_finite ΞΌ] (hs : is_measurable s) : (⨆ i, ΞΌ.restrict (spanning_sets ΞΌ i) s) = ΞΌ s := begin convert (restrict_Union_apply_eq_supr (is_measurable_spanning_sets ΞΌ) _ hs).symm, { simp [Union_spanning_sets] }, { exact directed_of_sup (monotone_spanning_sets ΞΌ) } end namespace finite_spanning_sets_in variables {C D : set (set Ξ±)} /-- If `ΞΌ` has finite spanning sets in `C` and `C βŠ† D` then `ΞΌ` has finite spanning sets in `D`. -/ protected def mono (h : ΞΌ.finite_spanning_sets_in C) (hC : C βŠ† D) : ΞΌ.finite_spanning_sets_in D := ⟨h.set, Ξ» i, hC (h.set_mem i), h.finite, h.spanning⟩ /-- If `ΞΌ` has finite spanning sets in the collection of measurable sets `C`, then `ΞΌ` is Οƒ-finite. -/ protected lemma sigma_finite (h : ΞΌ.finite_spanning_sets_in C) (hC : βˆ€ s ∈ C, is_measurable s) : sigma_finite ΞΌ := ⟨h.mono hC⟩ /-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of `finite_spanning_sets_in`. -/ protected lemma ext {Ξ½ : measure Ξ±} {C : set (set Ξ±)} (hA : β€Ή_β€Ί = generate_from C) (hC : is_pi_system C) (h : ΞΌ.finite_spanning_sets_in C) (h_eq : βˆ€ s ∈ C, ΞΌ s = Ξ½ s) : ΞΌ = Ξ½ := ext_of_generate_from_of_Union C _ hA hC h.spanning h.set_mem h.finite h_eq protected lemma is_countably_spanning (h : ΞΌ.finite_spanning_sets_in C) : is_countably_spanning C := ⟨_, h.set_mem, h.spanning⟩ end finite_spanning_sets_in end measure /-- Every finite measure is Οƒ-finite. -/ @[priority 100] instance finite_measure.to_sigma_finite (ΞΌ : measure Ξ±) [finite_measure ΞΌ] : sigma_finite ΞΌ := ⟨⟨λ _, univ, Ξ» _, is_measurable.univ, Ξ» _, measure_lt_top ΞΌ _, Union_const _⟩⟩ instance restrict.sigma_finite (ΞΌ : measure Ξ±) [sigma_finite ΞΌ] (s : set Ξ±) : sigma_finite (ΞΌ.restrict s) := begin refine ⟨⟨spanning_sets ΞΌ, is_measurable_spanning_sets ΞΌ, Ξ» i, _, Union_spanning_sets μ⟩⟩, rw [restrict_apply (is_measurable_spanning_sets ΞΌ i)], exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top ΞΌ i) end instance sum.sigma_finite {ΞΉ} [fintype ΞΉ] (ΞΌ : ΞΉ β†’ measure Ξ±) [βˆ€ i, sigma_finite (ΞΌ i)] : sigma_finite (sum ΞΌ) := begin haveI : encodable ΞΉ := (encodable.trunc_encodable_of_fintype ΞΉ).out, have : βˆ€ n, is_measurable (β‹‚ (i : ΞΉ), spanning_sets (ΞΌ i) n) := Ξ» n, is_measurable.Inter (Ξ» i, is_measurable_spanning_sets (ΞΌ i) n), refine ⟨⟨λ n, β‹‚ i, spanning_sets (ΞΌ i) n, this, Ξ» n, _, _⟩⟩, { rw [sum_apply _ (this n), tsum_fintype, ennreal.sum_lt_top_iff], rintro i -, exact (measure_mono $ Inter_subset _ i).trans_lt (measure_spanning_sets_lt_top (ΞΌ i) n) }, { rw [Union_Inter_of_monotone], simp_rw [Union_spanning_sets, Inter_univ], exact Ξ» i, monotone_spanning_sets (ΞΌ i), } end instance add.sigma_finite (ΞΌ Ξ½ : measure Ξ±) [sigma_finite ΞΌ] [sigma_finite Ξ½] : sigma_finite (ΞΌ + Ξ½) := by { rw [← sum_cond], refine @sum.sigma_finite _ _ _ _ _ (bool.rec _ _); simpa } /-- A measure is called locally finite if it is finite in some neighborhood of each point. -/ class locally_finite_measure [topological_space Ξ±] (ΞΌ : measure Ξ±) : Prop := (finite_at_nhds : βˆ€ x, ΞΌ.finite_at_filter (𝓝 x)) @[priority 100] instance finite_measure.to_locally_finite_measure [topological_space Ξ±] (ΞΌ : measure Ξ±) [finite_measure ΞΌ] : locally_finite_measure ΞΌ := ⟨λ x, finite_at_filter_of_finite _ _⟩ lemma measure.finite_at_nhds [topological_space Ξ±] (ΞΌ : measure Ξ±) [locally_finite_measure ΞΌ] (x : Ξ±) : ΞΌ.finite_at_filter (𝓝 x) := locally_finite_measure.finite_at_nhds x /-- Two finite measures are equal if they are equal on the Ο€-system generating the Οƒ-algebra (and `univ`). -/ lemma ext_of_generate_finite (C : set (set Ξ±)) (hA : _inst_1 = generate_from C) (hC : is_pi_system C) {ΞΌ Ξ½ : measure Ξ±} [finite_measure ΞΌ] [finite_measure Ξ½] (hΞΌΞ½ : βˆ€ s ∈ C, ΞΌ s = Ξ½ s) (h_univ : ΞΌ univ = Ξ½ univ) : ΞΌ = Ξ½ := begin ext1 s hs, refine induction_on_inter hA hC (by simp) hΞΌΞ½ _ _ hs, { rintros t h1t h2t, change is_measurable t at h1t, simp [measure_compl, measure_lt_top, *] }, { rintros f h1f h2f h3f, simp [measure_Union, is_measurable.Union, *] } end namespace measure namespace finite_at_filter variables {f g : filter Ξ±} lemma filter_mono (h : f ≀ g) : ΞΌ.finite_at_filter g β†’ ΞΌ.finite_at_filter f := Ξ» ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩ lemma inf_of_left (h : ΞΌ.finite_at_filter f) : ΞΌ.finite_at_filter (f βŠ“ g) := h.filter_mono inf_le_left lemma inf_of_right (h : ΞΌ.finite_at_filter g) : ΞΌ.finite_at_filter (f βŠ“ g) := h.filter_mono inf_le_right @[simp] lemma inf_ae_iff : ΞΌ.finite_at_filter (f βŠ“ ΞΌ.ae) ↔ ΞΌ.finite_at_filter f := begin refine ⟨_, Ξ» h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩, suffices : ΞΌ t ≀ ΞΌ s, from ⟨t, ht, this.trans_lt hμ⟩, exact measure_mono_ae (mem_sets_of_superset hu (Ξ» x hu ht, hs ⟨ht, hu⟩)) end alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _ lemma filter_mono_ae (h : f βŠ“ ΞΌ.ae ≀ g) (hg : ΞΌ.finite_at_filter g) : ΞΌ.finite_at_filter f := inf_ae_iff.1 (hg.filter_mono h) protected lemma measure_mono (h : ΞΌ ≀ Ξ½) : Ξ½.finite_at_filter f β†’ ΞΌ.finite_at_filter f := Ξ» ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩ @[mono] protected lemma mono (hf : f ≀ g) (hΞΌ : ΞΌ ≀ Ξ½) : Ξ½.finite_at_filter g β†’ ΞΌ.finite_at_filter f := Ξ» h, (h.filter_mono hf).measure_mono hΞΌ protected lemma eventually (h : ΞΌ.finite_at_filter f) : βˆ€αΆ  s in f.lift' powerset, ΞΌ s < ⊀ := (eventually_lift'_powerset' $ Ξ» s t hst ht, (measure_mono hst).trans_lt ht).2 h lemma filter_sup : ΞΌ.finite_at_filter f β†’ ΞΌ.finite_at_filter g β†’ ΞΌ.finite_at_filter (f βŠ” g) := Ξ» ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩, ⟨s βˆͺ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsΞΌ, htμ⟩)⟩ end finite_at_filter lemma finite_at_nhds_within [topological_space Ξ±] (ΞΌ : measure Ξ±) [locally_finite_measure ΞΌ] (x : Ξ±) (s : set Ξ±) : ΞΌ.finite_at_filter (𝓝[s] x) := (finite_at_nhds ΞΌ x).inf_of_left @[simp] lemma finite_at_principal : ΞΌ.finite_at_filter (π“Ÿ s) ↔ ΞΌ s < ⊀ := ⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hΞΌ, Ξ» h, ⟨s, mem_principal_self s, h⟩⟩ /-! ### Subtraction of measures -/ /-- The measure `ΞΌ - Ξ½` is defined to be the least measure `Ο„` such that `ΞΌ ≀ Ο„ + Ξ½`. It is the equivalent of `(ΞΌ - Ξ½) βŠ” 0` if `ΞΌ` and `Ξ½` were signed measures. Compare with `ennreal.has_sub`. Specifically, note that if you have `Ξ± = {1,2}`, and `ΞΌ {1} = 2`, `ΞΌ {2} = 0`, and `Ξ½ {2} = 2`, `Ξ½ {1} = 0`, then `(ΞΌ - Ξ½) {1, 2} = 2`. However, if `ΞΌ ≀ Ξ½`, and `Ξ½ univ β‰  ⊀`, then `(ΞΌ - Ξ½) + Ξ½ = ΞΌ`. -/ noncomputable instance has_sub {Ξ± : Type*} [measurable_space Ξ±] : has_sub (measure Ξ±) := ⟨λ ΞΌ Ξ½, Inf {Ο„ | ΞΌ ≀ Ο„ + Ξ½} ⟩ section measure_sub lemma sub_def : ΞΌ - Ξ½ = Inf {d | ΞΌ ≀ d + Ξ½} := rfl lemma sub_eq_zero_of_le (h : ΞΌ ≀ Ξ½) : ΞΌ - Ξ½ = 0 := begin rw [← le_zero_iff_eq', measure.sub_def], apply @Inf_le (measure Ξ±) _ _, simp [h], end /-- This application lemma only works in special circumstances. Given knowledge of when `ΞΌ ≀ Ξ½` and `Ξ½ ≀ ΞΌ`, a more general application lemma can be written. -/ lemma sub_apply [finite_measure Ξ½] (h₁ : is_measurable s) (hβ‚‚ : Ξ½ ≀ ΞΌ) : (ΞΌ - Ξ½) s = ΞΌ s - Ξ½ s := begin -- We begin by defining `measure_sub`, which will be equal to `(ΞΌ - Ξ½)`. let measure_sub : measure Ξ± := @measure_theory.measure.of_measurable Ξ± _ (Ξ» (t : set Ξ±) (h_t_is_measurable : is_measurable t), (ΞΌ t - Ξ½ t)) begin simp end begin intros g h_meas h_disj, simp only, rw ennreal.tsum_sub, repeat { rw ← measure_theory.measure_Union h_disj h_meas }, apply measure_theory.measure_lt_top, intro i, apply hβ‚‚, apply h_meas end, -- Now, we demonstrate `ΞΌ - Ξ½ = measure_sub`, and apply it. begin have h_measure_sub_add : (Ξ½ + measure_sub = ΞΌ), { ext t h_t_is_measurable, simp only [pi.add_apply, coe_add], rw [measure_theory.measure.of_measurable_apply _ h_t_is_measurable, add_comm, ennreal.sub_add_cancel_of_le (hβ‚‚ t h_t_is_measurable)] }, have h_measure_sub_eq : (ΞΌ - Ξ½) = measure_sub, { rw measure_theory.measure.sub_def, apply le_antisymm, { apply @Inf_le (measure Ξ±) (measure.complete_lattice), simp [le_refl, add_comm, h_measure_sub_add] }, apply @le_Inf (measure Ξ±) (measure.complete_lattice), intros d h_d, rw [← h_measure_sub_add, mem_set_of_eq, add_comm d] at h_d, apply measure.le_of_add_le_add_left h_d }, rw h_measure_sub_eq, apply measure.of_measurable_apply _ h₁, end end lemma sub_add_cancel_of_le [finite_measure Ξ½] (h₁ : Ξ½ ≀ ΞΌ) : ΞΌ - Ξ½ + Ξ½ = ΞΌ := begin ext s h_s_meas, rw [add_apply, sub_apply h_s_meas h₁, ennreal.sub_add_cancel_of_le (h₁ s h_s_meas)], end end measure_sub end measure end measure_theory open measure_theory measure_theory.measure namespace measurable_equiv open equiv variables [measurable_space Ξ±] [measurable_space Ξ²] {ΞΌ : measure Ξ±} {Ξ½ : measure Ξ²} /-- If we map a measure along a measurable equivalence, we can compute the measure on all sets (not just the measurable ones). -/ protected theorem map_apply (f : Ξ± ≃ᡐ Ξ²) (s : set Ξ²) : measure.map f ΞΌ s = ΞΌ (f ⁻¹' s) := begin refine le_antisymm _ (le_map_apply f.measurable s), rw [measure_eq_infi' ΞΌ], refine le_infi _, rintro ⟨t, hst, ht⟩, rw [subtype.coe_mk], have := f.symm.to_equiv.image_eq_preimage, simp only [←coe_eq, symm_symm, symm_to_equiv] at this, rw [← this, image_subset_iff] at hst, convert measure_mono hst, rw [map_apply, preimage_preimage], { refine congr_arg ΞΌ (eq.symm _), convert preimage_id, exact funext f.left_inv }, exacts [f.measurable, f.measurable_inv_fun ht] end end measurable_equiv section is_complete /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `ΞΌ s = 0`. -/ @[class] def measure_theory.measure.is_complete {_ : measurable_space Ξ±} (ΞΌ : measure Ξ±) : Prop := βˆ€ s, ΞΌ s = 0 β†’ is_measurable s variables [measurable_space Ξ±] {ΞΌ : measure Ξ±} {s t z : set Ξ±} /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def is_null_measurable (ΞΌ : measure Ξ±) (s : set Ξ±) : Prop := βˆƒ t z, s = t βˆͺ z ∧ is_measurable t ∧ ΞΌ z = 0 theorem is_null_measurable_iff : is_null_measurable ΞΌ s ↔ βˆƒ t, t βŠ† s ∧ is_measurable t ∧ ΞΌ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem is_null_measurable_measure_eq (st : t βŠ† s) (hz : ΞΌ (s \ t) = 0) : ΞΌ s = ΞΌ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem is_measurable.is_null_measurable (ΞΌ : measure Ξ±) (hs : is_measurable s) : is_null_measurable ΞΌ s := ⟨s, βˆ…, by simp, hs, ΞΌ.empty⟩ theorem is_null_measurable_of_complete (ΞΌ : measure Ξ±) [c : ΞΌ.is_complete] : is_null_measurable ΞΌ s ↔ is_measurable s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact is_measurable.union ht (c _ hz), Ξ» h, h.is_null_measurable _⟩ theorem is_null_measurable.union_null (hs : is_null_measurable ΞΌ s) (hz : ΞΌ z = 0) : is_null_measurable ΞΌ (s βˆͺ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' βˆͺ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_is_null_measurable (hz : ΞΌ z = 0) : is_null_measurable ΞΌ z := by simpa using (is_measurable.empty.is_null_measurable _).union_null hz theorem is_null_measurable.Union_nat {s : β„• β†’ set Ξ±} (hs : βˆ€ i, is_null_measurable ΞΌ (s i)) : is_null_measurable ΞΌ (Union s) := begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine is_null_measurable_iff.2 ⟨Union t, Union_subset_Union st, is_measurable.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (Ξ» i, by rw ← diff_subset_iff) end theorem is_measurable.diff_null (hs : is_measurable s) (hz : ΞΌ z = 0) : is_null_measurable ΞΌ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show βˆ€ q : {q : β„š // q > 0}, βˆƒ t : set Ξ±, z βŠ† t ∧ is_measurable t ∧ ΞΌ t < (nnreal.of_real q.1 : ennreal), { rintro ⟨Ρ, Ξ΅0⟩, have : 0 < (nnreal.of_real Ξ΅ : ennreal), { simpa using Ξ΅0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine is_null_measurable_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (Ξ» i, (hf i).1)), hs.diff (is_measurable.Inter (Ξ» i, (hf i).2.1)), measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ Ξ» h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨Ρ, Ξ΅0', Ξ΅0, h⟩, simp at Ξ΅0, apply not_le_of_lt (lt_trans (hf ⟨Ρ, Ξ΅0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem is_null_measurable.diff_null (hs : is_null_measurable ΞΌ s) (hz : ΞΌ z = 0) : is_null_measurable ΞΌ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem is_null_measurable.compl (hs : is_null_measurable ΞΌ s) : is_null_measurable ΞΌ sᢜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end theorem is_null_measurable_iff_ae {s : set Ξ±} : is_null_measurable ΞΌ s ↔ βˆƒ t, is_measurable t ∧ s =ᡐ[ΞΌ] t := begin simp only [ae_eq_set], split, { assume h, rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩, refine ⟨t, tmeas, ht, _⟩, rw [diff_eq_empty.2 ts, measure_empty] }, { rintros ⟨t, tmeas, h₁, hβ‚‚βŸ©, have : is_null_measurable ΞΌ (t βˆͺ (s \ t)) := is_null_measurable.union_null (tmeas.is_null_measurable _) h₁, have A : is_null_measurable ΞΌ ((t βˆͺ (s \ t)) \ (t \ s)) := is_null_measurable.diff_null this hβ‚‚, have : (t βˆͺ (s \ t)) \ (t \ s) = s, { apply subset.antisymm, { assume x hx, simp only [mem_union_eq, not_and, mem_diff, not_not_mem] at hx, cases hx.1, { exact hx.2 h }, { exact h.1 } }, { assume x hx, simp [hx, classical.em (x ∈ t)] } }, rwa this at A } end theorem is_null_measurable_iff_sandwich {s : set Ξ±} : is_null_measurable ΞΌ s ↔ βˆƒ (t u : set Ξ±), is_measurable t ∧ is_measurable u ∧ t βŠ† s ∧ s βŠ† u ∧ ΞΌ (u \ t) = 0 := begin split, { assume h, rcases is_null_measurable_iff.1 h with ⟨t, ts, tmeas, ht⟩, rcases is_null_measurable_iff.1 h.compl with ⟨u', u's, u'meas, hu'⟩, have A : s βŠ† u'ᢜ := subset_compl_comm.mp u's, refine ⟨t, u'ᢜ, tmeas, u'meas.compl, ts, A, _⟩, have : sᢜ \ u' = u'ᢜ \ s, by simp [compl_eq_univ_diff, diff_diff, union_comm], rw this at hu', apply le_antisymm _ bot_le, calc ΞΌ (u'ᢜ \ t) ≀ ΞΌ ((u'ᢜ \ s) βˆͺ (s \ t)) : begin apply measure_mono, assume x hx, simp at hx, simp [hx, or_comm, classical.em], end ... ≀ ΞΌ (u'ᢜ \ s) + ΞΌ (s \ t) : measure_union_le _ _ ... = 0 : by rw [ht, hu', zero_add] }, { rintros ⟨t, u, tmeas, umeas, ts, su, hμ⟩, refine is_null_measurable_iff.2 ⟨t, ts, tmeas, _⟩, apply le_antisymm _ bot_le, calc ΞΌ (s \ t) ≀ ΞΌ (u \ t) : measure_mono (diff_subset_diff_left su) ... = 0 : hΞΌ } end lemma restrict_apply_of_is_null_measurable {s t : set Ξ±} (ht : is_null_measurable (ΞΌ.restrict s) t) : ΞΌ.restrict s t = ΞΌ (t ∩ s) := begin rcases is_null_measurable_iff_sandwich.1 ht with ⟨u, v, umeas, vmeas, ut, tv, huv⟩, apply le_antisymm _ (le_restrict_apply _ _), calc ΞΌ.restrict s t ≀ ΞΌ.restrict s v : measure_mono tv ... = ΞΌ (v ∩ s) : restrict_apply vmeas ... ≀ ΞΌ ((u ∩ s) βˆͺ ((v \ u) ∩ s)) : measure_mono $ by { assume x hx, simp at hx, simp [hx, classical.em] } ... ≀ ΞΌ (u ∩ s) + ΞΌ ((v \ u) ∩ s) : measure_union_le _ _ ... = ΞΌ (u ∩ s) + ΞΌ.restrict s (v \ u) : by rw measure.restrict_apply (vmeas.diff umeas) ... = ΞΌ (u ∩ s) : by rw [huv, add_zero] ... ≀ ΞΌ (t ∩ s) : measure_mono $ inter_subset_inter_left s ut end /-- The measurable space of all null measurable sets. -/ def null_measurable (ΞΌ : measure Ξ±) : measurable_space Ξ± := { is_measurable' := is_null_measurable ΞΌ, is_measurable_empty := is_measurable.empty.is_null_measurable _, is_measurable_compl := Ξ» s hs, hs.compl, is_measurable_Union := Ξ» f, is_null_measurable.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion (ΞΌ : measure Ξ±) : @measure_theory.measure Ξ± (null_measurable ΞΌ) := { to_outer_measure := ΞΌ.to_outer_measure, m_Union := Ξ» s hs hd, show ΞΌ (Union s) = βˆ‘' i, ΞΌ (s i), begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw is_null_measurable_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (is_null_measurable_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, hβ‚‚βŸ©, exact hd i j ij ⟨st i h₁, st j hβ‚‚βŸ© } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (Ξ» i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable ΞΌ, refine le_antisymm (Ξ» s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (Ξ» t, infi_le_infi $ Ξ» st, infi_le_infi2 $ Ξ» ht, ⟨ht.is_null_measurable _, le_refl _⟩) end } instance completion.is_complete (ΞΌ : measure Ξ±) : (completion ΞΌ).is_complete := Ξ» z hz, null_is_null_measurable hz end is_complete namespace measure_theory /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (Ξ± : Type*) extends measurable_space Ξ± := (volume : measure Ξ±) export measure_space (volume) /-- `volume` is the canonical measure on `Ξ±`. -/ add_decl_doc volume section measure_space variables [measure_space Ξ±] {s₁ sβ‚‚ : set Ξ±} notation `βˆ€α΅` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end measure_theory /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. We define this property, called `ae_measurable f ΞΌ`, and discuss several of its properties that are analogous to properties of measurable functions. -/ section open measure_theory variables [measurable_space Ξ±] [measurable_space Ξ²] {f g : Ξ± β†’ Ξ²} {ΞΌ Ξ½ : measure Ξ±} /-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. -/ def ae_measurable (f : Ξ± β†’ Ξ²) (ΞΌ : measure Ξ± . measure_theory.volume_tac) : Prop := βˆƒ g : Ξ± β†’ Ξ², measurable g ∧ f =ᡐ[ΞΌ] g lemma measurable.ae_measurable (h : measurable f) : ae_measurable f ΞΌ := ⟨f, h, ae_eq_refl f⟩ namespace ae_measurable /-- Given an almost everywhere measurable function `f`, associate to it a measurable function that coincides with it almost everywhere. `f` is explicit in the definition to make sure that it shows in pretty-printing. -/ def mk (f : Ξ± β†’ Ξ²) (h : ae_measurable f ΞΌ) : Ξ± β†’ Ξ² := classical.some h lemma measurable_mk (h : ae_measurable f ΞΌ) : measurable (h.mk f) := (classical.some_spec h).1 lemma ae_eq_mk (h : ae_measurable f ΞΌ) : f =ᡐ[ΞΌ] (h.mk f) := (classical.some_spec h).2 lemma congr (hf : ae_measurable f ΞΌ) (h : f =ᡐ[ΞΌ] g) : ae_measurable g ΞΌ := ⟨hf.mk f, hf.measurable_mk, h.symm.trans hf.ae_eq_mk⟩ lemma mono_measure (h : ae_measurable f ΞΌ) (h' : Ξ½ ≀ ΞΌ) : ae_measurable f Ξ½ := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma add_measure {f : Ξ± β†’ Ξ²} (hΞΌ : ae_measurable f ΞΌ) (hΞ½ : ae_measurable f Ξ½) : ae_measurable f (ΞΌ + Ξ½) := begin let s := {x | f x β‰  hΞΌ.mk f x}, have : ΞΌ s = 0 := hΞΌ.ae_eq_mk, obtain ⟨t, st, t_meas, ΞΌt⟩ : βˆƒ t, s βŠ† t ∧ is_measurable t ∧ ΞΌ t = 0 := exists_is_measurable_superset_of_measure_eq_zero this, let g : Ξ± β†’ Ξ² := t.piecewise (hΞ½.mk f) (hΞΌ.mk f), refine ⟨g, measurable.piecewise t_meas hΞ½.measurable_mk hΞΌ.measurable_mk, _⟩, change ΞΌ {x | f x β‰  g x} + Ξ½ {x | f x β‰  g x} = 0, suffices : ΞΌ {x | f x β‰  g x} = 0 ∧ Ξ½ {x | f x β‰  g x} = 0, by simp [this.1, this.2], have ht : {x | f x β‰  g x} βŠ† t, { assume x hx, by_contra h, simp only [g, h, mem_set_of_eq, ne.def, not_false_iff, piecewise_eq_of_not_mem] at hx, exact h (st hx) }, split, { have : ΞΌ {x | f x β‰  g x} ≀ ΞΌ t := measure_mono ht, rw ΞΌt at this, exact le_antisymm this bot_le }, { have : {x | f x β‰  g x} βŠ† {x | f x β‰  hΞ½.mk f x}, { assume x hx, simpa [ht hx, g] using hx }, apply le_antisymm _ bot_le, calc Ξ½ {x | f x β‰  g x} ≀ Ξ½ {x | f x β‰  hΞ½.mk f x} : measure_mono this ... = 0 : hΞ½.ae_eq_mk } end lemma smul_measure (h : ae_measurable f ΞΌ) (c : ennreal) : ae_measurable f (c β€’ ΞΌ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_measurable [measurable_space Ξ΄] {f : Ξ± β†’ Ξ΄} {g : Ξ΄ β†’ Ξ²} (hg : ae_measurable g (measure.map f ΞΌ)) (hf : measurable f) : ae_measurable (g ∘ f) ΞΌ := ⟨(hg.mk g) ∘ f, hg.measurable_mk.comp hf, ae_eq_comp hf hg.ae_eq_mk⟩ lemma prod_mk {Ξ³ : Type*} [measurable_space Ξ³] {f : Ξ± β†’ Ξ²} {g : Ξ± β†’ Ξ³} (hf : ae_measurable f ΞΌ) (hg : ae_measurable g ΞΌ) : ae_measurable (Ξ» x, (f x, g x)) ΞΌ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma is_null_measurable (h : ae_measurable f ΞΌ) {s : set Ξ²} (hs : is_measurable s) : is_null_measurable ΞΌ (f ⁻¹' s) := begin apply is_null_measurable_iff_ae.2, refine ⟨(h.mk f) ⁻¹' s, h.measurable_mk hs, _⟩, filter_upwards [h.ae_eq_mk], assume x hx, change (f x ∈ s) = ((h.mk f) x ∈ s), rwa hx end end ae_measurable lemma ae_measurable_congr (h : f =ᡐ[ΞΌ] g) : ae_measurable f ΞΌ ↔ ae_measurable g ΞΌ := ⟨λ hf, ae_measurable.congr hf h, Ξ» hg, ae_measurable.congr hg h.symm⟩ @[simp] lemma ae_measurable_add_measure_iff : ae_measurable f (ΞΌ + Ξ½) ↔ ae_measurable f ΞΌ ∧ ae_measurable f Ξ½ := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, Ξ» h, h.1.add_measure h.2⟩ @[simp] lemma ae_measurable_const {b : Ξ²} : ae_measurable (Ξ» a : Ξ±, b) ΞΌ := measurable_const.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ennreal} (hc : c β‰  0) : ae_measurable f (c β€’ ΞΌ) ↔ ae_measurable f ΞΌ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, Ξ» h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma measurable.comp_ae_measurable [measurable_space Ξ΄] {f : Ξ± β†’ Ξ΄} {g : Ξ΄ β†’ Ξ²} (hg : measurable g) (hf : ae_measurable f ΞΌ) : ae_measurable (g ∘ f) ΞΌ := ⟨g ∘ hf.mk f, hg.comp hf.measurable_mk, eventually_eq.fun_comp hf.ae_eq_mk _⟩ end namespace is_compact variables [topological_space Ξ±] [measurable_space Ξ±] {ΞΌ : measure Ξ±} {s : set Ξ±} lemma finite_measure_of_nhds_within (hs : is_compact s) : (βˆ€ a ∈ s, ΞΌ.finite_at_filter (𝓝[s] a)) β†’ ΞΌ s < ⊀ := by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter] using hs.compl_mem_sets_of_nhds_within lemma finite_measure [locally_finite_measure ΞΌ] (hs : is_compact s) : ΞΌ s < ⊀ := hs.finite_measure_of_nhds_within $ Ξ» a ha, ΞΌ.finite_at_nhds_within _ _ lemma measure_zero_of_nhds_within (hs : is_compact s) : (βˆ€ a ∈ s, βˆƒ t ∈ 𝓝[s] a, ΞΌ t = 0) β†’ ΞΌ s = 0 := by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within end is_compact lemma metric.bounded.finite_measure [metric_space Ξ±] [proper_space Ξ±] [measurable_space Ξ±] {ΞΌ : measure Ξ±} [locally_finite_measure ΞΌ] {s : set Ξ±} (hs : metric.bounded s) : ΞΌ s < ⊀ := (measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2 ⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
30c20e70e4074db23ffd2d941b9f86865dc7f855
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/lean3_zulip_issues_1.lean
9e9cad56930dba91002f469f7bb45c3366c4f491
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,319
lean
example : Prop := βˆ€ n, (n:Nat) + n = n.succ example : Prop := βˆ€ n, n.succ = (n:Nat) + n example : Prop := βˆ€ n, (n:Nat) + n.succ = n example : Prop := βˆ€ n, n.succ + (n:Nat) = n example : Prop := βˆ€ n, (n.succ:Nat) + n = n example : Prop := βˆ€ n, (n:Nat).succ + n = n def fib: Nat β†’ Nat | 0 => 0 | 1 => 1 | n + 2 => fib n + fib (n + 1) theorem fib50Eq : fib 50 = 12586269025 := rfl inductive type : Type | A : type | B : type inductive val : type β†’ Type | cA : val type.A | cB : val type.B inductive wrap : Type | val : βˆ€ {t : type}, (val t) β†’ wrap def f : wrap β†’ Nat | wrap.val val.cA => 1 | _ => 1 example (a : Nat) : True := by have : βˆ€ n, n β‰₯ 0 β†’ a ≀ a := fun _ _ => Nat.le_refl .. exact True.intro example (αΎ° : Nat) : True := by have : βˆ€ n, n β‰₯ 0 β†’ αΎ° ≀ αΎ° := fun _ _ => Nat.le_refl .. exact True.intro inductive Vec.{u} (Ξ± : Type u) : Nat β†’ Type u | nil : Vec Ξ± 0 | cons : Ξ± β†’ {n : Nat} β†’ Vec Ξ± n β†’ Vec Ξ± (Nat.succ n) -- TODO: investigate why +1 doesn't work here constant Vars : Type structure Lang := (funcs : Nat β†’ Type) (consts : Type) inductive Term (L : Lang) : Type | const_term : L.consts β†’ Term L | var_term : Vars β†’ Term L | func_term (n : Nat) (f : L.funcs n) (v : Vec (Term L) n) : Term L
6a9482617fa5ca0eb6d55084e9929b484816f69c
d0664585e88edfefe384f2b01de54487029040bb
/exercises/entourages_from_pseudometric.lean
eda745c0a49d2f8eaf2286d5dc69ae9573023ed4
[]
no_license
ImperialCollegeLondon/uniform-structures
acf0a092d764925564595c59e7347e066d2a78ab
a41a170ef125b36bdac1e2201f54affa958d0349
refs/heads/master
1,668,088,958,039
1,592,495,127,000
1,592,495,127,000
269,964,470
2
0
null
null
null
null
UTF-8
Lean
false
false
2,390
lean
-- import the definitions of uniform space via entourages import uniform_structure.entourages -- import the definition of pseudometric space import pseudometric_space -- In this exercise we will show that a pseudometric on a set X -- gives rise to a collection of entourages for X -- This is a question about pseudometrics so let's put it -- in the pseudometric namespace namespace pseudometric -- Let X be a set (or a type), and let d be a pseudometric on X variables {X : Type} (d : X β†’ X β†’ ℝ) [is_pseudometric d] -- Define U βŠ† X Γ— X to be an entourage if there exists Ξ΅ > 0 such -- that d(x,y)≀Ρ β†’ (x,y) ∈ U def entourages := {U : set (X Γ— X) | βˆƒ Ξ΅ > 0, βˆ€ x y : X, d x y ≀ Ξ΅ β†’ (x,y) ∈ U} -- this lemma is true by definition lemma mem_entourages (U : set (X Γ— X)) : U ∈ entourages d ↔ βˆƒ Ξ΅ > 0, βˆ€ x y : X, d x y ≀ Ξ΅ β†’ (x,y) ∈ U := iff.rfl -- The exerise is to show that the 5 axioms of a uniform space are -- satisfied. -- Hint: You can `rw mem_entourages` to change from `U ∈ entourages d` to the -- explicit epsilon definition. -- Hint: if `hU : U ∈ entourages d` then `obtain ⟨Ρ, hΞ΅, hΞ΅U⟩ := hU` will -- get you the Ξ΅ which is a witness to U being an entourage for d. -- Axiom 1: the diagonal is in U lemma refl (U : set (X Γ— X)) (hU : U ∈ entourages d) : βˆ€ (x : X), (x, x) ∈ U := begin sorry end -- Axiom 2: anything bigger than an entourage is an entourage lemma bigger (U V : set (X Γ— X)) (hU : U ∈ entourages d) (hUV : U βŠ† V) : V ∈ entourages d := begin sorry end -- Axiom 3: Intersection of two entourages is an entourage lemma inter (U V : set (X Γ— X)) (hU : U ∈ entourages d) (hV : V ∈ entourages d) : U ∩ V ∈ entourages d := begin sorry end -- Axiom 4: the "square root" axiom. -- You'll need `mem_comp_ent` here (defined in the entourages file) lemma comp (U : set (X Γ— X)) (hU : U ∈ entourages d) : βˆƒ (V : set (X Γ— X)) (H : V ∈ entourages d), V ∘ V βŠ† U := begin sorry end -- Axiom 5: the "transpose" axiom. lemma symm (U : set (X Γ— X)) (hU : U ∈ entourages d) : {z : X Γ— X | (z.snd, z.fst) ∈ U} ∈ entourages d := begin sorry end definition to_entourages : uniform_space_entourage X := { entourages := entourages d, refl := refl d, bigger := bigger d, inter := inter d, comp := comp d, symm := symm d } end pseudometric
edf94b29da1f65d87dbb3cfa31d4ae99394a6b4d
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/polynomial/cyclotomic.lean
5f8487efc809d87e0c0995a6849aefd4b4a0e849
[ "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
30,740
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.arithmetic_function import data.polynomial.lifts import analysis.complex.roots_of_unity import field_theory.separable /-! # Cyclotomic polynomials. For `n : β„•` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - ΞΌ)`, where `ΞΌ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The MΓΆbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n β„€` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 β„€ = 1`, since there are no primitive cube roots of unity in `β„€`. The main example is `R = β„‚`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = β„‚`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n β„€`, we show in `minpoly_primitive_root_eq_cyclotomic` that `cyclotomic n β„€` is the minimal polynomial of any `n`-th primitive root of unity `ΞΌ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section integral_domain variables {R : Type*} [integral_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : β„•) (R : Type*) [integral_domain R] : polynomial R := ∏ ΞΌ in primitive_roots n R, (X - C ΞΌ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [integral_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [integral_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [integral_domain R] (p : β„•) [char_p R p] (hp : p β‰  2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : β„•) (R : Type*) [integral_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ Ξ» z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : β„•) (R : Type*) [integral_domain R] : cyclotomic' n R β‰  0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ΞΆ : R} {n : β„•} (h : is_primitive_root ΞΆ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (Ξ» (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ΞΆ : R} {n : β„•} (h : is_primitive_root ΞΆ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : β„•) (R : Type*) [integral_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end integral_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - ΞΌ)`, where `ΞΌ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ΞΆ : K} {n : β„•} (hpos : 0 < n) (h : is_primitive_root ΞΆ n) : X ^ n - 1 = ∏ ΞΆ in nth_roots_finset n K, (X - C ΞΆ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : β„•) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ΞΆ : K} {n : β„•} (h : is_primitive_root ΞΆ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ΞΆ : K} {n : β„•} (hpos : 0 < n) (h : is_primitive_root ΞΆ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : βˆ€ i ∈ nat.divisors n, cyclotomic' i K = ∏ ΞΌ in primitive_roots i K, (X - C ΞΌ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /β‚˜ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ΞΆ : K} {n : β„•} (hpos: 0 < n) (h : is_primitive_root ΞΆ n) : cyclotomic' n K = (X ^ n - 1) /β‚˜ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic {ΞΆ : K} {n : β„•} (h : is_primitive_root ΞΆ n) : (βˆƒ (P : polynomial β„€), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), revert h ΞΆ, apply nat.strong_induction_on n, intros k hk z hzeta, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_one, ring_hom.coe_of, and_self], }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, map_one, ring_hom.coe_of, and_self, map_sub] }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos hzeta hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial β„€ := (X ^ k - 1) /β‚˜ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos hzeta), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange], use Q₁, rw [(map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ΞΆ : K} {n : β„•+} (h : is_primitive_root ΞΆ n) : (βˆƒ! (P : polynomial β„€), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic h, rw exists_unique, use [P, hP.1], intros Q hQ, have mapinj : function.injective (map (int.cast_ring_hom K)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, rw [function.injective] at mapinj, apply mapinj, rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : β„•) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) lemma int_cyclotomic_rw {n : β„•} (h : n β‰  0) : cyclotomic n β„€ = (classical.some (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n h))) := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n β„€`. -/ lemma map_cyclotomic_int (n : β„•) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n β„€) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : β„•) : map (int.cast_ring_hom β„‚) (cyclotomic n β„€) = cyclotomic' n β„‚ ∧ (cyclotomic n β„€).degree = (cyclotomic' n β„‚).degree ∧ (cyclotomic n β„€).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact classical.some_spec (int_coeff_of_cyclotomic (complex.is_primitive_root_exp n hzero)) end lemma int_cyclotomic_unique {n : β„•} {P : polynomial β„€} (h : map (int.cast_ring_hom β„‚) P = cyclotomic' n β„‚) : P = cyclotomic n β„€ := begin have mapinj : function.injective (map (int.cast_ring_hom β„‚)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : β„•) {R S : Type*} [ring R] [ring S] (f : R β†’+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom β„‚) (X - 1) = cyclotomic' 1 β„‚, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom β„‚) (X + 1) = cyclotomic' 2 β„‚, { simp only [cyclotomic'_two β„‚ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : β„•) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : β„•) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R β‰  0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : β„•) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : β„•) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, norm_cast at hdeg, exact hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : β„•) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R; exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : β„•} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i β„€ = X ^ n - 1, { have mapinj : function.injective (map (int.cast_ring_hom β„‚)), { apply map_injective, simp only [int.cast_injective, int.coe_cast_ring_hom] }, apply mapinj, rw map_prod (int.cast_ring_hom β„‚) (Ξ» i, cyclotomic i β„€), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, ring_hom.coe_of, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : βˆ€ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i β„€), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (Ξ» i, cyclotomic i β„€), integer] end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using MΓΆbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : β„•} (hpos : 0 < n) (R : Type*) [comm_ring R] [nontrivial R] {K : Type*} [field K] (f : fraction_map (polynomial R) K) : f.to_map (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (f.to_map (X ^ i.snd - 1)) ^ ΞΌ i.fst := begin have h : βˆ€ (n : β„•), 0 < n β†’ ∏ i in nat.divisors n, f.to_map (cyclotomic i R) = f.to_map (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (Ξ» n hn, _) (Ξ» n hn, _)).1 h n hpos; rw [ne.def, fraction_map.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /β‚˜ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] [nontrivial R] {n : β„•} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /β‚˜ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : β„•} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m β‰  n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : β„•) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ ΞΌ in primitive_roots n R, (X - C ΞΌ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ΞΆ : K} {n : β„•} (h : is_primitive_root ΞΆ n) : cyclotomic n K = ∏ ΞΌ in primitive_roots n K, (X - C ΞΌ) := begin rw ←cyclotomic', revert h ΞΆ, apply nat.strong_induction_on n, intros k hk z hz, cases nat.eq_zero_or_pos k with hzero hpos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : βˆ€ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ (field.to_nontrivial K) _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end /-- Any `n`-th primitive root of unity is a root of `cyclotomic n β„€`.-/ lemma is_root_cyclotomic {n : β„•} {K : Type*} [field K] (hpos : 0 < n) {ΞΌ : K} (h : is_primitive_root ΞΌ n) : is_root (cyclotomic n K) ΞΌ := begin rw [← mem_roots (cyclotomic_ne_zero n K), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] [nontrivial R] {n : β„•} (hpos: 0 < n) (P : polynomial R) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin split, { intro hcycl, rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { intro hP, have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], split, { rwa [zero_add, mul_comm] }, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_series X p`. -/ lemma cyclotomic_eq_geom_series {R : Type*} [comm_ring R] [nontrivial R] {p : β„•} (hp : nat.prime p) : cyclotomic p R = geom_series X p := begin symmetry, refine (eq_cyclotomic_iff hp.pos _).mpr _, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end /-- The constant term of `cyclotomic n R` is `1` if `2 ≀ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : β„•} (hn : 2 ≀ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : βˆ€ j ∈ n.proper_divisors.erase 1, 2 ≀ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : βˆ€ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : β„•) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg_eq_neg_mul_symm, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : β„•)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : β„•} (hpos : 0 < n) {p : β„•} [hprime : fact p.prime] {a : β„•} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [nat.prime.coprime_iff_not_dvd hprime], by_contra h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : β„•)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : β„•} (hpos : 0 < n) {p : β„•} [hprime : fact p.prime] {a : β„•} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end /-- If `(a : β„•)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide `n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/ lemma order_of_root_cyclotomic {n : β„•} (hpos : 0 < n) {p : β„•} [hprime : fact p.prime] {a : β„•} (hn : Β¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n := begin set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)), have ha := coprime_of_root_cyclotomic hpos hroot, have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)), { replace hrootdiv := dvd_iff_is_root.2 hroot, simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv, simp only [hrootdiv, map_nat_cast, map_X, map_sub] }, by_contra hdiff, have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣ ∏ i in nat.proper_divisors n, cyclotomic i (zmod p), { suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1, { exact dvd_trans hdivm (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos (order_of_root_cyclotomic_dvd hpos hroot) hdiff) }, rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub, eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.coe_unit_of_coprime a ha, ← units.coe_pow, units.coe_eq_one], exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) }, have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1, { obtain ⟨P, hP⟩ := hdivcycl, obtain ⟨Q, hQ⟩ := hdiv, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ], exact ⟨P * Q, by ring⟩ }, have hnzero : ↑n β‰  (0 : (zmod p)), { intro ha, exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) }, rw [pow_two] at habs, replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero (map (int.cast_ring_hom (zmod p)) (X - a)) habs, simp only [map_nat_cast, map_X, map_sub] at habs, replace habs := degree_eq_zero_of_is_unit habs, rw [← C_eq_nat_cast, degree_X_sub_C] at habs, norm_cast at habs end end order end polynomial section minpoly open is_primitive_root polynomial complex /-- The minimal polynomial of a primitive `n`-th root of unity `ΞΌ` divides `cyclotomic n β„€`. -/ lemma minpoly_primitive_root_dvd_cyclotomic {n : β„•} {K : Type*} [field K] {ΞΌ : K} (h : is_primitive_root ΞΌ n) (hpos : 0 < n) [char_zero K] : minpoly β„€ ΞΌ ∣ cyclotomic n β„€ := begin apply minpoly.integer_dvd (is_integral h hpos) (cyclotomic.monic n β„€).is_primitive, simpa [aeval_def, evalβ‚‚_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end /-- `cyclotomic n β„€` is the minimal polynomial of a primitive `n`-th root of unity `ΞΌ`. -/ lemma cyclotomic_eq_minpoly {n : β„•} {K : Type*} [field K] {ΞΌ : K} (h : is_primitive_root ΞΌ n) (hpos : 0 < n) [char_zero K] : cyclotomic n β„€ = minpoly β„€ ΞΌ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n β„€) (minpoly_primitive_root_dvd_cyclotomic h hpos) _, simpa [nat_degree_cyclotomic n β„€] using totient_le_degree_minpoly h hpos end /-- `cyclotomic n β„€` is irreducible. -/ lemma cyclotomic.irreducible {n : β„•} (hpos : 0 < n) : irreducible (cyclotomic n β„€) := begin have h0 := (ne_of_lt hpos).symm, rw [cyclotomic_eq_minpoly (is_primitive_root_exp n h0) hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n h0).is_integral hpos, end end minpoly
e1fadcc96c067ce9ec737def815d3ff3313e44b1
bb31430994044506fa42fd667e2d556327e18dfe
/src/geometry/euclidean/circumcenter.lean
f03398d2a09fce64f6f59b01d91bd8bf0abb635e
[ "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
44,142
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real_inner_product_space namespace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp1, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps βŠ† s) (p : P) : set.pairwise ps (Ξ» p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise ps (Ξ» p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h hp1 hp2 hne), Ξ» h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h hp1 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps βŠ† s) (p : P) : (βˆƒ r, βˆ€ p1 ∈ ps, dist p1 p = r) ↔ βˆƒ r, βˆ€ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} [complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps βŠ† s) (hp : p βˆ‰ s) (hu : βˆƒ! cs : sphere P, cs.center ∈ s ∧ ps βŠ† (cs : set P)) : βˆƒ! csβ‚‚ : sphere P, csβ‚‚.center ∈ affine_span ℝ (insert p (s : set P)) ∧ (insert p ps) βŠ† (csβ‚‚ : set P) := begin haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps), rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y β‰  0 := dist_orthogonal_projection_ne_zero_of_not_mem hp, let yccβ‚‚ := (x * x + y * y - cr * cr) / (2 * y), let ccβ‚‚ := (yccβ‚‚ / y) β€’ (p -α΅₯ orthogonal_projection s p : V) +α΅₯ cc, let crβ‚‚ := real.sqrt (cr * cr + yccβ‚‚ * yccβ‚‚), use ⟨ccβ‚‚, crβ‚‚βŸ©, simp only, have hpo : p = (1 : ℝ) β€’ (p -α΅₯ orthogonal_projection s p : V) +α΅₯ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem _))) }, { intros p1 hp1, rw [sphere.mem_coe, mem_sphere, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk, dist_of_mem_subset_mk_sphere hp1 hcr, dist_eq_norm_vsub V ccβ‚‚ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, crβ‚ƒβŸ© ⟨hcc₃, hcrβ‚ƒβŸ©, simp only at hcc₃ hcr₃, obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ : βˆƒ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r β€’ (p -α΅₯ ↑((orthogonal_projection s) p)) +α΅₯ p0, { rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ }, have hcr₃' : βˆƒ r, βˆ€ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, Ξ» p1 hp1, dist_of_mem_subset_mk_sphere (set.mem_insert_of_mem _ hp1) hcrβ‚ƒβŸ©, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'', orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru ⟨cc₃', cr₃'⟩, simp only at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl, rw [←dist_of_mem_subset_mk_sphere (set.mem_insert_of_mem _ hp0) hcr₃, hcc₃'', ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', dist_of_mem_subset_mk_sphere hp0 hcr, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (|t₃|), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := dist_of_mem_subset_mk_sphere (set.mem_insert _ _) hcr₃, rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = yccβ‚‚ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = ccβ‚‚ at hcc₃'', congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma _root_.affine_independent.exists_unique_dist_eq {ΞΉ : Type*} [hne : nonempty ΞΉ] [fintype ΞΉ] {p : ΞΉ β†’ P} (ha : affine_independent ℝ p) : βˆƒ! cs : sphere P, cs.center ∈ affine_span ℝ (set.range p) ∧ set.range p βŠ† (cs : set P) := begin unfreezingI { induction hn : fintype.card ΞΉ with m hm generalizing ΞΉ }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ΞΉ := ⟨⟨i⟩, hi⟩, use ⟨p i, 0⟩, simp only [set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi default, set.singleton_subset_iff, sphere.mem_coe, mem_sphere, dist_self], exact ⟨rfl, rfl⟩ }, { rintros ⟨cc, cr⟩, simp only, rintros ⟨rfl, hdist⟩, simp_rw [set.singleton_subset_iff, sphere.mem_coe, mem_sphere, dist_self] at hdist, rw [hi default, hdist], exact ⟨rfl, rfl⟩ } }, { have i := hne.some, let ΞΉ2 := {x // x β‰  i}, have hc : fintype.card ΞΉ2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (Ξ» x, x β‰  i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ΞΉ2 := fintype.card_pos_iff.1 (hc.symm β–Έ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (Ξ» i2 : ΞΉ2, p i2) := ha.subtype _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (Ξ» i2 : ΞΉ2, p i2)), { change _ = insert _ (set.range (Ξ» i2 : {x | x β‰  i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, rw [hr, ←affine_span_insert_affine_span], refine exists_unique_dist_eq_of_insert (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert ha.not_mem_affine_span_diff i set.univ, change set.range (Ξ» i2 : {x | x β‰  i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The circumsphere of a simplex. -/ def circumsphere {n : β„•} (s : simplex ℝ P n) : sphere P := s.independent.exists_unique_dist_eq.some /-- The property satisfied by the circumsphere. -/ lemma circumsphere_unique_dist_eq {n : β„•} (s : simplex ℝ P n) : (s.circumsphere.center ∈ affine_span ℝ (set.range s.points) ∧ set.range s.points βŠ† s.circumsphere) ∧ (βˆ€ cs : sphere P, (cs.center ∈ affine_span ℝ (set.range s.points) ∧ set.range s.points βŠ† cs β†’ cs = s.circumsphere)) := s.independent.exists_unique_dist_eq.some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : β„•} (s : simplex ℝ P n) : P := s.circumsphere.center /-- The circumradius of a simplex. -/ def circumradius {n : β„•} (s : simplex ℝ P n) : ℝ := s.circumsphere.radius /-- The center of the circumsphere is the circumcenter. -/ @[simp] lemma circumsphere_center {n : β„•} (s : simplex ℝ P n) : s.circumsphere.center = s.circumcenter := rfl /-- The radius of the circumsphere is the circumradius. -/ @[simp] lemma circumsphere_radius {n : β„•} (s : simplex ℝ P n) : s.circumsphere.radius = s.circumradius := rfl /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : β„•} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumsphere_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : β„•} (s : simplex ℝ P n) (i : fin (n + 1)) : dist (s.points i) s.circumcenter = s.circumradius := dist_of_mem_subset_sphere (set.mem_range_self _) s.circumsphere_unique_dist_eq.1.2 /-- All points lie in the circumsphere. -/ lemma mem_circumsphere {n : β„•} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i ∈ s.circumsphere := s.dist_circumcenter_eq_circumradius i /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : β„•} (s : simplex ℝ P n) : βˆ€ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : β„•} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : βˆ€ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩, simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, sphere.ext_iff, set.forall_range_iff, mem_sphere, true_and] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : β„•} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : βˆ€ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumsphere_unique_dist_eq.2 ⟨p, r⟩, simp only [hp, hr, forall_const, eq_self_iff_true, subset_sphere, sphere.ext_iff, set.forall_range_iff, mem_sphere, true_and] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : β„•} (s : simplex ℝ P n) : 0 ≀ s.circumradius := s.dist_circumcenter_eq_circumradius 0 β–Έ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : β„•} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := s.independent.injective.ne (dec_trivial : (0 : fin (n + 2)) β‰  1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise set.univ (Ξ» i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_pair_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -α΅₯ s.points 0), ←one_smul ℝ (s.points j -α΅₯ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (Ξ» i, hr i (set.mem_univ _))).symm end /-- Reindexing a simplex along an `equiv` of index types does not change the circumsphere. -/ @[simp] lemma circumsphere_reindex {m n : β„•} (s : simplex ℝ P m) (e : fin (m + 1) ≃ fin (n + 1)) : (s.reindex e).circumsphere = s.circumsphere := begin refine s.circumsphere_unique_dist_eq.2 _ ⟨_, _⟩; rw ←s.reindex_range_points e, { exact (s.reindex e).circumsphere_unique_dist_eq.1.1 }, { exact (s.reindex e).circumsphere_unique_dist_eq.1.2 } end /-- Reindexing a simplex along an `equiv` of index types does not change the circumcenter. -/ @[simp] lemma circumcenter_reindex {m n : β„•} (s : simplex ℝ P m) (e : fin (m + 1) ≃ fin (n + 1)) : (s.reindex e).circumcenter = s.circumcenter := by simp_rw [←circumcenter, circumsphere_reindex] /-- Reindexing a simplex along an `equiv` of index types does not change the circumradius. -/ @[simp] lemma circumradius_reindex {m n : β„•} (s : simplex ℝ P m) (e : fin (m + 1) ≃ fin (n + 1)) : (s.reindex e).circumradius = s.circumradius := by simp_rw [←circumradius, circumsphere_reindex] local attribute [instance] affine_subspace.to_add_torsor /-- The orthogonal projection of a point `p` onto the hyperplane spanned by the simplex's points. -/ def orthogonal_projection_span {n : β„•} (s : simplex ℝ P n) : P →ᡃ[ℝ] affine_span ℝ (set.range s.points) := orthogonal_projection (affine_span ℝ (set.range s.points)) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : β„•} (s : simplex ℝ P n) {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ affine_span ℝ (set.range s.points)) : s.orthogonal_projection_span (r β€’ (p2 -α΅₯ s.orthogonal_projection_span p2 : V) +α΅₯ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ lemma coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection {n : β„•} {r₁ : ℝ} (s : simplex ℝ P n) {p p₁o : P} (hp₁o : p₁o ∈ affine_span ℝ (set.range s.points)) : ↑(s.orthogonal_projection_span (r₁ β€’ (p -α΅₯ ↑(s.orthogonal_projection_span p)) +α΅₯ p₁o)) = p₁o := congr_arg coe (orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ _ hp₁o) lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {n : β„•} (s : simplex ℝ P n) {p1 : P} (p2 : P) (hp1 : p1 ∈ affine_span ℝ (set.range s.points)) : dist p1 p2 * dist p1 p2 = dist p1 (s.orthogonal_projection_span p2) * dist p1 (s.orthogonal_projection_span p2) + dist p2 (s.orthogonal_projection_span p2) * dist p2 (s.orthogonal_projection_span p2) := begin rw [pseudo_metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (s.orthogonal_projection_span p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal _ p2), end lemma dist_circumcenter_sq_eq_sq_sub_circumradius {n : β„•} {r : ℝ} (s : simplex ℝ P n) {p₁ : P} (h₁ : βˆ€ (i : fin (n + 1)), dist (s.points i) p₁ = r) (h₁' : ↑((s.orthogonal_projection_span) p₁) = s.circumcenter) (h : s.points 0 ∈ affine_span ℝ (set.range s.points)) : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := begin rw [dist_comm, ←h₁ 0, s.dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h], simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius], end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : β„•} (s : simplex ℝ P n) {p : P} (hr : βˆƒ r, βˆ€ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := begin change βˆƒ r : ℝ, βˆ€ i, (Ξ» x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem p) (Ξ» i, hr _ (set.mem_range_self i)), end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : β„•} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : βˆ€ i, dist (s.points i) p = r) : ↑(s.orthogonal_projection_span p) = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : β„•} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : β„•} (h : fs.card = m + 1) : ↑((s.face h).orthogonal_projection_span s.circumcenter) = (s.face h).circumcenter := begin have hr : βˆƒ r, βˆ€ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : β„•} {s₁ sβ‚‚ : simplex ℝ P n} (h : set.range s₁.points = set.range sβ‚‚.points) : s₁.circumcenter = sβ‚‚.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range sβ‚‚.points) := h β–Έ s₁.circumcenter_mem_affine_span, have hr : βˆ€ i, dist (sβ‚‚.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : sβ‚‚.points i ∈ set.range sβ‚‚.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact sβ‚‚.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : β„•) | point_index : fin (n + 1) β†’ points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : β„•) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : β„•) : fin (n + 1) β†ͺ points_with_circumcenter_index n := ⟨λ i, point_index i, Ξ» _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {Ξ± : Type*} [add_comm_monoid Ξ±] {n : β„•} (f : points_with_circumcenter_index n β†’ Ξ±) : βˆ‘ i, f i = (βˆ‘ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, Ξ» _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = βˆ‘ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [finset.mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : β„•} (s : simplex ℝ P n) : points_with_circumcenter_index n β†’ P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : β„•} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : β„•} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : β„•} (i : fin (n + 1)) : points_with_circumcenter_index n β†’ ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : β„•} (i : fin (n + 1)) : βˆ‘ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : β„•} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 β‰  i := Ξ» h, hn (h β–Έ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : β„•} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n β†’ ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : β„•} {fs : finset (fin (n + 1))} (h : fs.nonempty) : βˆ‘ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : β„•} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (Ξ» i wi, wi β€’ (s.points i -α΅₯ classical.choice add_torsor.nonempty)) fs.subset_univ (Ξ» i, zero_smul ℝ _), set.indicator_apply], congr, end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : β„•) : points_with_circumcenter_index n β†’ ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : β„•) : βˆ‘ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : β„•} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ β‰  iβ‚‚`. -/ def reflection_circumcenter_weights_with_circumcenter {n : β„•} (i₁ iβ‚‚ : fin (n + 1)) : points_with_circumcenter_index n β†’ ℝ | (point_index i) := if i = i₁ ∨ i = iβ‚‚ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : β„•} {i₁ iβ‚‚ : fin (n + 1)} (h : i₁ β‰  iβ‚‚) : βˆ‘ i, reflection_circumcenter_weights_with_circumcenter i₁ iβ‚‚ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simpa only [if_true, mem_univ, disjoint_singleton] using h } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : β„•} (s : simplex ℝ P n) {i₁ iβ‚‚ : fin (n + 1)} (h : i₁ β‰  iβ‚‚) : reflection (affine_span ℝ (s.points '' {i₁, iβ‚‚})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ iβ‚‚) := begin have hc : card ({i₁, iβ‚‚} : finset (fin (n + 1))) = 2, { simp [h] }, -- Making the next line a separate definition helps the elaborator: set W : affine_subspace ℝ P := affine_span ℝ (s.points '' {i₁, iβ‚‚}) with W_def, have h_faces : ↑(orthogonal_projection W s.circumcenter) = ↑((s.face hc).orthogonal_projection_span s.circumcenter), { apply eq_orthogonal_projection_of_eq_subspace, simp }, rw [euclidean_geometry.reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] [complete_space s.direction] : cospherical ps ↔ βˆƒ (center ∈ s) (radius : ℝ), βˆ€ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ }, { exact Ξ» ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] [finite_dimensional ℝ s.direction] : cospherical ps ↔ βˆƒ (center ∈ s) (radius : ℝ), βˆ€ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : βˆƒ r : ℝ, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm β–Έ hc, exact (sx.eq_circumradius_of_dist_eq hc (Ξ» i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumradius = sxβ‚‚.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : βˆƒ r : ℝ, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumradius = r := begin haveI : nonempty (⊀ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumradius = sxβ‚‚.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : βˆƒ c : P, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm β–Έ hc, exact (sx.eq_circumcenter_of_dist_eq hc (Ξ» i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumcenter = sxβ‚‚.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : βˆƒ c : P, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumcenter = c := begin haveI : nonempty (⊀ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumcenter = sxβ‚‚.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumsphere. -/ lemma exists_circumsphere_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : βˆƒ c : sphere P, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumsphere = c := begin obtain ⟨r, hr⟩ := exists_circumradius_eq_of_cospherical_subset h hd hc, obtain ⟨c, hc⟩ := exists_circumcenter_eq_of_cospherical_subset h hd hc, exact ⟨⟨c, r⟩, Ξ» sx hsx, sphere.ext _ _ (hc sx hsx) (hr sx hsx)⟩ end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumsphere. -/ lemma circumsphere_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps βŠ† s) [nonempty s] {n : β„•} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumsphere = sxβ‚‚.circumsphere := begin rcases exists_circumsphere_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- All n-simplices among cospherical points in n-space have the same circumsphere. -/ lemma exists_circumsphere_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : βˆƒ c : sphere P, βˆ€ sx : simplex ℝ P n, set.range sx.points βŠ† ps β†’ sx.circumsphere = c := begin haveI : nonempty (⊀ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumsphere_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumsphere. -/ lemma circumsphere_eq_of_cospherical {ps : set P} {n : β„•} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sxβ‚‚ : simplex ℝ P n} (hsx₁ : set.range sx₁.points βŠ† ps) (hsxβ‚‚ : set.range sxβ‚‚.points βŠ† ps) : sx₁.circumsphere = sxβ‚‚.circumsphere := begin rcases exists_circumsphere_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sxβ‚‚ hsxβ‚‚] end /-- Suppose all distances from `p₁` and `pβ‚‚` to the points of a simplex are equal, and that `p₁` and `pβ‚‚` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `pβ‚‚` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : β„•} {s : simplex ℝ P n} {p p₁ pβ‚‚ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hpβ‚‚ : pβ‚‚ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : βˆ€ i, dist (s.points i) p₁ = r) (hβ‚‚ : βˆ€ i, dist (s.points i) pβ‚‚ = r) : p₁ = pβ‚‚ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) pβ‚‚ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have hβ‚‚' := s.orthogonal_projection_eq_circumcenter_of_dist_eq hβ‚‚, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hpβ‚‚, obtain ⟨r₁, p₁o, hp₁o, hpβ‚βŸ© := hp₁, obtain ⟨rβ‚‚, pβ‚‚o, hpβ‚‚o, hpβ‚‚βŸ© := hpβ‚‚, obtain rfl : ↑(s.orthogonal_projection_span p₁) = p₁o, { subst hp₁, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hp₁o }, rw h₁' at hp₁, obtain rfl : ↑(s.orthogonal_projection_span pβ‚‚) = pβ‚‚o, { subst hpβ‚‚, exact s.coe_orthogonal_projection_vadd_smul_vsub_orthogonal_projection hpβ‚‚o }, rw hβ‚‚' at hpβ‚‚, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius h₁ h₁' h, have hdβ‚‚ : dist pβ‚‚ s.circumcenter * dist pβ‚‚ s.circumcenter = r * r - s.circumradius * s.circumradius := s.dist_circumcenter_sq_eq_sq_sub_circumradius hβ‚‚ hβ‚‚' h, rw [←hdβ‚‚, hp₁, hpβ‚‚, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = s.orthogonal_projection_span p, { rw simplex.orthogonal_projection_span at hp, rw [hp₁, hpβ‚‚, ←hp], simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] }, { have hz : βŸͺp -α΅₯ orthogonal_projection span_s p, p -α΅₯ orthogonal_projection span_s p⟫ β‰  0, by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hpβ‚‚], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection p rβ‚‚ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
f89eb4464ea0831a734002ade9620f735e2ac0a3
367134ba5a65885e863bdc4507601606690974c1
/src/topology/algebra/normed_group.lean
fbc3cf1117fb4456ed8f0ba7be053821ce92a478
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,431
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 topology.algebra.group_completion import topology.metric_space.completion /-! # Completion of normed groups In this file we show that the completion of a normed group is naturally a normed group. ## Main declaration * `uniform_space.completion.normed_group`: the normed group instance on the completion of a normed group -/ noncomputable theory variables (V : Type*) namespace uniform_space namespace completion instance [uniform_space V] [has_norm V] : has_norm (completion V) := { norm := completion.extension has_norm.norm } @[simp] lemma norm_coe {V} [normed_group V] (v : V) : βˆ₯(v : completion V)βˆ₯ = βˆ₯vβˆ₯ := completion.extension_coe uniform_continuous_norm v instance [normed_group V] : normed_group (completion V) := { dist_eq := begin intros x y, apply completion.induction_onβ‚‚ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extensionβ‚‚ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, metric.completion.dist_eq, dist_eq_norm] } end, .. (show add_comm_group (completion V), by apply_instance), .. (show metric_space (completion V), by apply_instance) } end completion end uniform_space
8482e133da8c01c1e7884d4e514f2040905dfb56
17d3c61bf162bf88be633867ed4cb201378a8769
/tests/lean/run/basic_monitor1.lean
5e602a5e7750a4e78ca32712e0d484d78e760275
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
291
lean
meta def basic_monitor : vm_monitor nat := { init := 0, step := Ξ» s, return (trace ("step " ++ s^.to_string) (Ξ» u, s+1)) >> failure } run_command vm_monitor.register `basic_monitor set_option debugger true def f : nat β†’ nat | 0 := 0 | (a+1) := f a vm_eval trace "a" (Ξ» u, f 4)
b8ae839f1f4cade30ec7f0a2e340e046c3890e2c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/reserved_notation_auto.lean
1fb6601dd2878fd9ad5bf4e5e6482e5f2651d2df
[]
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
275
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort namespace Mathlib end Mathlib
d0c7c523de8fbf1478ec34383d58130831b77eb6
618003631150032a5676f229d13a079ac875ff77
/src/tactic/monotonicity/lemmas.lean
17e8a8d131b9bdcebc09790e212501ceaf5bdaf0
[ "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
1,737
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 variables {Ξ± : Type*} @[mono] lemma mul_mono_nonneg {x y z : Ξ±} [ordered_semiring Ξ±] (h' : 0 ≀ z) (h : x ≀ y) : x * z ≀ y * z := by apply mul_le_mul_of_nonneg_right; assumption lemma gt_of_mul_lt_mul_neg_right {a b c : Ξ±} [linear_ordered_ring Ξ±] (h : a * c < b * c) (hc : c ≀ 0) : a > b := have nhc : -c β‰₯ 0, from neg_nonneg_of_nonpos hc, have h2 : -(b * c) < -(a * c), from neg_lt_neg h, have h3 : b * (-c) < a * (-c), from calc b * (-c) = - (b * c) : by rewrite neg_mul_eq_mul_neg ... < - (a * c) : h2 ... = a * (-c) : by rewrite neg_mul_eq_mul_neg, lt_of_mul_lt_mul_right h3 nhc @[mono] lemma mul_mono_nonpos {x y z : Ξ±} [linear_ordered_ring Ξ±] (h' : 0 β‰₯ z) (h : y ≀ x) : x * z ≀ y * z := begin classical, by_contradiction h'', revert h, apply not_le_of_lt, apply gt_of_mul_lt_mul_neg_right _ h', apply lt_of_not_ge h'' end @[mono] lemma nat.sub_mono_left_strict {x y z : β„•} (h' : z ≀ x) (h : x < y) : x - z < y - z := begin have : z ≀ y, { transitivity, assumption, apply le_of_lt h, }, apply @nat.lt_of_add_lt_add_left z, rw [nat.add_sub_of_le,nat.add_sub_of_le]; solve_by_elim end @[mono] lemma nat.sub_mono_right_strict {x y z : β„•} (h' : x ≀ z) (h : y < x) : z - x < z - y := begin have h'' : y ≀ z, { transitivity, apply le_of_lt h, assumption }, apply @nat.lt_of_add_lt_add_right _ x, rw [nat.sub_add_cancel h'], apply @lt_of_le_of_lt _ _ _ (z - y + y), rw [nat.sub_add_cancel h''], apply nat.add_lt_add_left h end
a7cfbeee05457ef301469f3f06a195e25d61aaf3
ec62863c729b7eedee77b86d974f2c529fa79d25
/12/b.lean
6629149290820b87956ea2bf8cef4e2f1a00bbab
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
1,195
lean
structure Ship := x : Int y : Int dx : Int dy : Int instance : Inhabited Ship := ⟨⟨0,0,1,0⟩⟩ def fakeCos (n : Int) : Int := match (((n / 90) % 4 + 4) % 4 : Int) with | 0 => 1 | 1 => 0 | 2 => -1 | 3 => 0 | _ => panic! "impossible" def fakeSin (n : Int) : Int := fakeCos (90 - n) def move (s : Ship) : Char β†’ Int β†’ Ship | 'N', n => { s with dy := s.dy + n } | 'S', n => { s with dy := s.dy - n } | 'E', n => { s with dx := s.dx + n } | 'W', n => { s with dx := s.dx - n } | 'L', n => { s with dx := fakeCos n * s.dx - fakeSin n * s.dy, dy := fakeSin n * s.dx + fakeCos n * s.dy } | 'R', n => { s with dx := fakeCos n * s.dx + fakeSin n * s.dy, dy := - fakeSin n * s.dx + fakeCos n * s.dy } | 'F', n => { s with x := s.x + n * s.dx, y := s.y + n * s.dy } | _, _ => panic! "invalid command" def moveStr (s : Ship) (str : String) : Ship := match str.toList with | c :: rest => move s c (String.mk rest).toNat! | _ => panic! "invalid command" def Int.abs (n : Int) : Int := if n < 0 then -n else n def main : IO Unit := do let instrs ← IO.FS.lines "a.in" let result : Ship := instrs.foldl moveStr { x := 0, y := 0, dx := 10, dy := 1 } IO.print s!"{result.x.abs + result.y.abs}\n"
ae1e48612e4a137fefa27307a118b2941e591c03
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebraic_topology/simplicial_set.lean
762b3a27540fb88a799b60b0445733ed6348d8b6
[ "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
5,148
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import algebraic_topology.simplicial_object import category_theory.yoneda import category_theory.limits.types import category_theory.limits.presheaf import algebraic_topology.topological_simplex /-! A simplicial set is just a simplicial object in `Type`, i.e. a `Type`-valued presheaf on the simplex category. (One might be tempted to call these "simplicial types" when working in type-theoretic foundations, but this would be unnecessarily confusing given the existing notion of a simplicial type in homotopy type theory.) We define the standard simplices `Ξ”[n]` as simplicial sets, and their boundaries `βˆ‚Ξ”[n]` and horns `Ξ›[n, i]`. (The notations are available via `open_locale simplicial`.) ## Future work There isn't yet a complete API for simplices, boundaries, and horns. As an example, we should have a function that constructs from a non-surjective order preserving function `fin n β†’ fin n` a morphism `Ξ”[n] ⟢ βˆ‚Ξ”[n]`. -/ universes v u open category_theory open_locale simplicial /-- The category of simplicial sets. This is the category of contravariant functors from `simplex_category` to `Type u`. -/ @[derive [large_category, limits.has_limits, limits.has_colimits]] def sSet : Type (u+1) := simplicial_object (Type u) namespace sSet /-- The `n`-th standard simplex `Ξ”[n]` associated with a nonempty finite linear order `n` is the Yoneda embedding of `n`. -/ def standard_simplex : simplex_category β₯€ sSet := yoneda localized "notation `Ξ”[`n`]` := sSet.standard_simplex.obj (simplex_category.mk n)" in simplicial instance : inhabited sSet := βŸ¨Ξ”[0]⟩ section /-- The `m`-simplices of the `n`-th standard simplex are the monotone maps from `fin (m+1)` to `fin (n+1)`. -/ def as_preorder_hom {n} {m} (Ξ± : Ξ”[n].obj m) : preorder_hom (fin (m.unop.len+1)) (fin (n+1)) := Ξ±.to_preorder_hom end /-- The boundary `βˆ‚Ξ”[n]` of the `n`-th standard simplex consists of all `m`-simplices of `standard_simplex n` that are not surjective (when viewed as monotone function `m β†’ n`). -/ def boundary (n : β„•) : sSet := { obj := Ξ» m, {Ξ± : Ξ”[n].obj m // Β¬ function.surjective (as_preorder_hom Ξ±)}, map := Ξ» m₁ mβ‚‚ f Ξ±, ⟨f.unop ≫ (Ξ± : Ξ”[n].obj m₁), by { intro h, apply Ξ±.property, exact function.surjective.of_comp h }⟩ } localized "notation `βˆ‚Ξ”[`n`]` := sSet.boundary n" in simplicial /-- The inclusion of the boundary of the `n`-th standard simplex into that standard simplex. -/ def boundary_inclusion (n : β„•) : βˆ‚Ξ”[n] ⟢ Ξ”[n] := { app := Ξ» m (Ξ± : {Ξ± : Ξ”[n].obj m // _}), Ξ± } /-- `horn n i` (or `Ξ›[n, i]`) is the `i`-th horn of the `n`-th standard simplex, where `i : n`. It consists of all `m`-simplices `Ξ±` of `Ξ”[n]` for which the union of `{i}` and the range of `Ξ±` is not all of `n` (when viewing `Ξ±` as monotone function `m β†’ n`). -/ def horn (n : β„•) (i : fin (n+1)) : sSet := { obj := Ξ» m, { Ξ± : Ξ”[n].obj m // set.range (as_preorder_hom Ξ±) βˆͺ {i} β‰  set.univ }, map := Ξ» m₁ mβ‚‚ f Ξ±, ⟨f.unop ≫ (Ξ± : Ξ”[n].obj m₁), begin intro h, apply Ξ±.property, rw set.eq_univ_iff_forall at h ⊒, intro j, apply or.imp _ id (h j), intro hj, exact set.range_comp_subset_range _ _ hj, end⟩ } localized "notation `Ξ›[`n`, `i`]` := sSet.horn (n : β„•) i" in simplicial /-- The inclusion of the `i`-th horn of the `n`-th standard simplex into that standard simplex. -/ def horn_inclusion (n : β„•) (i : fin (n+1)) : Ξ›[n, i] ⟢ Ξ”[n] := { app := Ξ» m (Ξ± : {Ξ± : Ξ”[n].obj m // _}), Ξ± } section examples open_locale simplicial /-- The simplicial circle. -/ noncomputable def S1 : sSet := limits.colimit $ limits.parallel_pair ((standard_simplex.map $ simplex_category.Ξ΄ 0) : Ξ”[0] ⟢ Ξ”[1]) (standard_simplex.map $ simplex_category.Ξ΄ 1) end examples /-- Truncated simplicial sets. -/ @[derive [large_category, limits.has_limits, limits.has_colimits]] def truncated (n : β„•) := simplicial_object.truncated (Type u) n /-- The skeleton functor on simplicial sets. -/ def sk (n : β„•) : sSet β₯€ sSet.truncated n := simplicial_object.sk n instance {n} : inhabited (sSet.truncated n) := ⟨(sk n).obj $ Ξ”[0]⟩ end sSet /-- The functor associating the singular simplicial set to a topological space. -/ noncomputable def Top.to_sSet : Top β₯€ sSet := colimit_adj.restricted_yoneda simplex_category.to_Top /-- The geometric realization functor. -/ noncomputable def sSet.to_Top : sSet β₯€ Top := colimit_adj.extend_along_yoneda simplex_category.to_Top /-- Geometric realization is left adjoint to the singular simplicial set construction. -/ noncomputable def sSet_Top_adj : sSet.to_Top ⊣ Top.to_sSet := colimit_adj.yoneda_adjunction _ /-- The geometric realization of the representable simplicial sets agree with the usual topological simplices. -/ noncomputable def sSet.to_Top_simplex : (yoneda : simplex_category β₯€ _) β‹™ sSet.to_Top β‰… simplex_category.to_Top := colimit_adj.is_extension_along_yoneda _
d6c5cb82a998fcc86f48d7b4e986e76fefbae7ea
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/set/basic.lean
1782832b7584c07bd2c0a68560eddb8a9d7ab5b4
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
57,193
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.basic tactic.finish data.subtype logic.unique open function /- set coercion to a type -/ namespace set instance {Ξ± : Type*} : has_coe_to_sort (set Ξ±) := ⟨_, Ξ» s, {x // x ∈ s}⟩ end set section set_coe universe u variables {Ξ± : Type u} theorem set.set_coe_eq_subtype (s : set Ξ±) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set Ξ±} {p : s β†’ Prop} : (βˆ€ x : s, p x) ↔ (βˆ€ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set Ξ±} {p : s β†’ Prop} : (βˆƒ x : s, p x) ↔ (βˆƒ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : βˆ€ {s t : set Ξ±} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' β–Έ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set Ξ±} {a b : s} : (↑a : Ξ±) = ↑b β†’ a = b := subtype.eq theorem set_coe.ext_iff {s : set Ξ±} {a b : s} : (↑a : Ξ±) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h β–Έ rfl) end set_coe lemma subtype.mem {Ξ± : Type*} {s : set Ξ±} (p : s) : (p : Ξ±) ∈ s := p.property namespace set universes u v w x variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {ΞΉ : Sort x} {a : Ξ±} {s t : set Ξ±} instance : inhabited (set Ξ±) := βŸ¨βˆ…βŸ© @[extensionality] theorem ext {a b : set Ξ±} (h : βˆ€ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set Ξ±) : s = t ↔ βˆ€ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {Ξ± : Type u} {x : Ξ±} {s t : set Ξ±} (hx : x ∈ s) (h : s βŠ† t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : Ξ±} {p : Ξ± β†’ Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : Ξ±} {P : Ξ± β†’ Prop} : a βˆ‰ {a : Ξ± | P a} = Β¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set Ξ±} : {x | x ∈ s} = s := rfl lemma set_of_app_iff {p : Ξ± β†’ Prop} {x : Ξ±} : { x | p x } x ↔ p x := iff.refl _ theorem mem_def {a : Ξ±} {s : set Ξ±} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set Ξ±) [H : decidable_pred s] : βˆ€ a, decidable (a ∈ s) := H instance decidable_set_of (p : Ξ± β†’ Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : Ξ± β†’ Prop} : {a | p a} βŠ† {a | q a} ↔ (βˆ€a, p a β†’ q a) := iff.rfl @[simp] lemma sep_set_of {Ξ±} {p q : Ξ± β†’ Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {Ξ±} {s : set Ξ±} : {a | a ∈ s} = s := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set Ξ±} : (s βŠ† t) = βˆ€ x, x ∈ s β†’ x ∈ t := rfl @[refl] theorem subset.refl (a : set Ξ±) : a βŠ† a := assume x, id @[trans] theorem subset.trans {a b c : set Ξ±} (ab : a βŠ† b) (bc : b βŠ† c) : a βŠ† c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {Ξ± : Type u} {x y : Ξ±} {s : set Ξ±} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm β–Έ h theorem subset.antisymm {a b : set Ξ±} (h₁ : a βŠ† b) (hβ‚‚ : b βŠ† a) : a = b := ext (Ξ» x, iff.intro (Ξ» ina, h₁ ina) (Ξ» inb, hβ‚‚ inb)) theorem subset.antisymm_iff {a b : set Ξ±} : a = b ↔ a βŠ† b ∧ b βŠ† a := ⟨λ e, e β–Έ ⟨subset.refl _, subset.refl _⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, subset.antisymm h₁ hβ‚‚βŸ© -- an alterantive name theorem eq_of_subset_of_subset {a b : set Ξ±} (h₁ : a βŠ† b) (hβ‚‚ : b βŠ† a) : a = b := subset.antisymm h₁ hβ‚‚ theorem mem_of_subset_of_mem {s₁ sβ‚‚ : set Ξ±} {a : Ξ±} : s₁ βŠ† sβ‚‚ β†’ a ∈ s₁ β†’ a ∈ sβ‚‚ := assume h₁ hβ‚‚, h₁ hβ‚‚ theorem not_subset : (Β¬ s βŠ† t) ↔ βˆƒa, a ∈ s ∧ a βˆ‰ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s βŠ‚ t` means that `s` is a strict subset of `t`, that is, `s βŠ† t` but `s β‰  t`. -/ def strict_subset (s t : set Ξ±) := s βŠ† t ∧ s β‰  t instance : has_ssubset (set Ξ±) := ⟨strict_subset⟩ theorem ssubset_def : (s βŠ‚ t) = (s βŠ† t ∧ s β‰  t) := rfl lemma exists_of_ssubset {Ξ± : Type u} {s t : set Ξ±} (h : s βŠ‚ t) : (βˆƒx∈t, x βˆ‰ s) := classical.by_contradiction $ assume hn, have t βŠ† s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set Ξ±} : s βŠ‚ t ↔ s βŠ† t ∧ Β¬ t βŠ† s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : Ξ±) : Β¬ (x ∈ (βˆ… : set Ξ±)) := assume h : x ∈ βˆ…, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : Β¬ (a βˆ‰ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (βˆ… : set Ξ±) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : Ξ±) : x ∈ (βˆ… : set Ξ±) = false := rfl @[simp] theorem set_of_false : {a : Ξ± | false} = βˆ… := rfl theorem eq_empty_iff_forall_not_mem {s : set Ξ±} : s = βˆ… ↔ βˆ€ x, x βˆ‰ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set Ξ±} {x : Ξ±} (h : x ∈ s) : s β‰  βˆ… := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set Ξ±) : βˆ… βŠ† s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set Ξ±} : s βŠ† βˆ… ↔ s = βˆ… := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set Ξ±} : s βŠ† βˆ… β†’ s = βˆ… := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set Ξ±} : s β‰  βˆ… ↔ βˆƒ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set Ξ±} : s β‰  βˆ… β†’ βˆƒ x, x ∈ s := ne_empty_iff_exists_mem.1 theorem coe_nonempty_iff_ne_empty {s : set Ξ±} : nonempty s ↔ s β‰  βˆ… := nonempty_subtype.trans ne_empty_iff_exists_mem.symm -- TODO: remove when simplifier stops rewriting `a β‰  b` to `Β¬ a = b` theorem not_eq_empty_iff_exists {s : set Ξ±} : Β¬ (s = βˆ…) ↔ βˆƒ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set Ξ±} (h : t βŠ† s) (e : s = βˆ…) : t = βˆ… := subset_empty_iff.1 $ e β–Έ h theorem subset_ne_empty {s t : set Ξ±} (h : t βŠ† s) : t β‰  βˆ… β†’ s β‰  βˆ… := mt (subset_eq_empty h) theorem ball_empty_iff {p : Ξ± β†’ Prop} : (βˆ€ x ∈ (βˆ… : set Ξ±), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ Ξ± = {x | true} := rfl @[simp] theorem mem_univ (x : Ξ±) : x ∈ @univ Ξ± := trivial theorem empty_ne_univ [h : inhabited Ξ±] : (βˆ… : set Ξ±) β‰  univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set Ξ±) : s βŠ† univ := Ξ» x H, trivial theorem univ_subset_iff {s : set Ξ±} : univ βŠ† s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set Ξ±} : univ βŠ† s β†’ s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set Ξ±} : s = univ ↔ βˆ€ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set Ξ±} : (βˆ€ x, x ∈ s) β†’ s = univ := eq_univ_iff_forall.2 @[simp] lemma univ_eq_empty_iff {Ξ± : Type*} : (univ : set Ξ±) = βˆ… ↔ Β¬ nonempty Ξ± := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, Ξ» H x _, H ⟨x⟩⟩ lemma nonempty_iff_univ_ne_empty {Ξ± : Type*} : nonempty Ξ± ↔ (univ : set Ξ±) β‰  βˆ… := by classical; exact iff_not_comm.1 univ_eq_empty_iff lemma exists_mem_of_nonempty (Ξ±) : βˆ€ [nonempty Ξ±], βˆƒx:Ξ±, x ∈ (univ : set Ξ±) | ⟨x⟩ := ⟨x, trivial⟩ @[simp] lemma univ_ne_empty {Ξ±} [h : nonempty Ξ±] : (univ : set Ξ±) β‰  βˆ… := Ξ» e, univ_eq_empty_iff.1 e h instance univ_decidable : decidable_pred (@set.univ Ξ±) := Ξ» x, is_true trivial /- union -/ theorem union_def {s₁ sβ‚‚ : set Ξ±} : s₁ βˆͺ sβ‚‚ = {a | a ∈ s₁ ∨ a ∈ sβ‚‚} := rfl theorem mem_union_left {x : Ξ±} {a : set Ξ±} (b : set Ξ±) : x ∈ a β†’ x ∈ a βˆͺ b := or.inl theorem mem_union_right {x : Ξ±} {b : set Ξ±} (a : set Ξ±) : x ∈ b β†’ x ∈ a βˆͺ b := or.inr theorem mem_or_mem_of_mem_union {x : Ξ±} {a b : set Ξ±} (H : x ∈ a βˆͺ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : Ξ±} {a b : set Ξ±} {P : Prop} (H₁ : x ∈ a βˆͺ b) (Hβ‚‚ : x ∈ a β†’ P) (H₃ : x ∈ b β†’ P) : P := or.elim H₁ Hβ‚‚ H₃ theorem mem_union (x : Ξ±) (a b : set Ξ±) : x ∈ a βˆͺ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : Ξ±) (a b : set Ξ±) : x ∈ a βˆͺ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set Ξ±) : a βˆͺ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set Ξ±) : a βˆͺ βˆ… = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set Ξ±) : βˆ… βˆͺ a = a := ext (assume x, false_or _) theorem union_comm (a b : set Ξ±) : a βˆͺ b = b βˆͺ a := ext (assume x, or.comm) theorem union_assoc (a b c : set Ξ±) : (a βˆͺ b) βˆͺ c = a βˆͺ (b βˆͺ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set Ξ±) (βˆͺ) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set Ξ±) (βˆͺ) := ⟨union_comm⟩ theorem union_left_comm (s₁ sβ‚‚ s₃ : set Ξ±) : s₁ βˆͺ (sβ‚‚ βˆͺ s₃) = sβ‚‚ βˆͺ (s₁ βˆͺ s₃) := by finish theorem union_right_comm (s₁ sβ‚‚ s₃ : set Ξ±) : (s₁ βˆͺ sβ‚‚) βˆͺ s₃ = (s₁ βˆͺ s₃) βˆͺ sβ‚‚ := by finish theorem union_eq_self_of_subset_left {s t : set Ξ±} (h : s βŠ† t) : s βˆͺ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set Ξ±} (h : t βŠ† s) : s βˆͺ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set Ξ±) : s βŠ† s βˆͺ t := Ξ» x, or.inl @[simp] theorem subset_union_right (s t : set Ξ±) : t βŠ† s βˆͺ t := Ξ» x, or.inr theorem union_subset {s t r : set Ξ±} (sr : s βŠ† r) (tr : t βŠ† r) : s βˆͺ t βŠ† r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set Ξ±} : s βˆͺ t βŠ† u ↔ s βŠ† u ∧ t βŠ† u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ sβ‚‚ t₁ tβ‚‚ : set Ξ±} (h₁ : s₁ βŠ† sβ‚‚) (hβ‚‚ : t₁ βŠ† tβ‚‚) : s₁ βˆͺ t₁ βŠ† sβ‚‚ βˆͺ tβ‚‚ := by finish [subset_def] theorem union_subset_union_left {s₁ sβ‚‚ : set Ξ±} (t) (h : s₁ βŠ† sβ‚‚) : s₁ βˆͺ t βŠ† sβ‚‚ βˆͺ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ tβ‚‚ : set Ξ±} (h : t₁ βŠ† tβ‚‚) : s βˆͺ t₁ βŠ† s βˆͺ tβ‚‚ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set Ξ±} (h : s βŠ† t) (u : set Ξ±) : s βŠ† t βˆͺ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set Ξ±} (h : s βŠ† u) (t : set Ξ±) : s βŠ† t βˆͺ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set Ξ±} : s βˆͺ t = βˆ… ↔ s = βˆ… ∧ t = βˆ… := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ sβ‚‚ : set Ξ±} : s₁ ∩ sβ‚‚ = {a | a ∈ s₁ ∧ a ∈ sβ‚‚} := rfl theorem mem_inter_iff (x : Ξ±) (a b : set Ξ±) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : Ξ±) (a b : set Ξ±) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : Ξ±} {a b : set Ξ±} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : Ξ±} {a b : set Ξ±} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : Ξ±} {a b : set Ξ±} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set Ξ±) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set Ξ±) : a ∩ βˆ… = βˆ… := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set Ξ±) : βˆ… ∩ a = βˆ… := ext (assume x, false_and _) theorem inter_comm (a b : set Ξ±) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set Ξ±) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set Ξ±) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set Ξ±) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ sβ‚‚ s₃ : set Ξ±) : s₁ ∩ (sβ‚‚ ∩ s₃) = sβ‚‚ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ sβ‚‚ s₃ : set Ξ±) : (s₁ ∩ sβ‚‚) ∩ s₃ = (s₁ ∩ s₃) ∩ sβ‚‚ := by finish @[simp] theorem inter_subset_left (s t : set Ξ±) : s ∩ t βŠ† s := Ξ» x H, and.left H @[simp] theorem inter_subset_right (s t : set Ξ±) : s ∩ t βŠ† t := Ξ» x H, and.right H theorem subset_inter {s t r : set Ξ±} (rs : r βŠ† s) (rt : r βŠ† t) : r βŠ† s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set Ξ±} : r βŠ† s ∩ t ↔ r βŠ† s ∧ r βŠ† t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, subset_inter h₁ hβ‚‚βŸ© @[simp] theorem inter_univ (a : set Ξ±) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set Ξ±) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set Ξ±} (u : set Ξ±) (H : s βŠ† t) : s ∩ u βŠ† t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set Ξ±} (u : set Ξ±) (H : s βŠ† t) : u ∩ s βŠ† u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ sβ‚‚ t₁ tβ‚‚ : set Ξ±} (h₁ : s₁ βŠ† t₁) (hβ‚‚ : sβ‚‚ βŠ† tβ‚‚) : s₁ ∩ sβ‚‚ βŠ† t₁ ∩ tβ‚‚ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set Ξ±} (h : s βŠ† t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set Ξ±} (h : t βŠ† s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set Ξ±} : (s βˆͺ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set Ξ±} : (s βˆͺ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set Ξ±} (h : s ∩ t β‰  βˆ…) : t β‰  βˆ… := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set Ξ±} (h : s ∩ t β‰  βˆ…) : s β‰  βˆ… := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set Ξ±) : s ∩ (t βˆͺ u) = (s ∩ t) βˆͺ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set Ξ±) : (s βˆͺ t) ∩ u = (s ∩ u) βˆͺ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set Ξ±) : s βˆͺ (t ∩ u) = (s βˆͺ t) ∩ (s βˆͺ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set Ξ±) : (s ∩ t) βˆͺ u = (s βˆͺ u) ∩ (t βˆͺ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : Ξ±) (s : set Ξ±) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : Ξ±) (s : set Ξ±) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : Ξ±) (s : set Ξ±) : s βŠ† insert x s := assume y ys, or.inr ys theorem mem_insert (x : Ξ±) (s : set Ξ±) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : Ξ±} {s : set Ξ±} (y : Ξ±) : x ∈ s β†’ x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : Ξ±} {s : set Ξ±} : x ∈ insert a s β†’ x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : Ξ±} {s : set Ξ±} (xin : x ∈ insert a s) : x β‰  a β†’ x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : Ξ±} {s : set Ξ±} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : Ξ±} {s : set Ξ±} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s βŠ† t ↔ (a ∈ t ∧ s βŠ† t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s βŠ† t) : insert a s βŠ† insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set Ξ±} {a : Ξ±} (h : a βˆ‰ s) : s βŠ‚ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : Ξ±) (s : set Ξ±) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s βˆͺ t = insert a (s βˆͺ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s βˆͺ insert a t = insert a (s βˆͺ t) := ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : Ξ±) (s : set Ξ±) : insert a s β‰  βˆ… := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : Ξ± β†’ Prop} {a : Ξ±} {s : set Ξ±} (h : βˆ€ x, x ∈ insert a s β†’ P x) : βˆ€ x, x ∈ s β†’ P x := by finish theorem forall_insert_of_forall {P : Ξ± β†’ Prop} {a : Ξ±} {s : set Ξ±} (h : βˆ€ x, x ∈ s β†’ P x) (ha : P a) : βˆ€ x, x ∈ insert a s β†’ P x := by finish theorem ball_insert_iff {P : Ξ± β†’ Prop} {a : Ξ±} {s : set Ξ±} : (βˆ€ x ∈ insert a s, P x) ↔ P a ∧ (βˆ€x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : Ξ±) : ({a} : set Ξ±) = insert a βˆ… := rfl @[simp] theorem mem_singleton_iff {a b : Ξ±} : a ∈ ({b} : set Ξ±) ↔ a = b := by finish [singleton_def] lemma set_of_eq_eq_singleton {a : Ξ±} : {n | n = a} = {a} := set.ext $ Ξ» n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : Ξ±) : a ∈ ({a} : set Ξ±) := by finish theorem eq_of_mem_singleton {x y : Ξ±} (h : x ∈ ({y} : set Ξ±)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : Ξ±} : {x} = ({y} : set Ξ±) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : Ξ±} (H : x = y) : x ∈ ({y} : set Ξ±) := by finish theorem insert_eq (x : Ξ±) (s : set Ξ±) : insert x s = ({x} : set Ξ±) βˆͺ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : Ξ±) : ({a, a} : set Ξ±) = {a} := by finish @[simp] theorem singleton_ne_empty (a : Ξ±) : ({a} : set Ξ±) β‰  βˆ… := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : Ξ±} {s : set Ξ±} : {a} βŠ† s ↔ a ∈ s := ⟨λh, h (by simp), Ξ»h b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : Ξ±} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s βˆͺ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} βˆͺ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = βˆ… ↔ a βˆ‰ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = βˆ… ↔ a βˆ‰ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set Ξ±} : s βˆ‰ ({βˆ…} : set (set Ξ±)) ↔ nonempty s := by simp [coe_nonempty_iff_ne_empty] instance unique_singleton {Ξ± : Type*} (a : Ξ±) : unique β†₯({a} : set Ξ±) := { default := ⟨a, mem_singleton a⟩, uniq := begin intros x, apply subtype.coe_ext.2, apply eq_of_mem_singleton (subtype.mem x), end} /- separation -/ theorem mem_sep {s : set Ξ±} {p : Ξ± β†’ Prop} {x : Ξ±} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set Ξ±} {p : Ξ± β†’ Prop} {x : Ξ±} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set Ξ±} {p : Ξ± β†’ Prop} {x : Ξ±} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set Ξ±} (ssubt : s βŠ† t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set Ξ±) (p : Ξ± β†’ Prop) : {x ∈ s | p x} βŠ† s := assume x, and.left theorem forall_not_of_sep_empty {s : set Ξ±} {p : Ξ± β†’ Prop} (h : {x ∈ s | p x} = βˆ…) : βˆ€ x ∈ s, Β¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {Ξ±} {p : Ξ± β†’ Prop} : {a ∈ (univ : set Ξ±) | p a} = {a | p a} := set.ext $ by simp /- complement -/ theorem mem_compl {s : set Ξ±} {x : Ξ±} (h : x βˆ‰ s) : x ∈ -s := h lemma compl_set_of {Ξ±} (p : Ξ± β†’ Prop) : - {a | p a} = { a | Β¬ p a } := rfl theorem not_mem_of_mem_compl {s : set Ξ±} {x : Ξ±} (h : x ∈ -s) : x βˆ‰ s := h @[simp] theorem mem_compl_eq (s : set Ξ±) (x : Ξ±) : x ∈ -s = (x βˆ‰ s) := rfl theorem mem_compl_iff (s : set Ξ±) (x : Ξ±) : x ∈ -s ↔ x βˆ‰ s := iff.rfl @[simp] theorem inter_compl_self (s : set Ξ±) : s ∩ -s = βˆ… := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set Ξ±) : -s ∩ s = βˆ… := by finish [ext_iff] @[simp] theorem compl_empty : -(βˆ… : set Ξ±) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set Ξ±) : -(s βˆͺ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set Ξ±) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set Ξ±) : -(s ∩ t) = -s βˆͺ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set Ξ±) = βˆ… := by finish [ext_iff] lemma compl_empty_iff {s : set Ξ±} : -s = βˆ… ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set Ξ±} : -s = univ ↔ s = βˆ… := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set Ξ±} : nonempty (-s : set Ξ±) ↔ s β‰  univ := by { symmetry, rw [coe_nonempty_iff_ne_empty], apply not_congr, split, intro h, rw [h, compl_univ], intro h, rw [←compl_compl s, h, compl_empty] } theorem union_eq_compl_compl_inter_compl (s t : set Ξ±) : s βˆͺ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set Ξ±) : s ∩ t = -(-s βˆͺ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set Ξ±) : s βˆͺ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set Ξ±) : -s βˆͺ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set Ξ±) := funext compl_compl theorem compl_subset_comm {s t : set Ξ±} : -s βŠ† t ↔ -t βŠ† s := by haveI := classical.prop_decidable; exact forall_congr (Ξ» a, not_imp_comm) lemma compl_subset_compl {s t : set Ξ±} : -s βŠ† -t ↔ t βŠ† s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set Ξ±} : -s βŠ† t ↔ s βˆͺ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ Ξ» a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set Ξ±} : s βŠ† -t ↔ t βŠ† -s := forall_congr $ Ξ» a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set Ξ±} : s βŠ† -t ↔ s ∩ t = βˆ… := iff.trans (forall_congr $ Ξ» a, and_imp.symm) subset_empty_iff theorem inter_subset (a b c : set Ξ±) : a ∩ b βŠ† c ↔ a βŠ† -b βˆͺ c := begin haveI := classical.prop_decidable, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /- set difference -/ theorem diff_eq (s t : set Ξ±) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set Ξ±} (x : Ξ±) : x ∈ s \ t ↔ x ∈ s ∧ x βˆ‰ t := iff.rfl theorem mem_diff_of_mem {s t : set Ξ±} {x : Ξ±} (h1 : x ∈ s) (h2 : x βˆ‰ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set Ξ±} {x : Ξ±} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set Ξ±} {x : Ξ±} (h : x ∈ s \ t) : x βˆ‰ t := h.right theorem union_diff_cancel {s t : set Ξ±} (h : s βŠ† t) : s βˆͺ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set Ξ±} (h : s ∩ t βŠ† βˆ…) : (s βˆͺ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set Ξ±} (h : s ∩ t βŠ† βˆ…) : (s βˆͺ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set Ξ±} : (s βˆͺ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set Ξ±} : (s βˆͺ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set Ξ±} : (s βˆͺ t) \ u = s \ u βˆͺ t \ u := inter_distrib_right _ _ _ theorem inter_union_distrib_left {s t u : set Ξ±} : s ∩ (t βˆͺ u) = (s ∩ t) βˆͺ (s ∩ u) := set.ext $ Ξ» _, and_or_distrib_left theorem inter_union_distrib_right {s t u : set Ξ±} : (s ∩ t) βˆͺ u = (s βˆͺ u) ∩ (t βˆͺ u) := set.ext $ Ξ» _, and_or_distrib_right theorem union_inter_distrib_left {s t u : set Ξ±} : s βˆͺ (t ∩ u) = (s βˆͺ t) ∩ (s βˆͺ u) := set.ext $ Ξ» _, or_and_distrib_left theorem union_inter_distrib_right {s t u : set Ξ±} : (s βˆͺ t) ∩ u = (s ∩ u) βˆͺ (t ∩ u) := set.ext $ Ξ» _, or_and_distrib_right theorem inter_diff_assoc (a b c : set Ξ±) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set Ξ±) : a ∩ (b \ a) = βˆ… := by finish [ext_iff] theorem inter_union_diff (s t : set Ξ±) : (s ∩ t) βˆͺ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set Ξ±) : s \ t βŠ† s := by finish [subset_def] theorem diff_subset_diff {s₁ sβ‚‚ t₁ tβ‚‚ : set Ξ±} : s₁ βŠ† sβ‚‚ β†’ tβ‚‚ βŠ† t₁ β†’ s₁ \ t₁ βŠ† sβ‚‚ \ tβ‚‚ := by finish [subset_def] theorem diff_subset_diff_left {s₁ sβ‚‚ t : set Ξ±} (h : s₁ βŠ† sβ‚‚) : s₁ \ t βŠ† sβ‚‚ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set Ξ±} (h : t βŠ† u) : s \ u βŠ† s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set Ξ±) : -s = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff {Ξ± : Type*} (s : set Ξ±) : (βˆ… \ s : set Ξ±) = βˆ… := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set Ξ±} : s \ t = βˆ… ↔ s βŠ† t := ⟨assume h x hx, classical.by_contradiction $ assume : x βˆ‰ t, show x ∈ (βˆ… : set Ξ±), from h β–Έ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set Ξ±} : s \ βˆ… = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set Ξ±} : s \ t \ u = s \ (t βˆͺ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set Ξ±} : s \ t βŠ† u ↔ s βŠ† t βˆͺ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_insert_diff (s t : set Ξ±) : s βŠ† (s \ t) βˆͺ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : Ξ±} {s t : set Ξ±} : s \ {x} βŠ† t ↔ s βŠ† insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_insert_diff_singleton (x : Ξ±) (s : set Ξ±) : s βŠ† insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set Ξ±} : s \ t βŠ† u ↔ s \ u βŠ† t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set Ξ±} : s βˆͺ (t \ s) = s βˆͺ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set Ξ±} : (s \ t) βˆͺ t = s βˆͺ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set Ξ±} : (b \ a) ∩ a = βˆ… := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set Ξ±} : s \ t = s ↔ t ∩ s βŠ† βˆ… := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : Ξ±} {s : set Ξ±} (h : a βˆ‰ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : Ξ±} {s : set Ξ±} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set Ξ±} : s \ s = βˆ… := ext $ by simp lemma mem_diff_singleton {s s' : set Ξ±} {t : set (set Ξ±)} : s ∈ t \ {s'} ↔ (s ∈ t ∧ s β‰  s') := by simp lemma mem_diff_singleton_empty {s : set Ξ±} {t : set (set Ξ±)} : s ∈ t \ {βˆ…} ↔ (s ∈ t ∧ nonempty s) := by simp [coe_nonempty_iff_ne_empty] /- powerset -/ theorem mem_powerset {x s : set Ξ±} (h : x βŠ† s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set Ξ±} (h : x ∈ powerset s) : x βŠ† s := h theorem mem_powerset_iff (x s : set Ξ±) : x ∈ powerset s ↔ x βŠ† s := iff.rfl /- inverse image -/ /-- The preimage of `s : set Ξ²` by `f : Ξ± β†’ Ξ²`, written `f ⁻¹' s`, is the set of `x : Ξ±` such that `f x ∈ s`. -/ def preimage {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ²) : set Ξ± := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ³} @[simp] theorem preimage_empty : f ⁻¹' βˆ… = βˆ… := rfl @[simp] theorem mem_preimage {s : set Ξ²} {a : Ξ±} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl theorem preimage_mono {s t : set Ξ²} (h : s βŠ† t) : f ⁻¹' s βŠ† f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem subset_preimage_univ {s : set Ξ±} : s βŠ† f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set Ξ²} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set Ξ²} : f ⁻¹' (s βˆͺ t) = f ⁻¹' s βˆͺ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set Ξ²} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : Ξ± β†’ Ξ²) (s t : set Ξ²) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : Ξ± β†’ Prop} {f : Ξ² β†’ Ξ±} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set Ξ±} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set Ξ³} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : Ξ± β†’ Prop} {s : set (subtype p)} {t : set Ξ±} : s = subtype.val ⁻¹' t ↔ (βˆ€x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ fβ‚‚ : Ξ± β†’ Ξ²` are equal on `s` if `f₁ x = fβ‚‚ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : Ξ± β†’ Ξ²) (a : set Ξ±) : Prop := βˆ€ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : Ξ± β†’ Ξ²} {s : set Ξ±} {y : Ξ²} : y ∈ f '' s ↔ βˆƒ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : Ξ± β†’ Ξ²) (s : set Ξ±) (y: Ξ²) : y ∈ f '' s = βˆƒ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : Ξ± β†’ Ξ²) (s : set Ξ±) (y : Ξ²) : y ∈ f '' s ↔ βˆƒ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : Ξ± β†’ Ξ²) {x : Ξ±} {a : set Ξ±} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : Ξ± β†’ Ξ²} {a : Ξ±} {s : set Ξ±} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) β–Έ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : Ξ± β†’ Ξ²} {s : set Ξ±} {p : Ξ² β†’ Prop} (h : βˆ€ x ∈ s, p (f x)) : βˆ€ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : Ξ± β†’ Ξ²} {s : set Ξ±} {p : Ξ² β†’ Prop} : (βˆ€ y ∈ f '' s, p y) ↔ (βˆ€ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq β–Έ h a ha) theorem mono_image {f : Ξ± β†’ Ξ²} {s t : set Ξ±} (h : s βŠ† t) : f '' s βŠ† f '' t := assume x ⟨y, hy, y_eq⟩, y_eq β–Έ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : Ξ± β†’ Ξ²} {s : set Ξ±} {C : Ξ² β†’ Prop} (h : βˆ€ (x : Ξ±), x ∈ s β†’ C (f x)) : βˆ€{y : Ξ²}, y ∈ f '' s β†’ C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : Ξ± β†’ Ξ²} {s : set Ξ±} {C : Ξ² β†’ Prop} {y : Ξ²} (h_y : y ∈ f '' s) (h : βˆ€ (x : Ξ±), x ∈ s β†’ C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : Ξ± β†’ Ξ²} {s : set Ξ±} (h : βˆ€a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /- A common special case of `image_congr` -/ lemma image_congr' {f g : Ξ± β†’ Ξ²} {s : set Ξ±} (h : βˆ€ (x : Ξ±), f x = g x) : f '' s = g '' s := image_congr (Ξ»x _, h x) theorem image_eq_image_of_eq_on {f₁ fβ‚‚ : Ξ± β†’ Ξ²} {s : set Ξ±} (heq : eq_on f₁ fβ‚‚ s) : f₁ '' s = fβ‚‚ '' s := image_congr heq theorem image_comp (f : Ξ² β†’ Ξ³) (g : Ξ± β†’ Ξ²) (a : set Ξ±) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : Ξ² β†’ Ξ³) (f : Ξ± β†’ Ξ²) (s : set Ξ±) : g '' (f '' s) = (Ξ» x, g (f x)) '' s := (image_comp g f s).symm theorem image_subset {a b : set Ξ±} (f : Ξ± β†’ Ξ²) (h : a βŠ† b) : f '' a βŠ† f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : Ξ± β†’ Ξ²) (s t : set Ξ±) : f '' (s βˆͺ t) = f '' s βˆͺ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : Ξ± β†’ Ξ²) : f '' βˆ… = βˆ… := ext $ by simp theorem image_inter_on {f : Ξ± β†’ Ξ²} {s t : set Ξ±} (h : βˆ€x∈t, βˆ€y∈s, f x = f y β†’ x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, hβ‚βŸ©, ⟨aβ‚‚, haβ‚‚, hβ‚‚βŸ©βŸ©, have aβ‚‚ = a₁, from h _ haβ‚‚ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this β–Έ haβ‚‚βŸ©, hβ‚βŸ©) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : Ξ± β†’ Ξ²} {s t : set Ξ±} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ΞΉ : Type*} {f : ΞΉ β†’ Ξ²} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : Ξ± β†’ Ξ²} {a : Ξ±} : f '' {a} = {f a} := ext $ Ξ» x, by simp [image]; rw eq_comm @[simp] lemma image_eq_empty {Ξ± Ξ²} {f : Ξ± β†’ Ξ²} {s : set Ξ±} : f '' s = βˆ… ↔ s = βˆ… := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, Ξ» H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_ne_empty {Ξ± : Type*} {s : set Ξ±} {a : Ξ±} : s ∩ {a} β‰  βˆ… ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set Ξ±) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set Ξ±) (S : set (set Ξ±)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : βˆ€ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set Ξ±) : id '' s = s := ext $ by simp /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set Ξ±) : (Ξ»x, x) '' s = s := image_id s theorem compl_compl_image (S : set (set Ξ±)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : Ξ± β†’ Ξ²} {a : Ξ±} {s : set Ξ±} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (I : left_inverse g f) (s : set Ξ±) : f '' s βŠ† g ⁻¹' s := Ξ» b ⟨a, h, e⟩, e β–Έ ((I a).symm β–Έ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (I : left_inverse g f) (s : set Ξ²) : f ⁻¹' s βŠ† g '' s := Ξ» b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (h₁ : left_inverse g f) (hβ‚‚ : right_inverse g f) : image f = preimage g := funext $ Ξ» s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse hβ‚‚ s) theorem mem_image_iff_of_inverse {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} {b : Ξ²} {s : set Ξ±} (h₁ : left_inverse g f) (hβ‚‚ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ hβ‚‚; refl theorem image_compl_subset {f : Ξ± β†’ Ξ²} {s : set Ξ±} (H : injective f) : f '' -s βŠ† -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : Ξ± β†’ Ξ²} {s : set Ξ±} (H : surjective f) : -(f '' s) βŠ† f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : Ξ± β†’ Ξ²} {s : set Ξ±} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) lemma nonempty_image (f : Ξ± β†’ Ξ²) {s : set Ξ±} : nonempty s β†’ nonempty (f '' s) | ⟨⟨x, hx⟩⟩ := ⟨⟨f x, mem_image_of_mem f hx⟩⟩ /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set Ξ±} {t : set Ξ²} {f : Ξ± β†’ Ξ²} : f '' s βŠ† t ↔ s βŠ† f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : Ξ± β†’ Ξ²) (s : set Ξ²) : f '' (f ⁻¹' s) βŠ† s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : Ξ± β†’ Ξ²) (s : set Ξ±) : s βŠ† f ⁻¹' (f '' s) := Ξ» x, mem_image_of_mem f theorem preimage_image_eq {f : Ξ± β†’ Ξ²} (s : set Ξ±) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (Ξ» x ⟨y, hy, e⟩, h e β–Έ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : Ξ± β†’ Ξ²} {s : set Ξ²} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (Ξ» x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm β–Έ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : Ξ² β†’ Ξ±} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq Ξ² Ξ± f s hf, ← @image_preimage_eq Ξ² Ξ± f t hf, eq]) (assume eq, eq β–Έ rfl) lemma surjective_preimage {f : Ξ² β†’ Ξ±} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl Ξ±) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {Ξ± : Type u} {p : set Ξ± β†’ Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set Ξ±) (t : set Ξ²) (f : Ξ± β†’ Ξ²) : s ∩ f ⁻¹' t βŠ† f ⁻¹' (f '' s ∩ t) := Ξ» x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set Ξ±) (t : set Ξ²) (f : Ξ± β†’ Ξ²) : s βˆͺ f ⁻¹' t βŠ† f ⁻¹' (f '' s βˆͺ t) := Ξ» x h, or.elim h (Ξ» l, or.inl $ mem_image_of_mem _ l) (Ξ» r, or.inr r) theorem subset_image_union (f : Ξ± β†’ Ξ²) (s : set Ξ±) (t : set Ξ²) : f '' (s βˆͺ f ⁻¹' t) βŠ† f '' s βˆͺ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set Ξ±} {B : set Ξ²} {f : Ξ± β†’ Ξ²} : f⁻¹' B βŠ† A ↔ (βˆ€ a : Ξ±, f a ∈ B β†’ a ∈ A) := iff.rfl lemma image_eq_image {f : Ξ± β†’ Ξ²} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq β–Έ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : Ξ± β†’ Ξ²} (hf : injective f) : f '' s βŠ† f '' t ↔ s βŠ† t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : Ξ± β†’ Ξ²} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid Ξ±] (g : quotient s β†’ Ξ²) {h : Ξ± β†’ Ξ²} (Hh : h = g ∘ quotient.mk) (r : set (Ξ² Γ— Ξ²)) : {x : quotient s Γ— quotient s | (g x.1, g x.2) ∈ r} = (Ξ» a : Ξ± Γ— Ξ±, (⟦a.1⟧, ⟦a.2⟧)) '' ((Ξ» a : Ξ± Γ— Ξ±, (h a.1, h a.2)) ⁻¹' r) := Hh.symm β–Έ set.ext (Ξ» ⟨a₁, aβ‚‚βŸ©, ⟨quotient.induction_onβ‚‚ a₁ aβ‚‚ (Ξ» a₁ aβ‚‚ h, ⟨(a₁, aβ‚‚), h, rfl⟩), Ξ» ⟨⟨b₁, bβ‚‚βŸ©, h₁, hβ‚‚βŸ©, show (g a₁, g aβ‚‚) ∈ r, from have h₃ : ⟦bβ‚βŸ§ = a₁ ∧ ⟦bβ‚‚βŸ§ = aβ‚‚ := prod.ext_iff.1 hβ‚‚, h₃.1 β–Έ h₃.2 β–Έ hβ‚βŸ©) def image_factorization (f : Ξ± β†’ Ξ²) (s : set Ξ±) : s β†’ f '' s := Ξ» p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : Ξ± β†’ Ξ²} {s : set Ξ±} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ Ξ» p, rfl lemma surjective_onto_image {f : Ξ± β†’ Ξ²} {s : set Ξ±} : surjective (image_factorization f s) := Ξ» ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ΞΉ β†’ Ξ±} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ΞΉ β†’ Ξ±) : set Ξ± := {x | βˆƒy, f y = x} @[simp] theorem mem_range {x : Ξ±} : x ∈ range f ↔ βˆƒ y, f y = x := iff.rfl theorem mem_range_self (i : ΞΉ) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : Ξ± β†’ Prop} : (βˆ€ a ∈ range f, p a) ↔ (βˆ€ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi β–Έ h i⟩ theorem exists_range_iff {p : Ξ± β†’ Prop} : (βˆƒ a ∈ range f, p a) ↔ (βˆƒ i, p (f i)) := ⟨assume ⟨a, ⟨i, eq⟩, h⟩, ⟨i, eq.symm β–Έ h⟩, assume ⟨i, h⟩, ⟨f i, mem_range_self _, h⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id Ξ±) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ΞΉ : Type*} {f : ΞΉ β†’ Ξ²} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ΞΉ : Type*} (f : ΞΉ β†’ Ξ²) (s : set ΞΉ) : f '' s βŠ† range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : Ξ± β†’ Ξ²} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ΞΉ : Type*} {f : ΞΉ β†’ Ξ²} {s : set Ξ²} : range f βŠ† s ↔ βˆ€ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) : range (g ∘ f) βŠ† range g := by rw range_comp; apply image_subset_range lemma nonempty_of_nonempty_range {Ξ± : Type*} {Ξ² : Type*} {f : Ξ± β†’ Ξ²} (H : Β¬range f = βˆ…) : nonempty Ξ± := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end @[simp] lemma range_eq_empty {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β†’ Ξ²} : range f = βˆ… ↔ Β¬ nonempty Ξ± := by rw ← set.image_univ; simp [-set.image_univ] theorem image_preimage_eq_inter_range {f : Ξ± β†’ Ξ²} {t : set Ξ²} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq β–Έ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq β–Έ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : Ξ± β†’ Ξ²} {s : set Ξ²} (hs : s βŠ† range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set Ξ±} {f : Ξ² β†’ Ξ±} (hs : s βŠ† range f) : f ⁻¹' s βŠ† f ⁻¹' t ↔ s βŠ† t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set Ξ±} {f : Ξ² β†’ Ξ±} (hs : s βŠ† range f) (ht : t βŠ† range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end theorem preimage_inter_range {f : Ξ± β†’ Ξ²} {s : set Ξ²} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ Ξ» x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : Ξ± β†’ Ξ²} {s : set Ξ²} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid Ξ±] : range (Ξ»x : Ξ±, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : Ξ²} : range (Ξ»x:Ξ±, c) βŠ† {c} := range_subset_iff.2 $ Ξ» x, or.inl rfl @[simp] lemma range_const [h : nonempty Ξ±] {c : Ξ²} : range (Ξ»x:Ξ±, c) = {c} := begin refine subset.antisymm range_const_subset (Ξ»y hy, _), rw set.mem_singleton_iff.1 hy, rcases exists_mem_of_nonempty Ξ± with ⟨x, _⟩, exact mem_range_self x end def range_factorization (f : ΞΉ β†’ Ξ²) : ΞΉ β†’ range f := Ξ» i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ΞΉ β†’ Ξ²} : subtype.val ∘ range_factorization f = f := funext $ Ξ» i, rfl lemma surjective_onto_range : surjective (range_factorization f) := Ξ» ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : Ξ± β†’ Ξ²) (s : set Ξ±) : f '' s = range (Ξ»(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {Ξ± Ξ² Ξ³ : Type*} (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) : range (sum.elim f g) = range f βˆͺ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : Ξ± β†’ Ξ²} : range (if p then f else g) βŠ† range f βˆͺ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : Ξ± β†’ Prop} [decidable_pred p] {f g : Ξ± β†’ Ξ²} : range (Ξ» x, if p x then f x else g x) βŠ† range f βˆͺ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set Ξ±) (r : Ξ± β†’ Ξ± β†’ Prop) := βˆ€ x ∈ s, βˆ€ y ∈ s, x β‰  y β†’ r x y theorem pairwise_on.mono {s t : set Ξ±} {r} (h : t βŠ† s) (hp : pairwise_on s r) : pairwise_on t r := Ξ» x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set Ξ±} {r r' : Ξ± β†’ Ξ± β†’ Prop} (H : βˆ€ a b, r a b β†’ r' a b) (hp : pairwise_on s r) : pairwise_on s r' := Ξ» x xs y ys h, H _ _ (hp x xs y ys h) end set open set /- image and preimage on subtypes -/ namespace subtype variable {Ξ± : Type*} lemma val_image {p : Ξ± β†’ Prop} {s : set (subtype p)} : subtype.val '' s = {x | βˆƒh : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq β–Έ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma val_range {p : Ξ± β†’ Prop} : set.range (@subtype.val _ p) = {x | p x} := by rw ← set.image_univ; simp [-set.image_univ, val_image] @[simp] lemma range_val (s : set Ξ±) : range (subtype.val : s β†’ Ξ±) = s := val_range theorem val_image_subset (s : set Ξ±) (t : set (subtype s)) : t.image val βŠ† s := Ξ» x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem val_image_univ (s : set Ξ±) : @val _ s '' set.univ = s := set.eq_of_subset_of_subset (val_image_subset _ _) (Ξ» x xs, ⟨⟨x, xs⟩, ⟨set.mem_univ _, rfl⟩⟩) theorem image_preimage_val (s t : set Ξ±) : (@subtype.val _ s) '' ((@subtype.val _ s) ⁻¹' t) = t ∩ s := begin ext x, simp, split, { rintros ⟨y, ys, yt, yx⟩, rw ←yx, exact ⟨yt, ys⟩ }, rintros ⟨xt, xs⟩, exact ⟨x, xs, xt, rfl⟩ end theorem preimage_val_eq_preimage_val_iff (s t u : set Ξ±) : ((@subtype.val _ s) ⁻¹' t = (@subtype.val _ s) ⁻¹' u) ↔ (t ∩ s = u ∩ s) := begin rw [←image_preimage_val, ←image_preimage_val], split, { intro h, rw h }, intro h, exact set.injective_image (val_injective) h end lemma exists_set_subtype {t : set Ξ±} (p : set Ξ± β†’ Prop) : (βˆƒ(s : set t), p (subtype.val '' s)) ↔ βˆƒ(s : set Ξ±), s βŠ† t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨subtype.val '' s, _, hs⟩, convert image_subset_range _ _, rw [range_val] }, rintro ⟨s, hs₁, hsβ‚‚βŸ©, refine ⟨subtype.val ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hsβ‚‚, rw [range_val], exact hs₁ end end subtype namespace set section range variable {Ξ± : Type*} @[simp] lemma subtype.val_range {p : Ξ± β†’ Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype.val_image] @[simp] lemma range_coe_subtype (s : set Ξ±) : range (coe : s β†’ Ξ±) = s := subtype.val_range end range section prod variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} variables {s s₁ sβ‚‚ : set Ξ±} {t t₁ tβ‚‚ : set Ξ²} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set Ξ±) (t : set Ξ²) : set (Ξ± Γ— Ξ²) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set Ξ±) (t : set Ξ²) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : Ξ± Γ— Ξ²} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : Ξ± Γ— Ξ²} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : Ξ±} {b : Ξ²} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ lemma prod_subset_iff {P : set (Ξ± Γ— Ξ²)} : (set.prod s t βŠ† P) ↔ βˆ€ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), Ξ» h _ pin, by { cases mem_prod.1 pin with hs ht, simpa using h _ hs _ ht }⟩ @[simp] theorem prod_empty {s : set Ξ±} : set.prod s βˆ… = (βˆ… : set (Ξ± Γ— Ξ²)) := ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set Ξ²} : set.prod βˆ… t = (βˆ… : set (Ξ± Γ— Ξ²)) := ext $ by simp [set.prod] theorem insert_prod {a : Ξ±} {s : set Ξ±} {t : set Ξ²} : set.prod (insert a s) t = (prod.mk a '' t) βˆͺ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : Ξ²} {s : set Ξ±} {t : set Ξ²} : set.prod s (insert b t) = ((Ξ»a, (a, b)) '' s) βˆͺ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : Ξ³ β†’ Ξ±} {g : Ξ΄ β†’ Ξ²} : set.prod (preimage f s) (preimage g t) = preimage (Ξ»p, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ sβ‚‚ : set Ξ±} {t₁ tβ‚‚ : set Ξ²} (hs : s₁ βŠ† sβ‚‚) (ht : t₁ βŠ† tβ‚‚) : set.prod s₁ t₁ βŠ† set.prod sβ‚‚ tβ‚‚ := assume x ⟨h₁, hβ‚‚βŸ©, ⟨hs h₁, ht hβ‚‚βŸ© theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod sβ‚‚ tβ‚‚ = set.prod (s₁ ∩ sβ‚‚) (t₁ ∩ tβ‚‚) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hbβ‚βŸ©, ⟨haβ‚‚, hbβ‚‚βŸ©βŸ©, ⟨⟨ha₁, haβ‚‚βŸ©, ⟨hb₁, hbβ‚‚βŸ©βŸ©) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (Ξ»p:Ξ²Γ—Ξ±, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap Ξ± Ξ²) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : Ξ± β†’ Ξ³} {mβ‚‚ : Ξ² β†’ Ξ΄} : set.prod (image m₁ s) (image mβ‚‚ t) = image (Ξ»p:Ξ±Γ—Ξ², (m₁ p.1, mβ‚‚ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {Ξ± Ξ² Ξ³ Ξ΄} {m₁ : Ξ± β†’ Ξ³} {mβ‚‚ : Ξ² β†’ Ξ΄} : set.prod (range m₁) (range mβ‚‚) = range (Ξ»p:Ξ±Γ—Ξ², (m₁ p.1, mβ‚‚ p.2)) := ext $ by simp [range] theorem prod_range_univ_eq {Ξ± Ξ² Ξ³} {m₁ : Ξ± β†’ Ξ³} : set.prod (range m₁) (univ : set Ξ²) = range (Ξ»p:Ξ±Γ—Ξ², (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {Ξ± Ξ² Ξ΄} {mβ‚‚ : Ξ² β†’ Ξ΄} : set.prod (univ : set Ξ±) (range mβ‚‚) = range (Ξ»p:Ξ±Γ—Ξ², (p.1, mβ‚‚ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : Ξ±} {b : Ξ²} : set.prod {a} {b} = ({(a, b)} : set (Ξ±Γ—Ξ²)) := ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set Ξ±} {t : set Ξ²} : set.prod s t β‰  βˆ… ↔ (s β‰  βˆ… ∧ t β‰  βˆ…) := by simp [not_eq_empty_iff_exists] theorem prod_eq_empty_iff {s : set Ξ±} {t : set Ξ²} : set.prod s t = βˆ… ↔ (s = βˆ… ∨ t = βˆ…) := suffices (Β¬ set.prod s t β‰  βˆ…) ↔ (Β¬ s β‰  βˆ… ∨ Β¬ t β‰  βˆ…), by simpa only [(β‰ ), classical.not_not], by classical; rw [prod_neq_empty_iff, not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : Ξ±} {b : Ξ²} {s : set Ξ±} {t : set Ξ²} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ Ξ±) (@univ Ξ²) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set Ξ³} {f : Ξ± Γ— Ξ² β†’ Ξ³} : set.prod s t βŠ† f ⁻¹' W ↔ βˆ€ a b, a ∈ s β†’ b ∈ t β†’ f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set Ξ±) (t : set Ξ²) : prod.fst '' (set.prod s t) βŠ† s := Ξ» _ h, let ⟨_, ⟨hβ‚‚, _⟩, hβ‚βŸ© := (set.mem_image _ _ _).1 h in h₁ β–Έ hβ‚‚ lemma prod_subset_preimage_fst (s : set Ξ±) (t : set Ξ²) : set.prod s t βŠ† prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set Ξ²) {t : set Ξ±} (ht : t β‰  βˆ…) : prod.fst '' (set.prod s t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ Ξ» y y_in, let (⟨x, x_in⟩ : βˆƒ (x : Ξ±), x ∈ t) := set.exists_mem_of_ne_empty ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set Ξ±) (t : set Ξ²) : prod.snd '' (set.prod s t) βŠ† t := Ξ» _ h, let ⟨_, ⟨_, hβ‚‚βŸ©, hβ‚βŸ© := (set.mem_image _ _ _).1 h in h₁ β–Έ hβ‚‚ lemma prod_subset_preimage_snd (s : set Ξ±) (t : set Ξ²) : set.prod s t βŠ† prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set Ξ±} (hs : s β‰  βˆ…) (t : set Ξ²) : prod.snd '' (set.prod s t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ Ξ» y y_in, let (⟨x, x_in⟩ : βˆƒ (x : Ξ±), x ∈ s) := set.exists_mem_of_ne_empty hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (set.prod s t βŠ† set.prod s₁ t₁) ↔ (s βŠ† s₁ ∧ t βŠ† t₁) ∨ (s = βˆ…) ∨ (t = βˆ…) := begin classical, by_cases h : set.prod s t = βˆ…, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s β‰  βˆ… ∧ t β‰  βˆ…, by rwa [← ne.def, prod_neq_empty_iff] at h, split, { assume H : set.prod s t βŠ† set.prod s₁ t₁, have h' : s₁ β‰  βˆ… ∧ t₁ β‰  βˆ… := prod_neq_empty_iff.1 (subset_ne_empty H h), refine or.inl ⟨_, _⟩, show s βŠ† s₁, { have := image_subset (prod.fst : Ξ± Γ— Ξ² β†’ Ξ±) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t βŠ† t₁, { have := image_subset (prod.snd : Ξ± Γ— Ξ² β†’ Ξ²) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp [st] at H, exact prod_mono H.1 H.2 } } end end prod section pi variables {Ξ± : Type*} {Ο€ : Ξ± β†’ Type*} def pi (i : set Ξ±) (s : Ξ a, set (Ο€ a)) : set (Ξ a, Ο€ a) := { f | βˆ€a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Ξ a, set (Ο€ a)) : pi βˆ… s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : Ξ±) (i : set Ξ±) (s : Ξ a, set (Ο€ a)) : pi (insert a i) s = ((Ξ»f, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : Ξ±) (s : Ξ a, set (Ο€ a)) : pi {a} s = ((Ξ»f:(Ξ a, Ο€ a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : Ξ± β†’ Prop} [h : decidable_pred p] (i : set Ξ±) (s t : Ξ a, set (Ο€ a)) : pi i (Ξ»a, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | Β¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi section inclusion variable {Ξ± : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s βŠ† t` -/ def inclusion {s t : set Ξ±} (h : s βŠ† t) : s β†’ t := Ξ» x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set Ξ±} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set Ξ±} (hst : s βŠ† t) (htu : t βŠ† u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl lemma inclusion_injective {s t : set Ξ±} (h : s βŠ† t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext.2 ∘ subtype.ext.1 end inclusion end set
ea4e20b83eca143d247e531a51f8fbf7d5afa7de
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Compiler/ConstFolding.lean
350663d9a0e62a9acc8464da22b9b17611f2775b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
7,586
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.Expr import Lean.Compiler.Util /-! Constant folding for primitives that have special runtime support. -/ namespace Lean.Compiler abbrev BinFoldFn := Bool β†’ Expr β†’ Expr β†’ Option Expr abbrev UnFoldFn := Bool β†’ Expr β†’ Option Expr def mkUIntTypeName (nbytes : Nat) : Name := Name.mkSimple ("UInt" ++ toString nbytes) structure NumScalarTypeInfo where nbits : Nat id : Name := mkUIntTypeName nbits ofNatFn : Name := Name.mkStr id "ofNat" toNatFn : Name := Name.mkStr id "toNat" size : Nat := 2^nbits def numScalarTypes : List NumScalarTypeInfo := [{nbits := 8}, {nbits := 16}, {nbits := 32}, {nbits := 64}, {id := ``USize, nbits := System.Platform.numBits}] def isOfNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.ofNatFn == fn) def isToNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.toNatFn == fn) def getInfoFromFn (fn : Name) : List NumScalarTypeInfo β†’ Option NumScalarTypeInfo | [] => none | info::infos => if info.ofNatFn == fn then some info else getInfoFromFn fn infos def getInfoFromVal : Expr β†’ Option NumScalarTypeInfo | Expr.app (Expr.const fn _) _ => getInfoFromFn fn numScalarTypes | _ => none @[export lean_get_num_lit] def getNumLit : Expr β†’ Option Nat | Expr.lit (Literal.natVal n) => some n | Expr.app (Expr.const fn _) a => if isOfNat fn then getNumLit a else none | _ => none def mkUIntLit (info : NumScalarTypeInfo) (n : Nat) : Expr := mkApp (mkConst info.ofNatFn) (mkRawNatLit (n%info.size)) def mkUInt32Lit (n : Nat) : Expr := mkUIntLit {nbits := 32} n def foldBinUInt (fn : NumScalarTypeInfo β†’ Bool β†’ Nat β†’ Nat β†’ Nat) (beforeErasure : Bool) (a₁ aβ‚‚ : Expr) : Option Expr := do let n₁ ← getNumLit a₁ let nβ‚‚ ← getNumLit aβ‚‚ let info ← getInfoFromVal a₁ return mkUIntLit info (fn info beforeErasure n₁ nβ‚‚) def foldUIntAdd := foldBinUInt fun _ _ => Add.add def foldUIntMul := foldBinUInt fun _ _ => Mul.mul def foldUIntDiv := foldBinUInt fun _ _ => Div.div def foldUIntMod := foldBinUInt fun _ _ => Mod.mod def foldUIntSub := foldBinUInt fun info _ a b => (a + (info.size - b)) def preUIntBinFoldFns : List (Name Γ— BinFoldFn) := [(`add, foldUIntAdd), (`mul, foldUIntMul), (`div, foldUIntDiv), (`mod, foldUIntMod), (`sub, foldUIntSub)] def uintBinFoldFns : List (Name Γ— BinFoldFn) := numScalarTypes.foldl (fun r info => r ++ (preUIntBinFoldFns.map (fun ⟨suffix, fn⟩ => (info.id ++ suffix, fn)))) [] def foldNatBinOp (fn : Nat β†’ Nat β†’ Nat) (a₁ aβ‚‚ : Expr) : Option Expr := do let n₁ ← getNumLit a₁ let nβ‚‚ ← getNumLit aβ‚‚ return mkRawNatLit (fn n₁ nβ‚‚) def foldNatAdd (_ : Bool) := foldNatBinOp Add.add def foldNatMul (_ : Bool) := foldNatBinOp Mul.mul def foldNatDiv (_ : Bool) := foldNatBinOp Div.div def foldNatMod (_ : Bool) := foldNatBinOp Mod.mod -- TODO: add option for controlling the limit def natPowThreshold := 256 def foldNatPow (_ : Bool) (a₁ aβ‚‚ : Expr) : Option Expr := do let n₁ ← getNumLit a₁ let nβ‚‚ ← getNumLit aβ‚‚ if nβ‚‚ < natPowThreshold then return mkRawNatLit (n₁ ^ nβ‚‚) else failure def mkNatEq (a b : Expr) : Expr := mkAppN (mkConst ``Eq [levelOne]) #[(mkConst `Nat), a, b] def mkNatLt (a b : Expr) : Expr := mkAppN (mkConst ``LT.lt [levelZero]) #[mkConst ``Nat, mkConst ``Nat.lt, a, b] def mkNatLe (a b : Expr) : Expr := mkAppN (mkConst ``LE.le [levelZero]) #[mkConst ``Nat, mkConst ``Nat.le, a, b] def toDecidableExpr (beforeErasure : Bool) (pred : Expr) (r : Bool) : Expr := match beforeErasure, r with | false, true => mkConst ``Bool.true | false, false => mkConst ``Bool.false | true, true => mkDecIsTrue pred (mkLcProof pred) | true, false => mkDecIsFalse pred (mkLcProof pred) def foldNatBinPred (mkPred : Expr β†’ Expr β†’ Expr) (fn : Nat β†’ Nat β†’ Bool) (beforeErasure : Bool) (a₁ aβ‚‚ : Expr) : Option Expr := do let n₁ ← getNumLit a₁ let nβ‚‚ ← getNumLit aβ‚‚ return toDecidableExpr beforeErasure (mkPred a₁ aβ‚‚) (fn n₁ nβ‚‚) def foldNatDecEq := foldNatBinPred mkNatEq (fun a b => a = b) def foldNatDecLt := foldNatBinPred mkNatLt (fun a b => a < b) def foldNatDecLe := foldNatBinPred mkNatLe (fun a b => a ≀ b) def foldNatBinBoolPred (fn : Nat β†’ Nat β†’ Bool) (a₁ aβ‚‚ : Expr) : Option Expr := do let n₁ ← getNumLit a₁ let nβ‚‚ ← getNumLit aβ‚‚ if fn n₁ nβ‚‚ then return mkConst ``Bool.true else return mkConst ``Bool.false def foldNatBeq := fun _ : Bool => foldNatBinBoolPred (fun a b => a == b) def foldNatBle := fun _ : Bool => foldNatBinBoolPred (fun a b => a < b) def foldNatBlt := fun _ : Bool => foldNatBinBoolPred (fun a b => a ≀ b) def natFoldFns : List (Name Γ— BinFoldFn) := [(``Nat.add, foldNatAdd), (``Nat.mul, foldNatMul), (``Nat.div, foldNatDiv), (``Nat.mod, foldNatMod), (``Nat.pow, foldNatPow), (``Nat.decEq, foldNatDecEq), (``Nat.decLt, foldNatDecLt), (``Nat.decLe, foldNatDecLe), (``Nat.beq, foldNatBeq), (``Nat.blt, foldNatBlt), (``Nat.ble, foldNatBle) ] def getBoolLit : Expr β†’ Option Bool | Expr.const ``Bool.true _ => some true | Expr.const ``Bool.false _ => some false | _ => none def foldStrictAnd (_ : Bool) (a₁ aβ‚‚ : Expr) : Option Expr := let v₁ := getBoolLit a₁ let vβ‚‚ := getBoolLit aβ‚‚ match v₁, vβ‚‚ with | some true, _ => aβ‚‚ | some false, _ => a₁ | _, some true => a₁ | _, some false => aβ‚‚ | _, _ => none def foldStrictOr (_ : Bool) (a₁ aβ‚‚ : Expr) : Option Expr := let v₁ := getBoolLit a₁ let vβ‚‚ := getBoolLit aβ‚‚ match v₁, vβ‚‚ with | some true, _ => a₁ | some false, _ => aβ‚‚ | _, some true => aβ‚‚ | _, some false => a₁ | _, _ => none def boolFoldFns : List (Name Γ— BinFoldFn) := [(``strictOr, foldStrictOr), (``strictAnd, foldStrictAnd)] def binFoldFns : List (Name Γ— BinFoldFn) := boolFoldFns ++ uintBinFoldFns ++ natFoldFns def foldNatSucc (_ : Bool) (a : Expr) : Option Expr := do let n ← getNumLit a return mkRawNatLit (n+1) def foldCharOfNat (beforeErasure : Bool) (a : Expr) : Option Expr := do guard (!beforeErasure) let n ← getNumLit a if isValidChar n.toUInt32 then return mkUInt32Lit n else return mkUInt32Lit 0 def foldToNat (_ : Bool) (a : Expr) : Option Expr := do let n ← getNumLit a return mkRawNatLit n def uintFoldToNatFns : List (Name Γ— UnFoldFn) := numScalarTypes.foldl (fun r info => (info.toNatFn, foldToNat) :: r) [] def unFoldFns : List (Name Γ— UnFoldFn) := [(``Nat.succ, foldNatSucc), (``Char.ofNat, foldCharOfNat)] ++ uintFoldToNatFns def findBinFoldFn (fn : Name) : Option BinFoldFn := binFoldFns.lookup fn def findUnFoldFn (fn : Name) : Option UnFoldFn := unFoldFns.lookup fn @[export lean_fold_bin_op] def foldBinOp (beforeErasure : Bool) (f : Expr) (a : Expr) (b : Expr) : Option Expr := do match f with | Expr.const fn _ => let foldFn ← findBinFoldFn fn foldFn beforeErasure a b | _ => failure @[export lean_fold_un_op] def foldUnOp (beforeErasure : Bool) (f : Expr) (a : Expr) : Option Expr := do match f with | Expr.const fn _ => let foldFn ← findUnFoldFn fn foldFn beforeErasure a | _ => failure end Lean.Compiler
4e43f81664b19419f0e461f349d813ba0370c9fa
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/dynamics/ergodic/measure_preserving.lean
f493ce9c1f168768a1aaaf1db77dca1f93fb2701
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,825
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.measure_space /-! # Measure preserving maps We say that `f : Ξ± β†’ Ξ²` is a measure preserving map w.r.t. measures `ΞΌ : measure Ξ±` and `Ξ½ : measure Ξ²` if `f` is measurable and `map f ΞΌ = Ξ½`. In this file we define the predicate `measure_theory.measure_preserving` and prove its basic properties. We use the term "measure preserving" because in many applications `Ξ± = Ξ²` and `ΞΌ = Ξ½`. ## References Partially based on [this](https://www.isa-afp.org/browser_info/current/AFP/Ergodic_Theory/Measure_Preserving_Transformations.html) Isabelle formalization. ## Tags measure preserving map, measure -/ variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} [measurable_space Ξ±] [measurable_space Ξ²] [measurable_space Ξ³] [measurable_space Ξ΄] namespace measure_theory open measure function set variables {ΞΌa : measure Ξ±} {ΞΌb : measure Ξ²} {ΞΌc : measure Ξ³} {ΞΌd : measure Ξ΄} /-- `f` is a measure preserving map w.r.t. measures `ΞΌa` and `ΞΌb` if `f` is measurable and `map f ΞΌa = ΞΌb`. -/ @[protect_proj] structure measure_preserving (f : Ξ± β†’ Ξ²) (ΞΌa : measure Ξ± . volume_tac) (ΞΌb : measure Ξ² . volume_tac) : Prop := (measurable : measurable f) (map_eq : map f ΞΌa = ΞΌb) namespace measure_preserving protected lemma id (ΞΌ : measure Ξ±) : measure_preserving id ΞΌ ΞΌ := ⟨measurable_id, map_id⟩ lemma symm {e : Ξ± ≃ᡐ Ξ²} {ΞΌa : measure Ξ±} {ΞΌb : measure Ξ²} (h : measure_preserving e ΞΌa ΞΌb) : measure_preserving e.symm ΞΌb ΞΌa := ⟨e.symm.measurable, by rw [← h.map_eq, map_map e.symm.measurable e.measurable, e.symm_comp_self, map_id]⟩ protected lemma quasi_measure_preserving {f : Ξ± β†’ Ξ²} (hf : measure_preserving f ΞΌa ΞΌb) : quasi_measure_preserving f ΞΌa ΞΌb := ⟨hf.1, hf.2.absolutely_continuous⟩ lemma comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : measure_preserving g ΞΌb ΞΌc) (hf : measure_preserving f ΞΌa ΞΌb) : measure_preserving (g ∘ f) ΞΌa ΞΌc := ⟨hg.1.comp hf.1, by rw [← map_map hg.1 hf.1, hf.2, hg.2]⟩ protected lemma sigma_finite {f : Ξ± β†’ Ξ²} (hf : measure_preserving f ΞΌa ΞΌb) [sigma_finite ΞΌb] : sigma_finite ΞΌa := sigma_finite.of_map ΞΌa hf.1 (by rwa hf.map_eq) lemma measure_preimage {f : Ξ± β†’ Ξ²} (hf : measure_preserving f ΞΌa ΞΌb) {s : set Ξ²} (hs : measurable_set s) : ΞΌa (f ⁻¹' s) = ΞΌb s := by rw [← hf.map_eq, map_apply hf.1 hs] protected lemma iterate {f : Ξ± β†’ Ξ±} (hf : measure_preserving f ΞΌa ΞΌa) : βˆ€ n, measure_preserving (f^[n]) ΞΌa ΞΌa | 0 := measure_preserving.id ΞΌa | (n + 1) := (iterate n).comp hf variables {ΞΌ : measure Ξ±} {f : Ξ± β†’ Ξ±} {s : set Ξ±} /-- If `ΞΌ univ < n * ΞΌ s` and `f` is a map preserving measure `ΞΌ`, then for some `x ∈ s` and `0 < m < n`, `f^[m] x ∈ s`. -/ lemma exists_mem_image_mem_of_volume_lt_mul_volume (hf : measure_preserving f ΞΌ ΞΌ) (hs : measurable_set s) {n : β„•} (hvol : ΞΌ (univ : set Ξ±) < n * ΞΌ s) : βˆƒ (x ∈ s) (m ∈ Ioo 0 n), f^[m] x ∈ s := begin have A : βˆ€ m, measurable_set (f^[m] ⁻¹' s) := Ξ» m, (hf.iterate m).measurable hs, have B : βˆ€ m, ΞΌ (f^[m] ⁻¹' s) = ΞΌ s, from Ξ» m, (hf.iterate m).measure_preimage hs, have : ΞΌ (univ : set Ξ±) < (finset.range n).sum (Ξ» m, ΞΌ (f^[m] ⁻¹' s)), by simpa only [B, nsmul_eq_mul, finset.sum_const, finset.card_range], rcases exists_nonempty_inter_of_measure_univ_lt_sum_measure ΞΌ (Ξ» m hm, A m) this with ⟨i, hi, j, hj, hij, x, hxi, hxj⟩, -- without `tactic.skip` Lean closes the extra goal but it takes a long time; not sure why wlog hlt : i < j := hij.lt_or_lt using [i j, j i] tactic.skip, { simp only [set.mem_preimage, finset.mem_range] at hi hj hxi hxj, refine ⟨f^[i] x, hxi, j - i, ⟨tsub_pos_of_lt hlt, lt_of_le_of_lt (j.sub_le i) hj⟩, _⟩, rwa [← iterate_add_apply, tsub_add_cancel_of_le hlt.le] }, { exact Ξ» hi hj hij hxi hxj, this hj hi hij.symm hxj hxi } end /-- A self-map preserving a finite measure is conservative: if `ΞΌ s β‰  0`, then at least one point `x ∈ s` comes back to `s` under iterations of `f`. Actually, a.e. point of `s` comes back to `s` infinitely many times, see `measure_theory.measure_preserving.conservative` and theorems about `measure_theory.conservative`. -/ lemma exists_mem_image_mem [is_finite_measure ΞΌ] (hf : measure_preserving f ΞΌ ΞΌ) (hs : measurable_set s) (hs' : ΞΌ s β‰  0) : βˆƒ (x ∈ s) (m β‰  0), f^[m] x ∈ s := begin rcases ennreal.exists_nat_mul_gt hs' (measure_ne_top ΞΌ (univ : set Ξ±)) with ⟨N, hN⟩, rcases hf.exists_mem_image_mem_of_volume_lt_mul_volume hs hN with ⟨x, hx, m, hm, hmx⟩, exact ⟨x, hx, m, hm.1.ne', hmx⟩ end end measure_preserving end measure_theory
f2e0cc5ad36d3cc28b8662817fcd568f03b067f3
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/WFTactics.lean
c32bd34a2bbdc0a97f7d4a3fa1c5209574c69dab
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
2,605
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SizeOf import Init.WF /-- Unfold definitions commonly used in well founded relation definitions. This is primarily intended for internal use in `decreasing_tactic`. -/ macro "simp_wf" : tactic => `(tactic| simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel, WellFoundedRelation.rel]) /-- Extensible helper tactic for `decreasing_tactic`. This handles the "base case" reasoning after applying lexicographic order lemmas. It can be extended by adding more macro definitions, e.g. ``` macro_rules | `(tactic| decreasing_trivial) => `(tactic| linarith) ``` -/ syntax "decreasing_trivial" : tactic macro_rules | `(tactic| decreasing_trivial) => `(tactic| simp (config := { arith := true }); done) macro_rules | `(tactic| decreasing_trivial) => `(tactic| assumption) macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.sub_succ_lt_self; assumption) -- a - (i+1) < a - i if i < a macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt'; assumption) -- i-1 < i if j < i macro_rules | `(tactic| decreasing_trivial) => `(tactic| apply Nat.pred_lt; assumption) -- i-1 < i if i β‰  0 /-- Constructs a proof of decreasing along a well founded relation, by applying lexicographic order lemmas and using `ts` to solve the base case. If it fails, it prints a message to help the user diagnose an ill-founded recursive definition. -/ macro "decreasing_with " ts:tacticSeq : tactic => `(tactic| (simp_wf repeat (first | apply Prod.Lex.right | apply Prod.Lex.left) repeat (first | apply PSigma.Lex.right | apply PSigma.Lex.left) first | $ts | fail "failed to prove termination, possible solutions: - Use `have`-expressions to prove the remaining goals - Use `termination_by` to specify a different well-founded relation - Use `decreasing_by` to specify your own tactic for discharging this kind of goal")) /-- `decreasing_tactic` is called by default on well-founded recursions in order to synthesize a proof that recursive calls decrease along the selected well founded relation. It can be locally overridden by using `decreasing_by tac` on the recursive definition, and it can also be globally extended by adding more definitions for `decreasing_tactic` (or `decreasing_trivial`, which this tactic calls). -/ macro "decreasing_tactic" : tactic => `(tactic| decreasing_with first | decreasing_trivial | subst_vars; decreasing_trivial)
1b15c5ad957a4cdb9ba9b3b98e16e0cfca099255
dc253be9829b840f15d96d986e0c13520b085033
/algebra/product_group.hlean
b95d8603a3c3308e2b25861e79795f40422ac24f
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
4,616
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Favonia Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum .subgroup .quotient_group open eq algebra is_trunc set_quotient relation sigma prod prod.ops sum list trunc function equiv is_equiv namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} /- Binary products (direct product) of Groups -/ definition product_one [constructor] : G Γ— G' := (one, one) definition product_inv [unfold 3] : G Γ— G' β†’ G Γ— G' := Ξ»v, (v.1⁻¹, v.2⁻¹) definition product_mul [unfold 3 4] : G Γ— G' β†’ G Γ— G' β†’ G Γ— G' := Ξ»v w, (v.1 * w.1, v.2 * w.2) section local notation 1 := product_one local postfix ⁻¹ := product_inv local infix * := product_mul theorem product_mul_assoc (g₁ gβ‚‚ g₃ : G Γ— G') : g₁ * gβ‚‚ * g₃ = g₁ * (gβ‚‚ * g₃) := prod_eq !mul.assoc !mul.assoc theorem product_one_mul (g : G Γ— G') : 1 * g = g := prod_eq !one_mul !one_mul theorem product_mul_one (g : G Γ— G') : g * 1 = g := prod_eq !mul_one !mul_one theorem product_mul_left_inv (g : G Γ— G') : g⁻¹ * g = 1 := prod_eq !mul.left_inv !mul.left_inv theorem product_mul_comm {G G' : AbGroup} (g h : G Γ— G') : g * h = h * g := prod_eq !mul.comm !mul.comm end variables (G G') definition group_prod [constructor] : group (G Γ— G') := group.mk _ product_mul product_mul_assoc product_one product_one_mul product_mul_one product_inv product_mul_left_inv definition product [constructor] : Group := Group.mk _ (group_prod G G') definition ab_group_prod [constructor] (G G' : AbGroup) : ab_group (G Γ— G') := ⦃ab_group, group_prod G G', mul_comm := product_mul_comm⦄ definition ab_product [constructor] (G G' : AbGroup) : AbGroup := AbGroup.mk _ (ab_group_prod G G') definition add_product [constructor] (G G' : AddGroup) : AddGroup := group.product G G' definition add_ab_product [constructor] (G G' : AddAbGroup) : AddAbGroup := group.ab_product G G' infix ` Γ—g `:60 := group.product infix ` Γ—ag `:60 := group.ab_product infix ` Γ—a `:60 := group.add_product infix ` Γ—aa `:60 := group.add_ab_product definition product_inl [constructor] (G H : Group) : G β†’g G Γ—g H := homomorphism.mk (Ξ»x, (x, one)) (Ξ»x y, prod_eq !refl !one_mul⁻¹) definition product_inr [constructor] (G H : Group) : H β†’g G Γ—g H := homomorphism.mk (Ξ»x, (one, x)) (Ξ»x y, prod_eq !one_mul⁻¹ !refl) definition Group_sum_elim [constructor] {G H : Group} (I : AbGroup) (Ο† : G β†’g I) (ψ : H β†’g I) : G Γ—g H β†’g I := homomorphism.mk (Ξ»x, Ο† x.1 * ψ x.2) abstract (Ξ»x y, calc Ο† (x.1 * y.1) * ψ (x.2 * y.2) = (Ο† x.1 * Ο† y.1) * (ψ x.2 * ψ y.2) : by exact ap011 mul (to_respect_mul Ο† x.1 y.1) (to_respect_mul ψ x.2 y.2) ... = (Ο† x.1 * ψ x.2) * (Ο† y.1 * ψ y.2) : by exact mul.comm4 (Ο† x.1) (Ο† y.1) (ψ x.2) (ψ y.2)) end definition product_functor [constructor] {G G' H H' : Group} (Ο† : G β†’g H) (ψ : G' β†’g H') : G Γ—g G' β†’g H Γ—g H' := homomorphism.mk (Ξ»x, (Ο† x.1, ψ x.2)) (Ξ»x y, prod_eq !to_respect_mul !to_respect_mul) infix ` Γ—β†’g `:60 := group.product_functor definition product_isomorphism [constructor] {G G' H H' : Group} (Ο† : G ≃g H) (ψ : G' ≃g H') : G Γ—g G' ≃g H Γ—g H' := isomorphism.mk (Ο† Γ—β†’g ψ) !is_equiv_prod_functor infix ` ×≃g `:60 := group.product_isomorphism definition product_group_mul_eq {G H : Group} (g h : G Γ—g H) : g * h = product_mul g h := idp definition product_pr1 [constructor] (G H : Group) : G Γ—g H β†’g G := homomorphism.mk (Ξ»x, x.1) (Ξ»x y, idp) definition product_pr2 [constructor] (G H : Group) : G Γ—g H β†’g H := homomorphism.mk (Ξ»x, x.2) (Ξ»x y, idp) definition product_trivial_right [constructor] (G H : Group) (HH : is_contr H) : G Γ—g H ≃g G := begin apply isomorphism.mk (product_pr1 G H), apply adjointify _ (product_inl G H), { intro g, reflexivity }, { intro gh, exact prod_eq idp !is_prop.elim } end definition product_trivial_left [constructor] (G H : Group) (HH : is_contr G) : G Γ—g H ≃g H := begin apply isomorphism.mk (product_pr2 G H), apply adjointify _ (product_inr G H), { intro g, reflexivity }, { intro gh, exact prod_eq !is_prop.elim idp } end end group
52d0a1f771ffcc87e0aecf31536bd4ad5a9c88a9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.42.lean
5cb8a01cd4bac10cf620e1d9fe6ed76714afff19
[]
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
135
lean
/- page 91 -/ import standard namespace hide -- BEGIN inductive eq {A : Type} (a : A) : A β†’ Prop := refl : eq a a -- END end hide
9d7336530193664f3ef50a957f96f1f1bf745e8b
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/MergeFilter.lean
b70e9f52599654342636094cd6e0749bc6a00c17
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
890
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int variable integer_10: const datatypes.int theorem rule: forall ( Ξ“ scm_dept: Schema) (rel_dept: relation scm_dept) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept), denoteSQL ((SELECT1 (rightβ‹…dept_name) FROM1 ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (rightβ‹…dept_deptno)) (constantExpr integer_10)))) WHERE (equal (uvariable (rightβ‹…dept_deptno)) (constantExpr integer_10))) :SQL Ξ“ _) = denoteSQL ((SELECT1 (rightβ‹…dept_name) FROM1 (table rel_dept) WHERE (equal (uvariable (rightβ‹…dept_deptno)) (constantExpr integer_10))) :SQL Ξ“ _) := begin intros, unfold_all_denotations, funext, simp, print_size, TDP' ucongr, end
0e42bdb8e49424df9433a4abe6dc3ab66dcfd2db
a156d865507798f08f46a2f6ca204d9727f4734d
/src/tactic/metadata.lean
2b5d5e4ac9b3c934db916f026c83429d1808c6ff
[]
no_license
jesse-michael-han/formalabstracts
4e2fc8c107a3388823ffbd1671dd1e54108ea394
63a949de7989f17c791c40e580c3011516af57e0
refs/heads/master
1,625,470,495,408
1,551,315,841,000
1,551,316,547,000
136,272,424
0
0
null
1,528,259,798,000
1,528,259,798,000
null
UTF-8
Lean
false
false
4,297
lean
/- Copyright (c) 2018 Koundinya Vajjha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Koundinya Vajjha Generating meta data for a formal abstract. -/ import .depends import init.meta.interactive open tactic expr interactive nat native name list environment meta structure meta_data (n : name):= (type : expr) (value : expr) (informal : string) (typedepends : list name) (valdepends : list name) (position : string) meta def show_pos (n : name) : tactic string := do env ← get_env, pos ← returnopt (env.decl_pos n), olean ← returnopt (env.decl_olean n) <|> return "current file", -- to_string n ++ " was defined at " ++ pure $ olean ++ " : " ++ to_string pos.1 ++ ":" ++ to_string pos.2 /-TODO(Kody): What about structures? (A. Use is_structure) What about instances? (A. Anything that is not a thm, ax, defn, lemma, structure?)-/ meta def gen_metadata (n : name) : tactic (meta_data n) := do -- resolved ← resolve_constant n <|> fail ("unable to resolve constant " ++ to_string n) resolved ← resolve_constant n <|> pure n, informal ← doc_string n <|> return " ", d ← get_decl resolved <|> fail ("could not retrieve given declration"), let type := d.type, let value := d.value, typedepends ← name_dir_deps n, valdepends ← name_dir_deps_val n, position ← show_pos n, pure $ meta_data.mk n type value informal typedepends valdepends position meta def trace_metadata (n : name) : tactic unit := do f ← gen_metadata n, tactic.trace "Type: ", tactic.trace f.type, tactic.trace " ", tactic.trace "Value: ", tactic.trace f.value, tactic.trace " ", tactic.trace "Informal statement: ", tactic.trace f.informal, tactic.trace " ", tactic.trace "Type Dependencies: ", tactic.trace f.typedepends, tactic.trace " ", tactic.trace "Value Dependencies: ", tactic.trace f.valdepends, tactic.trace " ", tactic.trace "Position: ", tactic.trace f.position, tactic.trace " " def squash_linebreak (s : string) : string := list.foldr (++) "" $ list.map (Ξ» h, if h = '\n' then "" else to_string h) (s.to_list) /-TODO:1) Make this more general (arbitrary structure fields + values). 2) Make this more comprehensive (include `meta`, `noncomputable` information) -/ meta def trace_metadata_JSON (n : name) : tactic string := do env ← get_env <|> fail ("cannot get environment"), f ← gen_metadata n <|> fail ("cannot generate metadata for " ++ to_string n ++ "\npossibly due to ambiguous overload"), -- fields ← returnopt $ structure_fields env `meta_data, -- tactic.trace $ map () fields, pptype ← pp f.type, sppval ← pp f.value, let jsanitype := squash_linebreak $ format.to_string pptype, let jsanival := squash_linebreak $ format.to_string sppval, let jinformal := squash_linebreak f.informal, let tdeps := (do m ← f.typedepends, pure $ squash_linebreak $ to_string m), let jtdeps := squash_linebreak $ to_string tdeps, let vdeps := (do m ← f.valdepends, pure $ squash_linebreak $ to_string m), let jvdeps := squash_linebreak $ to_string vdeps, -- tactic.trace vdeps, let pos := f.position, -- skip pure $ to_string format!"{{\"Type\" :\"{jsanitype}\",\n\"Docstring\" :\"{jinformal}\",\n\"Value\":\"{jsanival}\",\n\"Type Dependencies\":\"{jtdeps}\",\n\"Value Dependencies\":\"{jvdeps}\",\n\"Position\":\"{pos}\"\n }" /- Tests -/ -- run_cmd trace_metadata `mathieu_group.Aut -- run_cmd trace_metadata `euclidean_space_canonical_inclusion -- run_cmd trace_metadata `nat.rec_on /- Example of a metadata trace on a structure -/ -- run_cmd trace_metadata `mathieu_group.steiner_system /- Example of a metadata trace on an instance -/ -- run_cmd trace_metadata `mathieu_group.steiner_system_fintype -- run_cmd trace_metadata `J4 -- run_cmd trace_metadata `mathieu_group.steiner_system_fintype -- run_cmd trace_metadata `dynkin_diagram -- #check mathieu_group.steiner_system_fintype -- run_cmd trace_metadata_JSON `J4 -- run_cmd trace_metadata_JSON `mathieu_group.steiner_system_fintype -- run_cmd trace_metadata_JSON `nat.rec_on -- run_cmd trace_metadata_JSON `measure_theory.lintegral_supr_directed >>= tactic.trace
344d22752d535a7b4c922e0c1316407e7de5ff4a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/simple_graph/prod.lean
2a1dd54310f7a1e21baf9831b5952adf2db20a8a
[ "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
8,020
lean
/- Copyright (c) 2022 George Peter Banyard, YaΓ«l Dillies, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: George Peter Banyard, YaΓ«l Dillies, Kyle Miller -/ import combinatorics.simple_graph.connectivity /-! # Graph products This file defines the box product of graphs and other product constructions. The box product of `G` and `H` is the graph on the product of the vertices such that `x` and `y` are related iff they agree on one component and the other one is related via either `G` or `H`. For example, the box product of two edges is a square. ## Main declarations * `simple_graph.box_prod`: The box product. ## Notation * `G β–‘ H`: The box product of `G` and `H`. ## TODO Define all other graph products! -/ variables {Ξ± Ξ² Ξ³ : Type*} namespace simple_graph variables {G : simple_graph Ξ±} {H : simple_graph Ξ²} {I : simple_graph Ξ³} {a a₁ aβ‚‚ : Ξ±} {b b₁ bβ‚‚ : Ξ²} {x y : Ξ± Γ— Ξ²} /-- Box product of simple graphs. It relates `(a₁, b)` and `(aβ‚‚, b)` if `G` relates `a₁` and `aβ‚‚`, and `(a, b₁)` and `(a, bβ‚‚)` if `H` relates `b₁` and `bβ‚‚`. -/ def box_prod (G : simple_graph Ξ±) (H : simple_graph Ξ²) : simple_graph (Ξ± Γ— Ξ²) := { adj := Ξ» x y, G.adj x.1 y.1 ∧ x.2 = y.2 ∨ H.adj x.2 y.2 ∧ x.1 = y.1, symm := Ξ» x y, by simp [and_comm, or_comm, eq_comm, adj_comm], loopless := Ξ» x, by simp } infix ` β–‘ `:70 := box_prod @[simp] lemma box_prod_adj : (G β–‘ H).adj x y ↔ G.adj x.1 y.1 ∧ x.2 = y.2 ∨ H.adj x.2 y.2 ∧ x.1 = y.1 := iff.rfl @[simp] lemma box_prod_adj_left : (G β–‘ H).adj (a₁, b) (aβ‚‚, b) ↔ G.adj a₁ aβ‚‚ := by rw [box_prod_adj, and_iff_left rfl, or_iff_left (Ξ» h : H.adj b b ∧ _, h.1.ne rfl)] @[simp] lemma box_prod_adj_right : (G β–‘ H).adj (a, b₁) (a, bβ‚‚) ↔ H.adj b₁ bβ‚‚ := by rw [box_prod_adj, and_iff_left rfl, or_iff_right (Ξ» h : G.adj a a ∧ _, h.1.ne rfl)] lemma box_prod_neighbor_set (x : Ξ± Γ— Ξ²) : (G β–‘ H).neighbor_set x = ((G.neighbor_set x.1) Γ—Λ’ {x.2}) βˆͺ ({x.1} Γ—Λ’ (H.neighbor_set x.2)) := begin ext ⟨a',b'⟩, simp only [mem_neighbor_set, set.mem_union, box_prod_adj, set.mem_prod, set.mem_singleton_iff], simp only [eq_comm, and_comm], end variables (G H I) /-- The box product is commutative up to isomorphism. `equiv.prod_comm` as a graph isomorphism. -/ @[simps] def box_prod_comm : G β–‘ H ≃g H β–‘ G := ⟨equiv.prod_comm _ _, Ξ» x y, or_comm _ _⟩ /-- The box product is associative up to isomorphism. `equiv.prod_assoc` as a graph isomorphism. -/ @[simps] def box_prod_assoc : (G β–‘ H) β–‘ I ≃g G β–‘ (H β–‘ I) := ⟨equiv.prod_assoc _ _ _, Ξ» x y, by simp only [box_prod_adj, equiv.prod_assoc_apply, or_and_distrib_right, or_assoc, prod.ext_iff, and_assoc, @and.comm (x.1.1 = _)]⟩ /-- The embedding of `G` into `G β–‘ H` given by `b`. -/ @[simps] def box_prod_left (b : Ξ²) : G β†ͺg G β–‘ H := { to_fun := Ξ» a, (a , b), inj' := Ξ» a₁ aβ‚‚, congr_arg prod.fst, map_rel_iff' := Ξ» a₁ aβ‚‚, box_prod_adj_left } /-- The embedding of `H` into `G β–‘ H` given by `a`. -/ @[simps] def box_prod_right (a : Ξ±) : H β†ͺg G β–‘ H := { to_fun := prod.mk a, inj' := Ξ» b₁ bβ‚‚, congr_arg prod.snd, map_rel_iff' := Ξ» b₁ bβ‚‚, box_prod_adj_right } namespace walk variables {G} /-- Turn a walk on `G` into a walk on `G β–‘ H`. -/ protected def box_prod_left (b : Ξ²) : G.walk a₁ aβ‚‚ β†’ (G β–‘ H).walk (a₁, b) (aβ‚‚, b) := walk.map (G.box_prod_left H b).to_hom variables (G) {H} /-- Turn a walk on `H` into a walk on `G β–‘ H`. -/ protected def box_prod_right (a : Ξ±) : H.walk b₁ bβ‚‚ β†’ (G β–‘ H).walk (a, b₁) (a, bβ‚‚) := walk.map (G.box_prod_right H a).to_hom variables {G} /-- Project a walk on `G β–‘ H` to a walk on `G` by discarding the moves in the direction of `H`. -/ def of_box_prod_left [decidable_eq Ξ²] [decidable_rel G.adj] : Ξ  {x y : Ξ± Γ— Ξ²}, (G β–‘ H).walk x y β†’ G.walk x.1 y.1 | _ _ nil := nil | x z (cons h w) := or.by_cases h (Ξ» hG, w.of_box_prod_left.cons hG.1) (Ξ» hH, show G.walk x.1 z.1, by rw hH.2; exact w.of_box_prod_left) /-- Project a walk on `G β–‘ H` to a walk on `H` by discarding the moves in the direction of `G`. -/ def of_box_prod_right [decidable_eq Ξ±] [decidable_rel H.adj] : Ξ  {x y : Ξ± Γ— Ξ²}, (G β–‘ H).walk x y β†’ H.walk x.2 y.2 | _ _ nil := nil | x z (cons h w) := (or.symm h).by_cases (Ξ» hH, w.of_box_prod_right.cons hH.1) (Ξ» hG, show H.walk x.2 z.2, by rw hG.2; exact w.of_box_prod_right) @[simp] lemma of_box_prod_left_box_prod_left [decidable_eq Ξ²] [decidable_rel G.adj] : βˆ€ {a₁ aβ‚‚ : Ξ±} (w : G.walk a₁ aβ‚‚), (w.box_prod_left H b).of_box_prod_left = w | _ _ nil := rfl | _ _ (cons' x y z h w) := begin rw [walk.box_prod_left, map_cons, of_box_prod_left, or.by_cases, dif_pos, ←walk.box_prod_left, of_box_prod_left_box_prod_left], exacts [rfl, ⟨h, rfl⟩], end @[simp] lemma of_box_prod_left_box_prod_right [decidable_eq Ξ±] [decidable_rel G.adj] : βˆ€ {b₁ bβ‚‚ : Ξ±} (w : G.walk b₁ bβ‚‚), (w.box_prod_right G a).of_box_prod_right = w | _ _ nil := rfl | _ _ (cons' x y z h w) := begin rw [walk.box_prod_right, map_cons, of_box_prod_right, or.by_cases, dif_pos, ←walk.box_prod_right, of_box_prod_left_box_prod_right], exacts [rfl, ⟨h, rfl⟩], end end walk variables {G H} protected lemma preconnected.box_prod (hG : G.preconnected) (hH : H.preconnected) : (G β–‘ H).preconnected := begin rintro x y, obtain ⟨wβ‚βŸ© := hG x.1 y.1, obtain ⟨wβ‚‚βŸ© := hH x.2 y.2, rw [←@prod.mk.eta _ _ x, ←@prod.mk.eta _ _ y], exact ⟨(w₁.box_prod_left _ _).append (wβ‚‚.box_prod_right _ _)⟩, end protected lemma preconnected.of_box_prod_left [nonempty Ξ²] (h : (G β–‘ H).preconnected) : G.preconnected := begin classical, rintro a₁ aβ‚‚, obtain ⟨w⟩ := h (a₁, classical.arbitrary _) (aβ‚‚, classical.arbitrary _), exact ⟨w.of_box_prod_left⟩, end protected lemma preconnected.of_box_prod_right [nonempty Ξ±] (h : (G β–‘ H).preconnected) : H.preconnected := begin classical, rintro b₁ bβ‚‚, obtain ⟨w⟩ := h (classical.arbitrary _, b₁) (classical.arbitrary _, bβ‚‚), exact ⟨w.of_box_prod_right⟩, end protected lemma connected.box_prod (hG : G.connected) (hH : H.connected) : (G β–‘ H).connected := by { haveI := hG.nonempty, haveI := hH.nonempty, exact ⟨hG.preconnected.box_prod hH.preconnected⟩ } protected lemma connected.of_box_prod_left (h : (G β–‘ H).connected) : G.connected := by { haveI := (nonempty_prod.1 h.nonempty).1, haveI := (nonempty_prod.1 h.nonempty).2, exact ⟨h.preconnected.of_box_prod_left⟩ } protected lemma connected.of_box_prod_right (h : (G β–‘ H).connected) : H.connected := by { haveI := (nonempty_prod.1 h.nonempty).1, haveI := (nonempty_prod.1 h.nonempty).2, exact ⟨h.preconnected.of_box_prod_right⟩ } @[simp] lemma box_prod_connected : (G β–‘ H).connected ↔ G.connected ∧ H.connected := ⟨λ h, ⟨h.of_box_prod_left, h.of_box_prod_right⟩, Ξ» h, h.1.box_prod h.2⟩ instance [decidable_eq Ξ±] [decidable_eq Ξ²] (x : Ξ± Γ— Ξ²) [fintype (G.neighbor_set x.1)] [fintype (H.neighbor_set x.2)] : fintype ((G β–‘ H).neighbor_set x) := begin rw box_prod_neighbor_set, apply_instance, end lemma box_prod_degree (x : Ξ± Γ— Ξ²) [fintype (G.neighbor_set x.1)] [fintype (H.neighbor_set x.2)] [fintype ((G β–‘ H).neighbor_set x)] : (G β–‘ H).degree x = G.degree x.1 + H.degree x.2 := begin classical, simp_rw [← card_neighbor_set_eq_degree, box_prod_neighbor_set, ← set.to_finset_card, set.to_finset_union], convert finset.card_disjoint_union _; simp only [set.to_finset_prod, finset.card_product, set.to_finset_card, set.card_singleton, mul_one, one_mul], { rintro ⟨_,_⟩ q, simp only [finset.inf_eq_inter, finset.mem_inter, finset.mem_product, set.mem_to_finset, mem_neighbor_set, set.mem_singleton_iff] at q, obtain ⟨⟨q, rfl⟩, ⟨rfl, _⟩⟩ := q, exact (q.ne rfl).elim, }, end end simple_graph
048c7733f6726afaca1e288071e5fc2cc9da375a
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/choose_letters.lean
457fbb8ff5a8c9820a85c1a1e75e981b7c36fe9d
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
1,779
lean
import for_mathlib.coprod.free_group data.list.min_max order.lexicographic open free_group multiplicative variables {ΞΉ : Type} [decidable_eq ΞΉ] [inhabited ΞΉ] (r : free_group ΞΉ) variables (T : set ΞΉ) [decidable_pred T] -- Want `x` to have least occurences in `w` -- `t` with smallest `exp_sum`, tie break is large sum of nat_abs in `r`, def vars : list ΞΉ := (r.to_list.map sigma.fst).erase_dup def exp_sum_and_occs (i : ΞΉ) : C∞ Γ— β„• := r.to_list.foldl (Ξ» n j, if j.1 = i then (n.1 * j.2, n.2 + to_add j.2.nat_abs) else n) (1, 0) def choose_t_and_x : (ΞΉ Γ— C∞) Γ— -- t and its exponent sum (ΞΉ Γ— C∞) -- x and its exponent sum. := let l := (vars r).map (Ξ» i, (i, exp_sum_and_occs r i)) in let t := (l.argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), show lex β„• (order_dual β„•), from ((to_add i.2.1).nat_abs, i.2.2))).iget in if t.2.1 = 1 then if t.1 ∈ T then let x := ((l.filter (Ξ» p : ΞΉ Γ— C∞ Γ— β„•, p.1 βˆ‰ T)).argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), i.2.2)).iget in ((t.1, 1), (x.1, x.2.1)) else let x := ((l.filter (Ξ» p : ΞΉ Γ— C∞ Γ— β„•, p.1 β‰  t.1)).argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), i.2.2)).iget in ((t.1, 1), (x.1, x.2.1)) else if t.1 ∈ T then let x := ((l.filter (Ξ» p : ΞΉ Γ— C∞ Γ— β„•, p.1 βˆ‰ T)).argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), i.2.2)).iget in ((t.1, t.2.1), (x.1, x.2.1)) else let x := ((l.filter (Ξ» p : ΞΉ Γ— C∞ Γ— β„•, p.1 βˆ‰ T)).argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), i.2.2)).iget in let t' := ((l.filter (Ξ» p : ΞΉ Γ— C∞ Γ— β„•, p.1 β‰  x.1)).argmin (Ξ» i : ΞΉ Γ— (C∞ Γ— β„•), show lex β„• (order_dual β„•), from ((to_add i.2.1).nat_abs, i.2.2))).iget in ((t'.1, t'.2.1), (x.1, x.2.1))
612f6bc4afabb51c821c27166a601985ccae6e79
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/witt_vector/domain.lean
2f908ee64d019da1e4cc169c8493b5a304b144e3
[ "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
3,732
lean
/- Copyright (c) 2022 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import ring_theory.witt_vector.identities /-! # Witt vectors over a domain This file builds to the proof `witt_vector.is_domain`, an instance that says if `R` is an integral domain, then so is `π•Ž R`. It depends on the API around iterated applications of `witt_vector.verschiebung` and `witt_vector.frobenius` found in `identities.lean`. The [proof sketch](https://math.stackexchange.com/questions/4117247/ring-of-witt-vectors-over-an-integral-domain/4118723#4118723) goes as follows: any nonzero $x$ is an iterated application of $V$ to some vector $w_x$ whose 0th component is nonzero (`witt_vector.verschiebung_nonzero`). Known identities (`witt_vector.iterate_verschiebung_mul`) allow us to transform the product of two such $x$ and $y$ to the form $V^{m+n}\left(F^n(w_x) \cdot F^m(w_y)\right)$, the 0th component of which must be nonzero. ## Main declarations * `witt_vector.iterate_verschiebung_mul_coeff` : an identity from [Haze09] * `witt_vector.is_domain` -/ noncomputable theory open_locale classical namespace witt_vector open function variables {p : β„•} {R : Type*} local notation `π•Ž` := witt_vector p -- type as `\bbW` /-! ## The `shift` operator -/ /-- `witt_vector.verschiebung` translates the entries of a Witt vector upward, inserting 0s in the gaps. `witt_vector.shift` does the opposite, removing the first entries. This is mainly useful as an auxiliary construction for `witt_vector.verschiebung_nonzero`. -/ def shift (x : π•Ž R) (n : β„•) : π•Ž R := mk p (Ξ» i, x.coeff (n + i)) lemma shift_coeff (x : π•Ž R) (n k : β„•) : (x.shift n).coeff k = x.coeff (n + k) := rfl variables [hp : fact p.prime] [comm_ring R] include hp lemma verschiebung_shift (x : π•Ž R) (k : β„•) (h : βˆ€ i < k+1, x.coeff i = 0) : verschiebung (x.shift k.succ) = x.shift k := begin ext ⟨j⟩, { rw [verschiebung_coeff_zero, shift_coeff, h], apply nat.lt_succ_self }, { simp only [verschiebung_coeff_succ, shift], congr' 1, rw [nat.add_succ, add_comm, nat.add_succ, add_comm] } end lemma eq_iterate_verschiebung {x : π•Ž R} {n : β„•} (h : βˆ€ i < n, x.coeff i = 0) : x = (verschiebung^[n] (x.shift n)) := begin induction n with k ih, { cases x; simp [shift] }, { dsimp, rw verschiebung_shift, { exact ih (Ξ» i hi, h _ (hi.trans (nat.lt_succ_self _))), }, { exact h } } end lemma verschiebung_nonzero {x : π•Ž R} (hx : x β‰  0) : βˆƒ n : β„•, βˆƒ x' : π•Ž R, x'.coeff 0 β‰  0 ∧ x = (verschiebung^[n] x') := begin have hex : βˆƒ k : β„•, x.coeff k β‰  0, { by_contra' hall, apply hx, ext i, simp only [hall, zero_coeff] }, let n := nat.find hex, use [n, x.shift n], refine ⟨nat.find_spec hex, eq_iterate_verschiebung (Ξ» i hi, not_not.mp _)⟩, exact nat.find_min hex hi, end /-! ## Witt vectors over a domain If `R` is an integral domain, then so is `π•Ž R`. This argument is adapted from <https://math.stackexchange.com/questions/4117247/ring-of-witt-vectors-over-an-integral-domain/4118723#4118723>. -/ instance [char_p R p] [no_zero_divisors R] : no_zero_divisors (π•Ž R) := ⟨λ x y, begin contrapose!, rintros ⟨ha, hb⟩, rcases verschiebung_nonzero ha with ⟨na, wa, hwa0, rfl⟩, rcases verschiebung_nonzero hb with ⟨nb, wb, hwb0, rfl⟩, refine ne_of_apply_ne (Ξ» x, x.coeff (na + nb)) _, rw [iterate_verschiebung_mul_coeff, zero_coeff], refine mul_ne_zero (pow_ne_zero _ hwa0) (pow_ne_zero _ hwb0), end⟩ instance [char_p R p] [is_domain R] : is_domain (π•Ž R) := { ..witt_vector.no_zero_divisors, ..witt_vector.nontrivial } end witt_vector
27f5f533ce6a78199479efadc91c820914e26f6e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/forInPArray.lean
4217c5589434b6a8cd22a27bb23cda797b68e6c8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
820
lean
import Lean.Data.PersistentArray def check (x : IO Nat) (expected : IO Nat) : IO Unit := do unless (← x) == (← expected) do throw $ IO.userError "unexpected result" def f1 (xs : Lean.PArray Nat) (top : Nat) : IO Nat := do let mut sum := 0 for x in xs do if x % 2 == 0 then IO.println s!"x: {x}" sum := sum + x if sum > top then return sum IO.println s!"sum: {sum}" return sum #eval f1 [1, 2, 3, 4, 5, 10, 20].toPArray' 10 #eval check (f1 [1, 2, 3, 4, 5, 10, 20].toPArray' 10) (pure 16) def f2 (xs : Lean.PArray Nat) (top : Nat) : IO Nat := do let mut sum := 0 for x in xs do if x % 2 == 0 then IO.println s!"x: {x}" sum := sum + x if sum > top then break IO.println s!"sum: {sum}" return sum #eval check (f1 (List.iota 100).toPArray' 1000) (f2 (List.iota 100).toPArray' 1000)
dac410b5d127fc1d9fc27fe8b48b7f5f30a351f5
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/data/finsupp.lean
fd8fb33722d6d053fee6ee146a3313ea58882c40
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,937
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * β„• β†’β‚€ Ξ±: Polynomials (where Ξ± is a ring) * (Οƒ β†’β‚€ β„•) β†’β‚€ Ξ±: Multivariate Polynomials (again Ξ± is a ring, and Οƒ are variable names) * Ξ± β†’β‚€ β„•: Multisets * Ξ± β†’β‚€ β„€: Abelian groups freely generated by Ξ± * Ξ² β†’β‚€ Ξ±: Linear combinations over Ξ² where Ξ± is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use Ξ± β†’β‚€ Ξ² directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module open finset variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {ΞΉ : Type*} {α₁ : Type*} {Ξ±β‚‚ : Type*} {β₁ : Type*} {Ξ²β‚‚ : Type*} reserve infix ` β†’β‚€ `:25 /-- `finsupp Ξ± Ξ²`, denoted `Ξ± β†’β‚€ Ξ²`, is the type of functions `f : Ξ± β†’ Ξ²` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (Ξ± : Type*) (Ξ² : Type*) [has_zero Ξ²] := (support : finset Ξ±) (to_fun : Ξ± β†’ Ξ²) (mem_support_to_fun : βˆ€a, a ∈ support ↔ to_fun a β‰  0) infix β†’β‚€ := finsupp namespace finsupp section basic variable [has_zero Ξ²] instance : has_coe_to_fun (Ξ± β†’β‚€ Ξ²) := ⟨λ_, Ξ± β†’ Ξ², finsupp.to_fun⟩ instance : has_zero (Ξ± β†’β‚€ Ξ²) := βŸ¨βŸ¨βˆ…, (Ξ»_, 0), Ξ» _, ⟨false.elim, Ξ» H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : Ξ±} : (0 : Ξ± β†’β‚€ Ξ²) a = 0 := rfl @[simp] lemma support_zero : (0 : Ξ± β†’β‚€ Ξ²).support = βˆ… := rfl instance : inhabited (Ξ± β†’β‚€ Ξ²) := ⟨0⟩ @[simp] lemma mem_support_iff {f : Ξ± β†’β‚€ Ξ²} : βˆ€{a:Ξ±}, a ∈ f.support ↔ f a β‰  0 := f.mem_support_to_fun lemma not_mem_support_iff {f : Ξ± β†’β‚€ Ξ²} {a} : a βˆ‰ f.support ↔ f a = 0 := by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm @[extensionality] lemma ext : βˆ€{f g : Ξ± β†’β‚€ Ξ²}, (βˆ€a, f a = g a) β†’ f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp] lemma support_eq_empty [decidable_eq Ξ²] {f : Ξ± β†’β‚€ Ξ²} : f.support = βˆ… ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ Ξ» H, (finset.ext.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance [decidable_eq Ξ±] [decidable_eq Ξ²] : decidable_eq (Ξ± β†’β‚€ Ξ²) := assume f g, decidable_of_iff (f.support = g.support ∧ (βˆ€a∈f.support, f a = g a)) ⟨assume ⟨h₁, hβ‚‚βŸ©, ext $ assume a, if h : a ∈ f.support then hβ‚‚ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, Ξ» _ _, rfl⟩⟩ lemma finite_supp (f : Ξ± β†’β‚€ Ξ²) : set.finite {a | f a β‰  0} := ⟨set.fintype_of_finset f.support (Ξ» _, mem_support_iff)⟩ lemma support_subset_iff {s : set Ξ±} {f : Ξ± β†’β‚€ Ξ²} [decidable_eq Ξ±] : ↑f.support βŠ† s ↔ (βˆ€aβˆ‰s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) end basic section single variables [decidable_eq Ξ±] [decidable_eq Ξ²] [has_zero Ξ²] {a a' : Ξ±} {b : Ξ²} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : Ξ±) (b : Ξ²) : Ξ± β†’β‚€ Ξ² := ⟨if b = 0 then βˆ… else finset.singleton a, Ξ» a', if a = a' then b else 0, Ξ» a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, Ξ» H, H rfl⟩ }, { exact ⟨false.elim, Ξ» H, H rfl⟩ }, { exact ⟨λ _, hb, Ξ» _, rfl⟩ }, { exact ⟨λ H _, h H.symm, Ξ» H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : Ξ± β†’β‚€ Ξ²) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : Ξ± β†’β‚€ Ξ²) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a β‰  a') : (single a b : Ξ± β†’β‚€ Ξ²) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : Ξ± β†’β‚€ Ξ²) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b β‰  0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support βŠ† {a} := show ite _ _ _ βŠ† _, by split_ifs; [exact empty_subset _, exact subset.refl _] end single section on_finset variables [decidable_eq Ξ²] [has_zero Ξ²] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset Ξ±) (f : Ξ± β†’ Ξ²) (hf : βˆ€a, f a β‰  0 β†’ a ∈ s) : Ξ± β†’β‚€ Ξ² := ⟨s.filter (Ξ»a, f a β‰  0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, Ξ» H, (H h).elim⟩) (assume h : f a β‰  0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset Ξ±} {f : Ξ± β†’ Ξ²} {hf a} : (on_finset s f hf : Ξ± β†’β‚€ Ξ²) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset Ξ±} {f : Ξ± β†’ Ξ²} {hf} : (on_finset s f hf).support βŠ† s := filter_subset _ end on_finset section map_range variables [has_zero β₁] [has_zero Ξ²β‚‚] [decidable_eq Ξ²β‚‚] /-- The composition of `f : β₁ β†’ Ξ²β‚‚` and `g : Ξ± β†’β‚€ β₁` is `map_range f hf g : Ξ± β†’β‚€ Ξ²β‚‚`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ β†’ Ξ²β‚‚) (hf : f 0 = 0) (g : Ξ± β†’β‚€ β₁) : Ξ± β†’β‚€ Ξ²β‚‚ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact Ξ» H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ β†’ Ξ²β‚‚} {hf : f 0 = 0} {g : Ξ± β†’β‚€ β₁} {a : Ξ±} : map_range f hf g a = f (g a) := rfl lemma support_map_range {f : β₁ β†’ Ξ²β‚‚} {hf : f 0 = 0} {g : Ξ± β†’β‚€ β₁} : (map_range f hf g).support βŠ† g.support := support_on_finset_subset variables [decidable_eq Ξ±] [decidable_eq β₁] @[simp] lemma map_range_single {f : β₁ β†’ Ξ²β‚‚} {hf : f 0 = 0} {a : Ξ±} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ Ξ» a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range section zip_with variables [has_zero Ξ²] [has_zero β₁] [has_zero Ξ²β‚‚] [decidable_eq Ξ±] [decidable_eq Ξ²] /-- `zip_with f hf g₁ gβ‚‚` is the finitely supported function satisfying `zip_with f hf g₁ gβ‚‚ a = f (g₁ a) (gβ‚‚ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ β†’ Ξ²β‚‚ β†’ Ξ²) (hf : f 0 0 = 0) (g₁ : Ξ± β†’β‚€ β₁) (gβ‚‚ : Ξ± β†’β‚€ Ξ²β‚‚) : (Ξ± β†’β‚€ Ξ²) := on_finset (g₁.support βˆͺ gβ‚‚.support) (Ξ»a, f (g₁ a) (gβ‚‚ a)) $ Ξ» a H, begin haveI := classical.dec_eq β₁, simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, hβ‚‚βŸ©, rw [h₁, hβ‚‚] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ β†’ Ξ²β‚‚ β†’ Ξ²} {hf : f 0 0 = 0} {g₁ : Ξ± β†’β‚€ β₁} {gβ‚‚ : Ξ± β†’β‚€ Ξ²β‚‚} {a : Ξ±} : zip_with f hf g₁ gβ‚‚ a = f (g₁ a) (gβ‚‚ a) := rfl lemma support_zip_with {f : β₁ β†’ Ξ²β‚‚ β†’ Ξ²} {hf : f 0 0 = 0} {g₁ : Ξ± β†’β‚€ β₁} {gβ‚‚ : Ξ± β†’β‚€ Ξ²β‚‚} : (zip_with f hf g₁ gβ‚‚).support βŠ† g₁.support βˆͺ gβ‚‚.support := support_on_finset_subset end zip_with section erase variables [decidable_eq Ξ±] [decidable_eq Ξ²] def erase [has_zero Ξ²] (a : Ξ±) (f : Ξ± β†’β‚€ Ξ²) : Ξ± β†’β‚€ Ξ² := ⟨f.support.erase a, (Ξ»a', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, Ξ» H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero Ξ²] {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero Ξ²] {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero Ξ²] {a a' : Ξ±} {f : Ξ± β†’β‚€ Ξ²} (h : a' β‰  a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero Ξ²] [add_comm_monoid Ξ³] (f : Ξ± β†’β‚€ Ξ²) (g : Ξ± β†’ Ξ² β†’ Ξ³) : Ξ³ := f.support.sum (Ξ»a, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive finsupp.sum] def prod [has_zero Ξ²] [comm_monoid Ξ³] (f : Ξ± β†’β‚€ Ξ²) (g : Ξ± β†’ Ξ² β†’ Ξ³) : Ξ³ := f.support.prod (Ξ»a, g a (f a)) attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1 @[to_additive finsupp.sum_map_range_index] lemma prod_map_range_index [has_zero β₁] [has_zero Ξ²β‚‚] [comm_monoid Ξ³] [decidable_eq Ξ²β‚‚] {f : β₁ β†’ Ξ²β‚‚} {hf : f 0 = 0} {g : Ξ± β†’β‚€ β₁} {h : Ξ± β†’ Ξ²β‚‚ β†’ Ξ³} (h0 : βˆ€a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (Ξ»a b, h a (f b)) := finset.prod_subset support_map_range $ Ξ» _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive finsupp.sum_zero_index] lemma prod_zero_index [add_comm_monoid Ξ²] [comm_monoid Ξ³] {h : Ξ± β†’ Ξ² β†’ Ξ³} : (0 : Ξ± β†’β‚€ Ξ²).prod h = 1 := rfl section decidable variables [decidable_eq Ξ±] [decidable_eq Ξ²] section add_monoid variables [add_monoid Ξ²] @[to_additive finsupp.sum_single_index] lemma prod_single_index [comm_monoid Ξ³] {a : Ξ±} {b : Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton, prod_singleton, single_eq_same] } end instance : has_add (Ξ± β†’β‚€ Ξ²) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} {a : Ξ±} : (g₁ + gβ‚‚) a = g₁ a + gβ‚‚ a := rfl lemma support_add {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} : (g₁ + gβ‚‚).support βŠ† g₁.support βˆͺ gβ‚‚.support := support_zip_with lemma support_add_eq {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} (h : disjoint g₁.support gβ‚‚.support): (g₁ + gβ‚‚).support = g₁.support βˆͺ gβ‚‚.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a βˆ‰ gβ‚‚.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a βˆ‰ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : Ξ±} {b₁ bβ‚‚ : Ξ²} : single a (b₁ + bβ‚‚) = single a b₁ + single a bβ‚‚ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (Ξ± β†’β‚€ Ξ²) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } lemma single_add_erase {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} : single a (f a) + f.erase a = f := ext $ Ξ» a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} : f.erase a + single a (f a) = f := ext $ Ξ» a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[elab_as_eliminator] protected theorem induction {p : (Ξ± β†’β‚€ Ξ²) β†’ Prop} (f : Ξ± β†’β‚€ Ξ²) (h0 : p 0) (ha : βˆ€a b (f : Ξ± β†’β‚€ Ξ²), a βˆ‰ f.support β†’ b β‰  0 β†’ p f β†’ p (single a b + f)) : p f := suffices βˆ€s (f : Ξ± β†’β‚€ Ξ²), f.support = s β†’ p f, from this _ _ rfl, assume s, finset.induction_on s (Ξ» f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact Ξ» H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma inductionβ‚‚ {p : (Ξ± β†’β‚€ Ξ²) β†’ Prop} (f : Ξ± β†’β‚€ Ξ²) (h0 : p 0) (ha : βˆ€a b (f : Ξ± β†’β‚€ Ξ²), a βˆ‰ f.support β†’ b β‰  0 β†’ p f β†’ p (f + single a b)) : p f := suffices βˆ€s (f : Ξ± β†’β‚€ Ξ²), f.support = s β†’ p f, from this _ _ rfl, assume s, finset.induction_on s (Ξ» f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact Ξ» H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end end add_monoid instance [add_comm_monoid Ξ²] : add_comm_monoid (Ξ± β†’β‚€ Ξ²) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group Ξ²] : add_group (Ξ± β†’β‚€ Ξ²) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid Ξ²] [decidable_eq Ξ±] [decidable_eq Ξ²] (s : multiset Ξ²) (a : Ξ±) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ Ξ» a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid Ξ²] [decidable_eq Ξ±] [decidable_eq Ξ²] (s : finset Ξ³) (f : Ξ³ β†’ Ξ²) (a : Ξ±) : single a (s.sum f) = s.sum (Ξ»b, single a (f b)) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero Ξ³] [add_comm_monoid Ξ²] [decidable_eq Ξ±] [decidable_eq Ξ²] (s : Ξ΄ β†’β‚€ Ξ³) (f : Ξ΄ β†’ Ξ³ β†’ Ξ²) (a : Ξ±) : single a (s.sum f) = s.sum (Ξ»d c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive finsupp.sum_neg_index] lemma prod_neg_index [add_group Ξ²] [comm_monoid Ξ³] {g : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h0 : βˆ€a, h a 0 = 1) : (-g).prod h = g.prod (Ξ»a b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group Ξ²] {g : Ξ± β†’β‚€ Ξ²} {a : Ξ±} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group Ξ²] {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} {a : Ξ±} : (g₁ - gβ‚‚) a = g₁ a - gβ‚‚ a := rfl @[simp] lemma support_neg [add_group Ξ²] {f : Ξ± β†’β‚€ Ξ²} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... βŠ† support (- f) : support_map_range) instance [add_comm_group Ξ²] : add_comm_group (Ξ± β†’β‚€ Ξ²) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid Ξ²] {f : α₁ β†’β‚€ β₁} {g : α₁ β†’ β₁ β†’ Ξ± β†’β‚€ Ξ²} {aβ‚‚ : Ξ±} : (f.sum g) aβ‚‚ = f.sum (Ξ»a₁ b, g a₁ b aβ‚‚) := (finset.sum_hom (Ξ»f : Ξ± β†’β‚€ Ξ², f aβ‚‚) rfl (assume a b, rfl)).symm lemma support_sum [has_zero β₁] [add_comm_monoid Ξ²] {f : α₁ β†’β‚€ β₁} {g : α₁ β†’ β₁ β†’ (Ξ± β†’β‚€ Ξ²)} : (f.sum g).support βŠ† f.support.bind (Ξ»a, (g a (f a)).support) := have βˆ€a₁ : Ξ±, f.sum (Ξ» (a : α₁) (b : β₁), (g a b) a₁) β‰  0 β†’ (βˆƒ (a : α₁), f a β‰  0 ∧ Β¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid Ξ²] [add_comm_monoid Ξ³] {f : Ξ± β†’β‚€ Ξ²} : f.sum (Ξ»a b, (0 : Ξ³)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid Ξ²] [add_comm_monoid Ξ³] {f : Ξ± β†’β‚€ Ξ²} {h₁ hβ‚‚ : Ξ± β†’ Ξ² β†’ Ξ³} : f.sum (Ξ»a b, h₁ a b + hβ‚‚ a b) = f.sum h₁ + f.sum hβ‚‚ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid Ξ²] [add_comm_group Ξ³] {f : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} : f.sum (Ξ»a b, - h a b) = - f.sum h := finset.sum_hom (@has_neg.neg Ξ³ _) neg_zero (assume a b, neg_add _ _) @[simp] lemma sum_sub [add_comm_monoid Ξ²] [add_comm_group Ξ³] {f : Ξ± β†’β‚€ Ξ²} {h₁ hβ‚‚ : Ξ± β†’ Ξ² β†’ Ξ³} : f.sum (Ξ»a b, h₁ a b - hβ‚‚ a b) = f.sum h₁ - f.sum hβ‚‚ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid Ξ²] {f : Ξ± β†’β‚€ Ξ²} : f.sum single = f := have βˆ€a:Ξ±, f.sum (Ξ»a' b, ite (a' = a) b 0) = ({a} : finset Ξ±).sum (Ξ»a', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset Ξ±) βŠ† f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (Ξ» _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (f.support.sum (Ξ»a, (0 : Ξ²))), { refine (finset.sum_congr rfl $ Ξ» a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, insert_empty_eq_singleton, sum_singleton, if_pos] @[to_additive finsupp.sum_add_index] lemma prod_add_index [add_comm_monoid Ξ²] [comm_monoid Ξ³] {f g : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h_zero : βˆ€a, h a 0 = 1) (h_add : βˆ€a b₁ bβ‚‚, h a (b₁ + bβ‚‚) = h a b₁ * h a bβ‚‚) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support βˆͺ g.support).prod (Ξ»a, h a (f a)) = f.prod h, from (finset.prod_subset finset.subset_union_left $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : (f.support βˆͺ g.support).prod (Ξ»a, h a (g a)) = g.prod h, from (finset.prod_subset finset.subset_union_right $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc (f + g).support.prod (Ξ»a, h a ((f + g) a)) = (f.support βˆͺ g.support).prod (Ξ»a, h a ((f + g) a)) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (f.support βˆͺ g.support).prod (Ξ»a, h a (f a)) * (f.support βˆͺ g.support).prod (Ξ»a, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group Ξ²] [add_comm_group Ξ³] {f g : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h_sub : βˆ€a b₁ bβ‚‚, h a (b₁ - bβ‚‚) = h a b₁ - h a bβ‚‚) : (f - g).sum h = f.sum h - g.sum h := have h_zero : βˆ€a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : βˆ€a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : βˆ€a b₁ bβ‚‚, h a (b₁ + bβ‚‚) = h a b₁ + h a bβ‚‚, from assume a b₁ bβ‚‚, have h a (b₁ - (- bβ‚‚)) = h a b₁ - h a (- bβ‚‚), from h_sub a b₁ (-bβ‚‚), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive finsupp.sum_finset_sum_index] lemma prod_finset_sum_index [add_comm_monoid Ξ²] [comm_monoid Ξ³] [decidable_eq ΞΉ] {s : finset ΞΉ} {g : ΞΉ β†’ Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h_zero : βˆ€a, h a 0 = 1) (h_add : βˆ€a b₁ bβ‚‚, h a (b₁ + bβ‚‚) = h a b₁ * h a bβ‚‚): s.prod (Ξ»i, (g i).prod h) = (s.sum g).prod h := finset.induction_on s rfl $ Ξ» a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive finsupp.sum_sum_index] lemma prod_sum_index [decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid Ξ²] [comm_monoid Ξ³] {f : α₁ β†’β‚€ β₁} {g : α₁ β†’ β₁ β†’ Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h_zero : βˆ€a, h a 0 = 1) (h_add : βˆ€a b₁ bβ‚‚, h a (b₁ + bβ‚‚) = h a b₁ * h a bβ‚‚): (f.sum g).prod h = f.prod (Ξ»a b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [decidable_eq Ξ±] [decidable_eq Ξ²] [add_comm_monoid Ξ²] [add_comm_monoid Ξ³] (f : multiset (Ξ± β†’β‚€ Ξ²)) (h : Ξ± β†’ Ξ² β†’ Ξ³) (hβ‚€ : βˆ€a, h a 0 = 0) (h₁ : βˆ€ (a : Ξ±) (b₁ bβ‚‚ : Ξ²), h a (b₁ + bβ‚‚) = h a b₁ + h a bβ‚‚) : (f.sum.sum h) = (f.map $ Ξ»g:Ξ± β†’β‚€ Ξ², g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index hβ‚€ h₁, ih] lemma multiset_map_sum [has_zero Ξ²] {f : Ξ± β†’β‚€ Ξ²} {m : Ξ³ β†’ Ξ΄} {h : Ξ± β†’ Ξ² β†’ multiset Ξ³} : multiset.map m (f.sum h) = f.sum (Ξ»a b, (h a b).map m) := (finset.sum_hom _ (multiset.map_zero m) (multiset.map_add m)).symm lemma multiset_sum_sum [has_zero Ξ²] [add_comm_monoid Ξ³] {f : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ multiset Ξ³} : multiset.sum (f.sum h) = f.sum (Ξ»a b, multiset.sum (h a b)) := begin refine (finset.sum_hom multiset.sum _ _).symm, exact multiset.sum_zero, exact multiset.sum_add end section map_domain variables [decidable_eq α₁] [decidable_eq Ξ±β‚‚] [add_comm_monoid Ξ²] {v v₁ vβ‚‚ : Ξ± β†’β‚€ Ξ²} /-- Given `f : α₁ β†’ Ξ±β‚‚` and `v : α₁ β†’β‚€ Ξ²`, `map_domain f v : Ξ±β‚‚ β†’β‚€ Ξ²` is the finitely supported function whose value at `a : Ξ±β‚‚` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ β†’ Ξ±β‚‚) (v : α₁ β†’β‚€ Ξ²) : Ξ±β‚‚ β†’β‚€ Ξ² := v.sum $ Ξ»a, single (f a) lemma map_domain_id : map_domain id v = v := sum_single lemma map_domain_comp {f : Ξ± β†’ α₁} {g : α₁ β†’ Ξ±β‚‚} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (Ξ» _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : Ξ± β†’ α₁} {a : Ξ±} {b : Ξ²} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero lemma map_domain_zero {f : Ξ± β†’ Ξ±β‚‚} : map_domain f 0 = (0 : Ξ±β‚‚ β†’β‚€ Ξ²) := sum_zero_index lemma map_domain_congr {f g : Ξ± β†’ Ξ±β‚‚} (h : βˆ€x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ Ξ» _ H, by simp only [h _ H] lemma map_domain_add {f : Ξ± β†’ Ξ±β‚‚} : map_domain f (v₁ + vβ‚‚) = map_domain f v₁ + map_domain f vβ‚‚ := sum_add_index (Ξ» _, single_zero) (Ξ» _ _ _, single_add) lemma map_domain_finset_sum [decidable_eq ΞΉ] {f : Ξ± β†’ Ξ±β‚‚} {s : finset ΞΉ} {v : ΞΉ β†’ Ξ± β†’β‚€ Ξ²} : map_domain f (s.sum v) = s.sum (Ξ»i, map_domain f (v i)) := eq.symm $ sum_finset_sum_index (Ξ» _, single_zero) (Ξ» _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : Ξ± β†’ Ξ±β‚‚} {s : Ξ± β†’β‚€ β₁} {v : Ξ± β†’ β₁ β†’ Ξ± β†’β‚€ Ξ²} : map_domain f (s.sum v) = s.sum (Ξ»a b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (Ξ» _, single_zero) (Ξ» _ _ _, single_add) lemma map_domain_support {f : Ξ± β†’ Ξ±β‚‚} {s : Ξ± β†’β‚€ Ξ²} : (s.map_domain f).support βŠ† s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive finsupp.sum_map_domain_index] lemma prod_map_domain_index [comm_monoid Ξ³] {f : Ξ± β†’ Ξ±β‚‚} {s : Ξ± β†’β‚€ Ξ²} {h : Ξ±β‚‚ β†’ Ξ² β†’ Ξ³} (h_zero : βˆ€a, h a 0 = 1) (h_add : βˆ€a b₁ bβ‚‚, h a (b₁ + bβ‚‚) = h a b₁ * h a bβ‚‚) : (s.map_domain f).prod h = s.prod (Ξ»a b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ Ξ» _ _, prod_single_index (h_zero _) end map_domain /-- The product of `f g : Ξ± β†’β‚€ Ξ²` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `Ξ±` is the monoid of monomial exponents.) -/ instance [has_add Ξ±] [semiring Ξ²] : has_mul (Ξ± β†’β‚€ Ξ²) := ⟨λf g, f.sum $ Ξ»a₁ b₁, g.sum $ Ξ»aβ‚‚ bβ‚‚, single (a₁ + aβ‚‚) (b₁ * bβ‚‚)⟩ lemma mul_def [has_add Ξ±] [semiring Ξ²] {f g : Ξ± β†’β‚€ Ξ²} : f * g = (f.sum $ Ξ»a₁ b₁, g.sum $ Ξ»aβ‚‚ bβ‚‚, single (a₁ + aβ‚‚) (b₁ * bβ‚‚)) := rfl /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero Ξ±] [has_zero Ξ²] [has_one Ξ²] : has_one (Ξ± β†’β‚€ Ξ²) := ⟨single 0 1⟩ lemma one_def [has_zero Ξ±] [has_zero Ξ²] [has_one Ξ²] : 1 = (single 0 1 : Ξ± β†’β‚€ Ξ²) := rfl section filter -- TODO: remove filter? build upon subtype_domain? section has_zero variables [has_zero Ξ²] {p : Ξ± β†’ Prop} [decidable_pred p] {f : Ξ± β†’β‚€ Ξ²} /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : Ξ± β†’ Prop) [decidable_pred p] (f : Ξ± β†’β‚€ Ξ²) : Ξ± β†’β‚€ Ξ² := on_finset f.support (Ξ»a, if p a then f a else 0) $ Ξ» a H, mem_support_iff.2 $ Ξ» h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : Ξ±} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : Ξ±} (h : Β¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg H, mem_filter, H, and_false, ne.def, ne_self_iff_false] end has_zero lemma filter_pos_add_filter_neg [add_monoid Ξ²] {f : Ξ± β†’β‚€ Ξ²} {p : Ξ± β†’ Prop} [decidable_pred p] [decidable_pred (Ξ»a, Β¬ p a)] : f.filter p + f.filter (Ξ»a, Β¬ p a) = f := finsupp.ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter section subtype_domain variables {Ξ±' : Type*} [has_zero Ξ΄] {p : Ξ± β†’ Prop} [decidable_pred p] section zero variables [has_zero Ξ²] {v v' : Ξ±' β†’β‚€ Ξ²} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : Ξ± β†’ Prop) [decidable_pred p] (f : Ξ± β†’β‚€ Ξ²) : (subtype p β†’β‚€ Ξ²) := ⟨f.support.subtype p, f ∘ subtype.val, Ξ» a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : Ξ± β†’β‚€ Ξ²} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : Ξ± β†’β‚€ Ξ²} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : Ξ± β†’β‚€ Ξ²) = 0 := rfl @[to_additive finsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [comm_monoid Ξ³] {v : Ξ± β†’β‚€ Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (hp : βˆ€x∈v.support, p x) : (v.subtype_domain p).prod (Ξ»a b, h a.1 b) = v.prod h := prod_bij (Ξ»p _, p.val) (Ξ» _, mem_subtype.1) (Ξ» _ _, rfl) (Ξ» _ _ _ _, subtype.eq) (Ξ» b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid Ξ²] {v v' : Ξ±' β†’β‚€ Ξ²} @[simp] lemma subtype_domain_add {v v' : Ξ± β†’β‚€ Ξ²} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ Ξ» _, rfl end monoid section comm_monoid variables [add_comm_monoid Ξ²] lemma subtype_domain_sum {s : finset Ξ³} {h : Ξ³ β†’ Ξ± β†’β‚€ Ξ²} : (s.sum h).subtype_domain p = s.sum (Ξ»c, (h c).subtype_domain p) := eq.symm (finset.sum_hom _ subtype_domain_zero $ assume v v', subtype_domain_add) lemma subtype_domain_finsupp_sum {s : Ξ³ β†’β‚€ Ξ΄} {h : Ξ³ β†’ Ξ΄ β†’ Ξ± β†’β‚€ Ξ²} : (s.sum h).subtype_domain p = s.sum (Ξ»c d, (h c d).subtype_domain p) := subtype_domain_sum end comm_monoid section group variables [add_group Ξ²] {v v' : Ξ±' β†’β‚€ Ξ²} @[simp] lemma subtype_domain_neg {v : Ξ± β†’β‚€ Ξ²} : (- v).subtype_domain p = - v.subtype_domain p := ext $ Ξ» _, rfl @[simp] lemma subtype_domain_sub {v v' : Ξ± β†’β‚€ Ξ²} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ Ξ» _, rfl end group end subtype_domain section multiset def to_multiset (f : Ξ± β†’β‚€ β„•) : multiset Ξ± := f.sum (Ξ»a n, add_monoid.smul n {a}) @[simp] lemma count_to_multiset [decidable_eq Ξ±] (f : Ξ± β†’β‚€ β„•) (a : Ξ±) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (Ξ»x n, (add_monoid.smul n {x} : multiset Ξ±).count a) : (finset.sum_hom _ (multiset.count_zero a) (multiset.count_add a)).symm ... = f.sum (Ξ»x n, n * ({x} : multiset Ξ±).count a) : by simp only [multiset.count_smul] ... = f.sum (Ξ»x n, n * (x :: 0 : multiset Ξ±).count a) : rfl ... = f a * (a :: 0 : multiset Ξ±).count a : sum_eq_single _ (Ξ» a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (Ξ» H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] def of_multiset [decidable_eq Ξ±] (m : multiset Ξ±) : Ξ± β†’β‚€ β„• := on_finset m.to_finset (Ξ»a, m.count a) $ Ξ» a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply [decidable_eq Ξ±] (m : multiset Ξ±) (a : Ξ±) : of_multiset m a = m.count a := rfl def equiv_multiset [decidable_eq Ξ±] : (Ξ± β†’β‚€ β„•) ≃ (multiset Ξ±) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ Ξ» a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ Ξ» a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [decidable_eq Ξ±] [decidable_eq Ξ²] [add_comm_monoid Ξ²] {s : multiset (Ξ± β†’β‚€ Ξ²)} (a : Ξ±) : a ∈ s.sum.support β†’ βˆƒf∈s, a ∈ (f : Ξ± β†’β‚€ Ξ²).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', hβ‚€, hβ‚βŸ©, exact ⟨f', multiset.mem_cons_of_mem hβ‚€, hβ‚βŸ© } end lemma mem_support_finset_sum [decidable_eq Ξ±] [decidable_eq Ξ²] [add_comm_monoid Ξ²] {s : finset Ξ³} {h : Ξ³ β†’ Ξ± β†’β‚€ Ξ²} (a : Ξ±) (ha : a ∈ (s.sum h).support) : βˆƒc∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm β–Έ hfa⟩ lemma mem_support_single [decidable_eq Ξ±] [decidable_eq Ξ²] [has_zero Ξ²] (a a' : Ξ±) (b : Ξ²) : a ∈ (single a' b).support ↔ a = a' ∧ b β‰  0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, Ξ» ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset section curry_uncurry protected def curry [decidable_eq Ξ±] [decidable_eq Ξ²] [decidable_eq Ξ³] [add_comm_monoid Ξ³] (f : (Ξ± Γ— Ξ²) β†’β‚€ Ξ³) : Ξ± β†’β‚€ (Ξ² β†’β‚€ Ξ³) := f.sum $ Ξ»p c, single p.1 (single p.2 c) lemma sum_curry_index [decidable_eq Ξ±] [decidable_eq Ξ²] [decidable_eq Ξ³] [add_comm_monoid Ξ³] [add_comm_monoid Ξ΄] (f : (Ξ± Γ— Ξ²) β†’β‚€ Ξ³) (g : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ΄) (hgβ‚€ : βˆ€ a b, g a b 0 = 0) (hg₁ : βˆ€a b cβ‚€ c₁, g a b (cβ‚€ + c₁) = g a b cβ‚€ + g a b c₁) : f.curry.sum (Ξ»a f, f.sum (g a)) = f.sum (Ξ»p c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a bβ‚€ b₁, sum_add_index (assume a, hgβ‚€ _ _) (assume c dβ‚€ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hgβ‚€ _ _) end protected def uncurry [decidable_eq Ξ±] [decidable_eq Ξ²] [decidable_eq Ξ³] [add_comm_monoid Ξ³] (f : Ξ± β†’β‚€ (Ξ² β†’β‚€ Ξ³)) : (Ξ± Γ— Ξ²) β†’β‚€ Ξ³ := f.sum $ Ξ»a g, g.sum $ Ξ»b c, single (a, b) c def finsupp_prod_equiv [add_comm_monoid Ξ³] [decidable_eq Ξ±] [decidable_eq Ξ²] [decidable_eq Ξ³] : ((Ξ± Γ— Ξ²) β†’β‚€ Ξ³) ≃ (Ξ± β†’β‚€ (Ξ² β†’β‚€ Ξ³)) := by refine ⟨finsupp.curry, finsupp.uncurry, Ξ» f, _, Ξ» f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] end curry_uncurry section variables [add_monoid Ξ±] [semiring Ξ²] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : Ξ± β†’β‚€ Ξ²) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] private lemma mul_zero (f : Ξ± β†’β‚€ Ξ²) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : Ξ± β†’β‚€ Ξ²) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : Ξ± β†’β‚€ Ξ²) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] def to_semiring : semiring (Ξ± β†’β‚€ Ξ²) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end local attribute [instance] to_semiring def to_comm_semiring [add_comm_monoid Ξ±] [comm_semiring Ξ²] : comm_semiring (Ξ± β†’β‚€ Ξ²) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. finsupp.to_semiring } local attribute [instance] to_comm_semiring def to_ring [add_monoid Ξ±] [ring Ξ²] : ring (Ξ± β†’β‚€ Ξ²) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.to_semiring } def to_comm_ring [add_comm_monoid Ξ±] [comm_ring Ξ²] : comm_ring (Ξ± β†’β‚€ Ξ²) := { mul_comm := mul_comm, .. finsupp.to_ring} lemma single_mul_single [has_add Ξ±] [semiring Ξ²] {a₁ aβ‚‚ : Ξ±} {b₁ bβ‚‚ : Ξ²}: single a₁ b₁ * single aβ‚‚ bβ‚‚ = single (a₁ + aβ‚‚) (b₁ * bβ‚‚) := (sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [_root_.mul_zero, single_zero])) lemma prod_single [decidable_eq ΞΉ] [add_comm_monoid Ξ±] [comm_semiring Ξ²] {s : finset ΞΉ} {a : ΞΉ β†’ Ξ±} {b : ΞΉ β†’ Ξ²} : s.prod (Ξ»i, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ Ξ» a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] section variable (Ξ²) def to_has_scalar' [ring Ξ³] [module Ξ³ Ξ²] : has_scalar Ξ³ (Ξ± β†’β‚€ Ξ²) := ⟨λa v, v.map_range ((β€’) a) (smul_zero)⟩ local attribute [instance] to_has_scalar' @[simp] lemma smul_apply' [ring Ξ³] [module Ξ³ Ξ²] {a : Ξ±} {b : Ξ³} {v : Ξ± β†’β‚€ Ξ²} : (b β€’ v) a = b β€’ (v a) := rfl def to_module [ring Ξ³] [module Ξ³ Ξ²] : module Ξ³ (Ξ± β†’β‚€ Ξ²) := { smul := (β€’), smul_add := assume a x y, finsupp.ext $ Ξ» _, smul_add, add_smul := assume a x y, finsupp.ext $ Ξ» _, add_smul, one_smul := assume x, finsupp.ext $ Ξ» _, one_smul, mul_smul := assume r s x, finsupp.ext $ Ξ» _, mul_smul, .. finsupp.add_comm_group } end def to_has_scalar [ring Ξ²] : has_scalar Ξ² (Ξ± β†’β‚€ Ξ²) := to_has_scalar' Ξ² local attribute [instance] to_has_scalar @[simp] lemma smul_apply [ring Ξ²] {a : Ξ±} {b : Ξ²} {v : Ξ± β†’β‚€ Ξ²} : (b β€’ v) a = b β€’ (v a) := rfl lemma sum_smul_index [ring Ξ²] [add_comm_monoid Ξ³] {g : Ξ± β†’β‚€ Ξ²} {b : Ξ²} {h : Ξ± β†’ Ξ² β†’ Ξ³} (h0 : βˆ€i, h i 0 = 0) : (b β€’ g).sum h = g.sum (Ξ»i a, h i (b * a)) := finsupp.sum_map_range_index h0 end decidable section variables [semiring Ξ²] [semiring Ξ³] lemma sum_mul (b : Ξ³) (s : Ξ± β†’β‚€ Ξ²) {f : Ξ± β†’ Ξ² β†’ Ξ³} : (s.sum f) * b = s.sum (Ξ» a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum [semiring Ξ²] [semiring Ξ³] (b : Ξ³) (s : Ξ± β†’β‚€ Ξ²) {f : Ξ± β†’ Ξ² β†’ Ξ³} : b * (s.sum f) = s.sum (Ξ» a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] end end finsupp
b1983c188c6707a6f24d171538d92e605b8a52ed
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/multiset/powerset.lean
199cf2ec4d733d598d53e5427a6ae041b65bf786
[ "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
9,262
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.basic /-! # The powerset of a multiset -/ namespace multiset open list variables {Ξ± : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ def powerset_aux (l : list Ξ±) : list (multiset Ξ±) := 0 :: sublists_aux l (Ξ» x y, x :: y) theorem powerset_aux_eq_map_coe {l : list Ξ±} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ Ξ± (multiset Ξ±) l (Ξ» x, [↑x]) = sublists_aux l (Ξ» x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list Ξ±} {s} : s ∈ powerset_aux l ↔ s ≀ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powerset_aux' (l : list Ξ±) : list (multiset Ξ±) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list Ξ±} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _ @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil Ξ±) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : Ξ±) (l : list Ξ±) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : powerset_aux' l₁ ~ powerset_aux' lβ‚‚ := begin induction p with a l₁ lβ‚‚ p IH a b l l₁ lβ‚‚ l₃ p₁ pβ‚‚ IH₁ IHβ‚‚, {simp}, { simp, exact IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IHβ‚‚ } end theorem powerset_aux_perm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : powerset_aux l₁ ~ powerset_aux lβ‚‚ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm /-- The power set of a multiset. -/ def powerset (s : multiset Ξ±) : multiset (multiset Ξ±) := quot.lift_on s (Ξ» l, (powerset_aux l : multiset (multiset Ξ±))) (Ξ» l₁ lβ‚‚ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list Ξ±) : @powerset Ξ± l = ((sublists l).map coe : list (multiset Ξ±)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list Ξ±) : @powerset Ξ± l = ((sublists' l).map coe : list (multiset Ξ±)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset Ξ± 0 = {0} := rfl @[simp] theorem powerset_cons (a : Ξ±) (s) : powerset (a ::β‚˜ s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ Ξ» l, by simp; refl @[simp] theorem mem_powerset {s t : multiset Ξ±} : s ∈ powerset t ↔ s ≀ t := quotient.induction_onβ‚‚ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset Ξ±) : s.map singleton ≀ powerset s := quotient.induction_on s $ Ξ» l, begin simp only [powerset_coe, quot_mk_to_coe, coe_le, coe_map], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset Ξ±) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list Ξ±} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, lβ‚‚, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list Ξ±} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, lβ‚‚, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq Ξ±] (l : list Ξ±) {l' : list (multiset Ξ±)} (H : βˆ€ ⦃x : _ Γ— _⦄, x ∈ revzip l' β†’ x.1 + x.2 = ↑l) : revzip l' = l'.map (Ξ» x, (x, ↑l - x)) := begin have : forallβ‚‚ (Ξ» (p : multiset Ξ± Γ— multiset Ξ±) (s : multiset Ξ±), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forallβ‚‚_map_right_iff, apply forallβ‚‚_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forallβ‚‚_eq_eq_eq, forallβ‚‚_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list Ξ±} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq Ξ±, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : revzip (powerset_aux l₁) ~ revzip (powerset_aux lβ‚‚) := begin haveI := classical.dec_eq Ξ±, simp [Ξ» l:list Ξ±, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : β„•) (l : list Ξ±) : list (multiset Ξ±) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list Ξ±} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list Ξ±} {s} : s ∈ powerset_len_aux n l ↔ s ≀ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact Ξ» l₁, ⟨λ ⟨lβ‚‚, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, Ξ» ⟨⟨lβ‚‚, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list Ξ±) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : β„•) : powerset_len_aux (n+1) (@nil Ξ±) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : β„•) (a : Ξ±) (l : list Ξ±) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ lβ‚‚ : list Ξ±} (p : l₁ ~ lβ‚‚) : powerset_len_aux n l₁ ~ powerset_len_aux n lβ‚‚ := begin induction n with n IHn generalizing l₁ lβ‚‚, {simp}, induction p with a l₁ lβ‚‚ p IH a b l l₁ lβ‚‚ l₃ p₁ pβ‚‚ IH₁ IHβ‚‚, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IHβ‚‚ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : β„•) (s : multiset Ξ±) : multiset (multiset Ξ±) := quot.lift_on s (Ξ» l, (powerset_len_aux n l : multiset (multiset Ξ±))) (Ξ» l₁ lβ‚‚ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list Ξ±) : @powerset_len Ξ± n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list Ξ±) : @powerset_len Ξ± n l = ((sublists_len n l).map coe : list (multiset Ξ±)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset Ξ±) : powerset_len 0 s = {0} := quotient.induction_on s $ Ξ» l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : β„•) : @powerset_len Ξ± (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : β„•) (a : Ξ±) (s) : powerset_len (n + 1) (a ::β‚˜ s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ Ξ» l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : β„•} {s t : multiset Ξ±} : s ∈ powerset_len n t ↔ s ≀ t ∧ card s = n := quotient.induction_on t $ Ξ» l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : β„•) (s : multiset Ξ±) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : β„•) (s : multiset Ξ±) : powerset_len n s ≀ powerset s := quotient.induction_on s $ Ξ» l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : β„•) {s t : multiset Ξ±} (h : s ≀ t) : powerset_len n s ≀ powerset_len n t := le_induction_on h $ Ξ» l₁ lβ‚‚ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm end multiset
61ce329f1ec0d11351d6e5a4b72de2215a927379
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/zmod/defs.lean
a8a6a3732836cd7fd2af36d7079b93f530dc6a3b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,760
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import algebra.ne_zero import data.nat.modeq import data.fintype.lattice /-! # Definition of `zmod n` + basic results. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides the basic details of `zmod n`, including its commutative ring structure. ## Implementation details This used to be inlined into data/zmod/basic.lean. This file imports `char_p/basic`, which is an issue; all `char_p` instances create an `algebra (zmod p) R` instance; however, this instance may not be definitionally equal to other `algebra` instances (for example, `galois_field` also has an `algebra` instance as it is defined as a `splitting_field`). The way to fix this is to use the forgetful inheritance pattern, and make `char_p` carry the data of what the `smul` should be (so for example, the `smul` on the `galois_field` `char_p` instance should be equal to the `smul` from its `splitting_field` structure); there is only one possible `zmod p` algebra for any `p`, so this is not an issue mathematically. For this to be possible, however, we need `char_p/basic` to be able to import some part of `zmod`. -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat.modeq int /-- Multiplicative commutative semigroup structure on `fin n`. -/ instance (n : β„•) : comm_semigroup (fin n) := { mul_assoc := Ξ» ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % n * c) ≑ a * b * c [MOD n] : (nat.mod_modeq _ _).mul_right _ ... ≑ a * (b * c) [MOD n] : by rw mul_assoc ... ≑ a * (b * c % n) [MOD n] : (nat.mod_modeq _ _).symm.mul_left _), mul_comm := fin.mul_comm, ..fin.has_mul } private lemma left_distrib_aux (n : β„•) : βˆ€ a b c : fin n, a * (b + c) = a * b + a * c := Ξ» ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % n) ≑ a * (b + c) [MOD n] : (nat.mod_modeq _ _).mul_left _ ... ≑ a * b + a * c [MOD n] : by rw mul_add ... ≑ (a * b) % n + (a * c) % n [MOD n] : (nat.mod_modeq _ _).symm.add (nat.mod_modeq _ _).symm) /-- Commutative ring structure on `fin n`. -/ instance (n : β„•) [ne_zero n] : comm_ring (fin n) := { one_mul := fin.one_mul, mul_one := fin.mul_one, left_distrib := left_distrib_aux n, right_distrib := Ξ» a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.add_monoid_with_one, ..fin.add_comm_group n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : β„•`. -/ def zmod : β„• β†’ Type | 0 := β„€ | (n+1) := fin (n+1) instance zmod.decidable_eq : Ξ  (n : β„•), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance zmod.has_repr : Ξ  (n : β„•), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ namespace zmod instance fintype : Ξ  (n : β„•) [ne_zero n], fintype (zmod n) | 0 h := by exactI (ne_zero.ne 0 rfl).elim | (n+1) _ := fin.fintype (n+1) instance infinite : infinite (zmod 0) := int.infinite @[simp] lemma card (n : β„•) [fintype (zmod n)] : fintype.card (zmod n) = n := begin casesI n, { exact (not_finite (zmod 0)).elim }, { convert fintype.card_fin (n+1) } end /- We define each field by cases, to ensure that the eta-expanded `zmod.comm_ring` is defeq to the original, this helps avoid diamonds with instances coming from classes extending `comm_ring` such as field. -/ instance comm_ring (n : β„•) : comm_ring (zmod n) := { add := nat.cases_on n ((@has_add.add) int _) (Ξ» n, @has_add.add (fin n.succ) _), add_assoc := nat.cases_on n (@add_assoc int _) (Ξ» n, @add_assoc (fin n.succ) _), zero := nat.cases_on n (0 : int) (Ξ» n, (0 : fin n.succ)), zero_add := nat.cases_on n (@zero_add int _) (Ξ» n, @zero_add (fin n.succ) _), add_zero := nat.cases_on n (@add_zero int _) (Ξ» n, @add_zero (fin n.succ) _), neg := nat.cases_on n ((@has_neg.neg) int _) (Ξ» n, @has_neg.neg (fin n.succ) _), sub := nat.cases_on n ((@has_sub.sub) int _) (Ξ» n, @has_sub.sub (fin n.succ) _), sub_eq_add_neg := nat.cases_on n (@sub_eq_add_neg int _) (Ξ» n, @sub_eq_add_neg (fin n.succ) _), zsmul := nat.cases_on n ((@comm_ring.zsmul) int _) (Ξ» n, @comm_ring.zsmul (fin n.succ) _), zsmul_zero' := nat.cases_on n (@comm_ring.zsmul_zero' int _) (Ξ» n, @comm_ring.zsmul_zero' (fin n.succ) _), zsmul_succ' := nat.cases_on n (@comm_ring.zsmul_succ' int _) (Ξ» n, @comm_ring.zsmul_succ' (fin n.succ) _), zsmul_neg' := nat.cases_on n (@comm_ring.zsmul_neg' int _) (Ξ» n, @comm_ring.zsmul_neg' (fin n.succ) _), nsmul := nat.cases_on n ((@comm_ring.nsmul) int _) (Ξ» n, @comm_ring.nsmul (fin n.succ) _), nsmul_zero' := nat.cases_on n (@comm_ring.nsmul_zero' int _) (Ξ» n, @comm_ring.nsmul_zero' (fin n.succ) _), nsmul_succ' := nat.cases_on n (@comm_ring.nsmul_succ' int _) (Ξ» n, @comm_ring.nsmul_succ' (fin n.succ) _), add_left_neg := by { cases n, exacts [@add_left_neg int _, @add_left_neg (fin n.succ) _] }, add_comm := nat.cases_on n (@add_comm int _) (Ξ» n, @add_comm (fin n.succ) _), mul := nat.cases_on n ((@has_mul.mul) int _) (Ξ» n, @has_mul.mul (fin n.succ) _), mul_assoc := nat.cases_on n (@mul_assoc int _) (Ξ» n, @mul_assoc (fin n.succ) _), one := nat.cases_on n (1 : int) (Ξ» n, (1 : fin n.succ)), one_mul := nat.cases_on n (@one_mul int _) (Ξ» n, @one_mul (fin n.succ) _), mul_one := nat.cases_on n (@mul_one int _) (Ξ» n, @mul_one (fin n.succ) _), nat_cast := nat.cases_on n (coe : β„• β†’ β„€) (Ξ» n, (coe : β„• β†’ fin n.succ)), nat_cast_zero := nat.cases_on n (@nat.cast_zero int _) (Ξ» n, @nat.cast_zero (fin n.succ) _), nat_cast_succ := nat.cases_on n (@nat.cast_succ int _) (Ξ» n, @nat.cast_succ (fin n.succ) _), int_cast := nat.cases_on n (coe : β„€ β†’ β„€) (Ξ» n, (coe : β„€ β†’ fin n.succ)), int_cast_of_nat := nat.cases_on n (@int.cast_of_nat int _) (Ξ» n, @int.cast_of_nat (fin n.succ) _), int_cast_neg_succ_of_nat := nat.cases_on n (@int.cast_neg_succ_of_nat int _) (Ξ» n, @int.cast_neg_succ_of_nat (fin n.succ) _), left_distrib := nat.cases_on n (@left_distrib int _ _ _) (Ξ» n, @left_distrib (fin n.succ) _ _ _), right_distrib := nat.cases_on n (@right_distrib int _ _ _) (Ξ» n, @right_distrib (fin n.succ) _ _ _), mul_comm := nat.cases_on n (@mul_comm int _) (Ξ» n, @mul_comm (fin n.succ) _) } instance inhabited (n : β„•) : inhabited (zmod n) := ⟨0⟩ end zmod
6922c707b4d1cdc41a40d350a4a527a2bd12dc02
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/group_theory/order_of_element.lean
e3d3ab575c4ec55c8e016645238b9d1643d7f39f
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,894
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Julian Kuelshammer -/ import algebra.pointwise import group_theory.coset import dynamics.periodic_pts import algebra.iterate_hom /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n β‰₯ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_find_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : β„•} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order lemma is_periodic_pt_add_iff_nsmul_eq_zero (a : A) : is_periodic_pt ((+) a) n 0 ↔ n β€’ a = 0 := by rw [is_periodic_pt, is_fixed_pt, add_left_iterate, add_zero] @[to_additive is_periodic_pt_add_iff_nsmul_eq_zero] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n β‰₯ 1` such that `n β€’ a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n β‰₯ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl lemma is_of_fin_add_order_iff_nsmul_eq_zero (a : A) : is_of_fin_add_order a ↔ βˆƒ n, 0 < n ∧ n β€’ a = 0 := by { convert iff.rfl, simp only [exists_prop, is_periodic_pt_add_iff_nsmul_eq_zero] } @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ βˆƒ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } end is_of_fin_order /-- `add_order_of a` is the order of the element `a`, i.e. the `n β‰₯ 1`, s.t. `n β€’ a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention.-/ noncomputable def add_order_of (a : A) : β„• := minimal_period ((+) a) 0 /-- `order_of x` is the order of the element `x`, i.e. the `n β‰₯ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of] noncomputable def order_of (x : G) : β„• := minimal_period ((*) x) 1 attribute [to_additive add_order_of] order_of @[to_additive] lemma commute.order_of_mul_dvd_lcm (h : commute x y) : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end lemma add_order_of_nsmul_eq_zero (a : A) : add_order_of a β€’ a = 0 := begin convert is_periodic_pt_minimal_period ((+) a) _, rw [add_order_of, add_left_iterate, add_zero], end attribute [to_additive add_order_of_nsmul_eq_zero] pow_order_of_eq_one @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : Β¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] lemma nsmul_ne_zero_of_lt_add_order_of' (n0 : n β‰  0) (h : n < add_order_of a) : n β€’ a β‰  0 := Ξ» j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_add_iff_nsmul_eq_zero a).mpr j) @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_eq_one_of_lt_order_of' (n0 : n β‰  0) (h : n < order_of x) : x ^ n β‰  1 := Ξ» j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) lemma add_order_of_le_of_nsmul_eq_zero (hn : 0 < n) (h : n β€’ a = 0) : add_order_of a ≀ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_add_iff_nsmul_eq_zero) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≀ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp] lemma add_order_of_zero : add_order_of (0 : A) = 1 := by simp only [←order_of_of_add_eq_add_order_of, order_of_one, of_add_zero] attribute [to_additive add_order_of_zero] order_of_one @[simp] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[simp] lemma add_order_of_eq_one_iff : add_order_of a = 1 ↔ a = 0 := by simp [← order_of_of_add_eq_add_order_of] attribute [to_additive add_order_of_eq_one_iff] order_of_eq_one_iff lemma pow_eq_mod_order_of {n : β„•} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma nsmul_eq_mod_add_order_of {n : β„•} : n β€’ a = (n % add_order_of a) β€’ a := begin apply multiplicative.of_add.injective, rw [← order_of_of_add_eq_add_order_of, of_add_nsmul, of_add_nsmul, pow_eq_mod_order_of], end attribute [to_additive nsmul_eq_mod_add_order_of] pow_eq_mod_order_of lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) lemma add_order_of_dvd_of_nsmul_eq_zero (h : n β€’ a = 0) : add_order_of a ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr h) attribute [to_additive add_order_of_dvd_of_nsmul_eq_zero] order_of_dvd_of_pow_eq_one lemma add_order_of_dvd_iff_nsmul_eq_zero {n : β„•} : add_order_of a ∣ n ↔ n β€’ a = 0 := ⟨λ h, by rw [nsmul_eq_mod_add_order_of, nat.mod_eq_zero_of_dvd h, zero_nsmul], add_order_of_dvd_of_nsmul_eq_zero⟩ @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : β„•} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : βˆƒ m : β„•, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end lemma exists_nsmul_eq_self_of_coprime (a : A) (h : coprime n (add_order_of a)) : βˆƒ m : β„•, m β€’ (n β€’ a) = a := begin change n.coprime (order_of (multiplicative.of_add a)) at h, exact exists_pow_eq_self_of_coprime h, end attribute [to_additive exists_nsmul_eq_self_of_coprime] exists_pow_eq_self_of_coprime lemma add_order_of_eq_add_order_of_iff {B : Type*} [add_monoid B] {b : B} : add_order_of a = add_order_of b ↔ βˆ€ n : β„•, n β€’ a = 0 ↔ n β€’ b = 0 := begin simp_rw ← add_order_of_dvd_iff_nsmul_eq_zero, exact ⟨λ h n, by rw h, Ξ» h, nat.dvd_antisymm ((h _).mpr (dvd_refl _)) ((h _).mp (dvd_refl _))⟩, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ βˆ€ n : β„•, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] lemma add_order_of_injective {B : Type*} [add_monoid B] (f : A β†’+ B) (hf : function.injective f) (a : A) : add_order_of (f a) = add_order_of a := by simp_rw [add_order_of_eq_add_order_of_iff, ←f.map_nsmul, ←f.map_zero, hf.eq_iff, iff_self, forall_const] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G β†’* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y variables (x) lemma order_of_pow' (h : n β‰  0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) lemma add_order_of_nsmul' (h : n β‰  0) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := by simpa [← order_of_of_add_eq_add_order_of, of_add_nsmul] using order_of_pow' _ h attribute [to_additive add_order_of_nsmul'] order_of_pow' variable (n) lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end lemma add_order_of_nsmul'' (h : is_of_fin_add_order a) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := by simp [← order_of_of_add_eq_add_order_of, of_add_nsmul, order_of_pow'' _ n (is_of_fin_order_of_add_iff.mpr h)] attribute [to_additive add_order_of_nsmul''] order_of_pow'' section p_prime variables {a x n} {p : β„•} [hp : fact p.prime] include hp lemma add_order_of_eq_prime (hg : p β€’ a = 0) (hg1 : a β‰  0) : add_order_of a = p := minimal_period_eq_prime ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr hg) (by rwa [is_fixed_pt, add_zero]) @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x β‰  1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) lemma add_order_of_eq_prime_pow (hnot : Β¬ (p ^ n) β€’ a = 0) (hfin : (p ^ (n + 1)) β€’ a = 0) : add_order_of a = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_add_iff_nsmul_eq_zero, end @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : Β¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end omit hp -- An example on how to determine the order of an element of a finite group. example : order_of (-1 : units β„€) = 2 := begin haveI : fact (prime 2) := ⟨prime_two⟩, exact order_of_eq_prime (int.units_mul_self _) dec_trivial, end end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x) variables [add_left_cancel_monoid A] (a) lemma pow_injective_aux (h : n ≀ m) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := by_contradiction $ assume ne : n β‰  m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have hβ‚‚ : m = n + (m - n) := (nat.add_sub_of_le h).symm, have h₃ : x ^ (m - n) = 1, by { rw [hβ‚‚, pow_add] at eq, apply mul_left_cancel, convert eq.symm, exact mul_one (x ^ n) }, have le : order_of x ≀ m - n, from order_of_le_of_pow_eq_one h₁ h₃, have lt : m - n < order_of x, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (le.trans_lt lt) -- TODO: This lemma was originally private, but this doesn't seem to work with `to_additive`, -- therefore the private got removed. lemma nsmul_injective_aux {n m : β„•} (h : n ≀ m) (hm : m < add_order_of a) (eq : n β€’ a = m β€’ a) : n = m := begin apply_fun multiplicative.of_add at eq, rw [of_add_nsmul, of_add_nsmul] at eq, rw ← order_of_of_add_eq_add_order_of at hm, exact pow_injective_aux (multiplicative.of_add a) h hm eq, end attribute [to_additive nsmul_injective_aux] pow_injective_aux lemma nsmul_injective_of_lt_add_order_of {n m : β„•} (hn : n < add_order_of a) (hm : m < add_order_of a) (eq : n β€’ a = m β€’ a) : n = m := (le_total n m).elim (assume h, nsmul_injective_aux a h hm eq) (assume h, (nsmul_injective_aux a h hn eq.symm).symm) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux x h hm eq) (assume h, (pow_injective_aux x h hn eq.symm).symm) end cancel_monoid section group variables [group G] [add_group A] {x a} {i : β„€} @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y lemma gpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma gsmul_eq_mod_add_order_of : i β€’ a = (i % add_order_of a) β€’ a := begin apply multiplicative.of_add.injective, simp [of_add_gsmul, gpow_eq_mod_order_of], end attribute [to_additive gsmul_eq_mod_add_order_of] gpow_eq_mod_order_of @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ Β¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : β„•} : x ^ n = x ^ m ↔ n = m := begin by_cases hx : x = 1, { rw [←order_of_eq_one_iff, h] at hx, contradiction }, rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end lemma pow_inj_mod {n m : β„•} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), Ξ» h, congr_arg _ h⟩ end lemma nsmul_inj_mod {n m : β„•} : n β€’ a = m β€’ a ↔ n % add_order_of a = m % add_order_of a := begin cases (add_order_of a).zero_le.eq_or_lt with hx hx, { simp [nsmul_inj_iff_of_add_order_of_eq_zero, hx.symm] }, rw [nsmul_eq_mod_add_order_of, @nsmul_eq_mod_add_order_of _ _ _ m], refine ⟨nsmul_injective_of_lt_add_order_of a (nat.mod_lt n hx) (nat.mod_lt m hx), Ξ» h, _⟩, rw h end attribute [to_additive nsmul_inj_mod] pow_inj_mod end group section fintype variables [fintype G] [fintype A] section finite_monoid variables [monoid G] [add_monoid A] open_locale big_operators lemma sum_card_add_order_of_eq_card_nsmul_eq_zero [decidable_eq A] (hn : 0 < n) : βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» a : A, add_order_of a = m)).card = (finset.univ.filter (Ξ» a : A, n β€’ a = 0)).card := calc βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» a : A, add_order_of a = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume a, suffices : add_order_of a ≀ n ∧ add_order_of a ∣ n ↔ n β€’ a = 0, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, mul_comm, mul_nsmul, add_order_of_nsmul_eq_zero, nsmul_zero], Ξ» h, ⟨add_order_of_le_of_nsmul_eq_zero hn h, add_order_of_dvd_of_nsmul_eq_zero h⟩⟩ end)) @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [decidable_eq G] (hn : 0 < n) : βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» x : G, order_of x = m)).card = (finset.univ.filter (Ξ» x : G, x ^ n = 1)).card := calc βˆ‘ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (Ξ» x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≀ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], Ξ» h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. lemma exists_pow_eq_one (x : G) : is_of_fin_order x := begin refine (is_of_fin_order_iff_pow_eq_one _).mpr _, obtain ⟨i, j, a_eq, ne⟩ : βˆƒ(i j : β„•), x ^ i = x ^ j ∧ i β‰  j := by simpa only [not_forall, exists_prop] using (not_injective_infinite_fintype (Ξ»i:β„•, x^i)), wlog h'' : j ≀ i, refine ⟨i - j, nat.sub_pos_of_lt (lt_of_le_of_ne h'' ne.symm), mul_right_injective (x^j) _⟩, rw [mul_one, ← pow_add, ← a_eq, nat.add_sub_cancel' h''], end lemma exists_nsmul_eq_zero (a : A) : is_of_fin_add_order a := begin rcases exists_pow_eq_one (multiplicative.of_add a) with ⟨i, hi1, hi2⟩, refine ⟨i, hi1, multiplicative.of_add.injective _⟩, rw [add_left_iterate, of_add_zero, of_add_eq_one, add_zero], exact (is_periodic_pt_mul_iff_pow_eq_one (multiplicative.of_add a)).mp hi2, end attribute [to_additive exists_nsmul_eq_zero] exists_pow_eq_one lemma add_order_of_le_card_univ : add_order_of a ≀ fintype.card A := finset.le_card_of_inj_on_range (β€’ a) (assume n _, finset.mem_univ _) (assume i hi j hj, nsmul_injective_of_lt_add_order_of a hi hj) @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ : order_of x ≀ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid.-/ lemma add_order_of_pos (a : A) : 0 < add_order_of a := add_order_of_pos' (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos] lemma order_of_pos (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid. -/ lemma add_order_of_nsmul (a : A) : add_order_of (n β€’ a) = add_order_of a / gcd (add_order_of a) n := add_order_of_nsmul'' _ _ (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul] lemma order_of_pow (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) lemma mem_multiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_submonoid.multiples a ↔ b ∈ (finset.range (add_order_of a)).image ((β€’ a) : β„• β†’ A) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (add_order_of_pos a) (assume i, nsmul_eq_mod_add_order_of.symm) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : β„• β†’ G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) noncomputable instance decidable_multiples [decidable_eq A] : decidable_pred (∈ add_submonoid.multiples a) := begin assume b, apply decidable_of_iff' (b ∈ (finset.range (add_order_of a)).image (β€’ a)), exact mem_multiples_iff_mem_range_add_order_of, end @[to_additive decidable_multiples] noncomputable instance decidable_powers [decidable_eq G] : decidable_pred (∈ submonoid.powers x) := begin assume y, apply decidable_of_iff' (y ∈ (finset.range (order_of x)).image ((^) x)), exact mem_powers_iff_mem_range_order_of end /-- The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_powers (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (Ξ» n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, subtype.mk_eq_mk.2 (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), Ξ» ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ /-- The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i β€’ a`."-/ noncomputable def fin_equiv_multiples (a : A) : fin (add_order_of a) ≃ (add_submonoid.multiples a : set A) := fin_equiv_powers (multiplicative.of_add a) attribute [to_additive fin_equiv_multiples] fin_equiv_powers @[simp] lemma fin_equiv_powers_apply {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp] lemma fin_equiv_multiples_apply {a : A} {n : fin (add_order_of a)} : fin_equiv_multiples a n = ⟨nsmul ↑n a, n, rfl⟩ := rfl attribute [to_additive fin_equiv_multiples_apply] fin_equiv_powers_apply @[simp] lemma fin_equiv_powers_symm_apply (x : G) (n : β„•) {hn : βˆƒ (m : β„•), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] @[simp] lemma fin_equiv_multiples_symm_apply (a : A) (n : β„•) {hn : βˆƒ (m : β„•), m β€’ a = n β€’ a} : ((fin_equiv_multiples a).symm ⟨n β€’ a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_powers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_multiples_symm_apply] fin_equiv_powers_symm_apply /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def powers_equiv_powers (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) /-- The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i β€’ a` to `i β€’ b`. -/ noncomputable def multiples_equiv_multiples (h : add_order_of a = add_order_of b) : (add_submonoid.multiples a : set A) ≃ (add_submonoid.multiples b : set A) := (fin_equiv_multiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_multiples b)) attribute [to_additive multiples_equiv_multiples] powers_equiv_powers @[simp] lemma powers_equiv_powers_apply (h : order_of x = order_of y) (n : β„•) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[simp] lemma multiples_equiv_multiples_apply (h : add_order_of a = add_order_of b) (n : β„•) : multiples_equiv_multiples h ⟨n β€’ a, n, rfl⟩ = ⟨n β€’ b, n, rfl⟩ := powers_equiv_powers_apply h n attribute [to_additive multiples_equiv_multiples_apply] powers_equiv_powers_apply lemma order_eq_card_powers [decidable_eq G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) lemma add_order_of_eq_card_multiples [decidable_eq A] : add_order_of a = fintype.card (add_submonoid.multiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_multiples a⟩) attribute [to_additive add_order_of_eq_card_multiples] order_eq_card_powers end finite_cancel_monoid section finite_group variables [group G] [add_group A] lemma exists_gpow_eq_one (x : G) : βˆƒ (i : β„€) (H : i β‰  0), x ^ (i : β„€) = 1 := --lemma exists_gpow_eq_one (a : Ξ±) : βˆƒ (i : β„€) (H : i β‰  0), a ^ (i : β„€) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw gpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end lemma exists_gsmul_eq_zero (a : A) : βˆƒ (i : β„€) (H : i β‰  0), i β€’ a = 0 := @exists_gpow_eq_one (multiplicative A) _ _ a attribute [to_additive] exists_gpow_eq_one lemma mem_multiples_iff_mem_gmultiples : b ∈ add_submonoid.multiples a ↔ b ∈ add_subgroup.gmultiples a := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, Ξ» ⟨i, hi⟩, ⟨(i % add_order_of a).nat_abs, by { simp only [nsmul_eq_smul] at hi ⊒, rwa [← gsmul_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (add_order_of_pos a))), ← gsmul_eq_mod_add_order_of] } ⟩⟩ open subgroup @[to_additive mem_multiples_iff_mem_gmultiples] lemma mem_powers_iff_mem_gpowers : y ∈ submonoid.powers x ↔ y ∈ gpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, Ξ» ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← gpow_eq_mod_order_of]⟩⟩ lemma multiples_eq_gmultiples (a : A) : (add_submonoid.multiples a : set A) = add_subgroup.gmultiples a := set.ext $ Ξ» y, mem_multiples_iff_mem_gmultiples @[to_additive multiples_eq_gmultiples] lemma powers_eq_gpowers (x : G) : (submonoid.powers x : set G) = gpowers x := set.ext $ Ξ» x, mem_powers_iff_mem_gpowers lemma mem_gmultiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_subgroup.gmultiples a ↔ b ∈ (finset.range (add_order_of a)).image (β€’ a) := by rw [← mem_multiples_iff_mem_gmultiples, mem_multiples_iff_mem_range_add_order_of] @[to_additive mem_gmultiples_iff_mem_range_add_order_of] lemma mem_gpowers_iff_mem_range_order_of [decidable_eq G] : y ∈ subgroup.gpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : β„• β†’ G) := by rw [← mem_powers_iff_mem_gpowers, mem_powers_iff_mem_range_order_of] noncomputable instance decidable_gmultiples [decidable_eq A] : decidable_pred (∈ add_subgroup.gmultiples a) := begin simp_rw ←set_like.mem_coe, rw ← multiples_eq_gmultiples, exact decidable_multiples, end @[to_additive decidable_gmultiples] noncomputable instance decidable_gpowers [decidable_eq G] : decidable_pred (∈ subgroup.gpowers x) := begin simp_rw ←set_like.mem_coe, rw ← powers_eq_gpowers, exact decidable_powers, end /-- The equivalence between `fin (order_of x)` and `subgroup.gpowers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_gpowers (x : G) : fin (order_of x) ≃ (subgroup.gpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_gpowers x)) /-- The equivalence between `fin (add_order_of a)` and `subgroup.gmultiples a`, sending `i` to `i β€’ a`. -/ noncomputable def fin_equiv_gmultiples (a : A) : fin (add_order_of a) ≃ (add_subgroup.gmultiples a : set A) := fin_equiv_gpowers (multiplicative.of_add a) attribute [to_additive fin_equiv_gmultiples] fin_equiv_gpowers @[simp] lemma fin_equiv_gpowers_apply {n : fin (order_of x)} : fin_equiv_gpowers x n = ⟨x ^ (n : β„•), n, gpow_coe_nat x n⟩ := rfl @[simp] lemma fin_equiv_gmultiples_apply {n : fin (add_order_of a)} : fin_equiv_gmultiples a n = ⟨(n : β„•) β€’ a, n, gsmul_coe_nat a n⟩ := fin_equiv_gpowers_apply attribute [to_additive fin_equiv_gmultiples_apply] fin_equiv_gpowers_apply @[simp] lemma fin_equiv_gpowers_symm_apply (x : G) (n : β„•) {hn : βˆƒ (m : β„€), x ^ m = x ^ n} : ((fin_equiv_gpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_gpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } @[simp] lemma fin_equiv_gmultiples_symm_apply (a : A) (n : β„•) {hn : βˆƒ (m : β„€), m β€’ a = n β€’ a} : ((fin_equiv_gmultiples a).symm ⟨n β€’ a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_gpowers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_gmultiples_symm_apply] fin_equiv_gpowers_symm_apply /-- The equivalence between `subgroup.gpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def gpowers_equiv_gpowers (h : order_of x = order_of y) : (subgroup.gpowers x : set G) ≃ (subgroup.gpowers y : set G) := (fin_equiv_gpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gpowers y)) /-- The equivalence between `subgroup.gmultiples` of two elements `a, b` of the same additive order, mapping `i β€’ a` to `i β€’ b`. -/ noncomputable def gmultiples_equiv_gmultiples (h : add_order_of a = add_order_of b) : (add_subgroup.gmultiples a : set A) ≃ (add_subgroup.gmultiples b : set A) := (fin_equiv_gmultiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gmultiples b)) attribute [to_additive gmultiples_equiv_gmultiples] gpowers_equiv_gpowers @[simp] lemma gpowers_equiv_gpowers_apply (h : order_of x = order_of y) (n : β„•) : gpowers_equiv_gpowers h ⟨x ^ n, n, gpow_coe_nat x n⟩ = ⟨y ^ n, n, gpow_coe_nat y n⟩ := begin rw [gpowers_equiv_gpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_gpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_gpowers_symm_apply], simp [h] end @[simp] lemma gmultiples_equiv_gmultiples_apply (h : add_order_of a = add_order_of b) (n : β„•) : gmultiples_equiv_gmultiples h ⟨n β€’ a, n, gsmul_coe_nat a n⟩ = ⟨n β€’ b, n, gsmul_coe_nat b n⟩ := gpowers_equiv_gpowers_apply h n attribute [to_additive gmultiples_equiv_gmultiples_apply] gpowers_equiv_gpowers_apply lemma order_eq_card_gpowers [decidable_eq G] : order_of x = fintype.card (subgroup.gpowers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gpowers x⟩) lemma add_order_eq_card_gmultiples [decidable_eq A] : add_order_of a = fintype.card (add_subgroup.gmultiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gmultiples a⟩) attribute [to_additive add_order_eq_card_gmultiples] order_eq_card_gpowers open quotient_group /- TODO: use cardinal theory, introduce `card : set G β†’ β„•`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype (quotient (gpowers x) Γ— (gpowers x)), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers x)), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (gpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eqβ‚‚ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (quotient (subgroup.gpowers x)) ft_cosets) (by rw [eq₁, eqβ‚‚, mul_comm]) end lemma add_order_of_dvd_card_univ : add_order_of a ∣ fintype.card A := begin rw ← order_of_of_add_eq_add_order_of, exact order_of_dvd_card_univ, end attribute [to_additive add_order_of_dvd_card_univ] order_of_dvd_card_univ @[simp] lemma pow_card_eq_one : x ^ fintype.card G = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ x _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] @[simp] lemma card_nsmul_eq_zero {a : A} : fintype.card A β€’ a = 0 := begin apply multiplicative.of_add.injective, rw [of_add_nsmul, of_add_zero], exact pow_card_eq_one, end @[to_additive nsmul_eq_mod_card] lemma pow_eq_mod_card (n : β„•) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma gpow_eq_mod_card (n : β„€) : x ^ n = x ^ (n % fintype.card G) := by by rw [gpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← gpow_eq_mod_order_of] attribute [to_additive card_nsmul_eq_zero] pow_card_eq_one /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[simps] def pow_coprime (h : nat.coprime (fintype.card G) n) : G ≃ G := { to_fun := Ξ» g, g ^ n, inv_fun := Ξ» g, g ^ (nat.gcd_b (fintype.card G) n), left_inv := Ξ» g, by { have key : g ^ _ = g ^ _ := congr_arg (Ξ» n : β„€, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul, gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key }, right_inv := Ξ» g, by { have key : g ^ _ = g ^ _ := congr_arg (Ξ» n : β„€, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul', gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key } } @[simp] lemma pow_coprime_one (h : nat.coprime (fintype.card G) n) : pow_coprime h 1 = 1 := one_pow n @[simp] lemma pow_coprime_inv (h : nat.coprime (fintype.card G) n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H βŠ“ K = βŠ₯ := begin refine (H βŠ“ K).eq_bot_iff_forall.mpr (Ξ» x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) lemma image_range_add_order_of [decidable_eq A] : finset.image (Ξ» i, i β€’ a) (finset.range (add_order_of a)) = (add_subgroup.gmultiples a : set A).to_finset := by {ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gmultiples_iff_mem_range_add_order_of] } /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of] lemma image_range_order_of [decidable_eq G] : finset.image (Ξ» i, x ^ i) (finset.range (order_of x)) = (gpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gpowers_iff_mem_range_order_of] } lemma gcd_nsmul_card_eq_zero_iff : n β€’ a = 0 ↔ (gcd n (fintype.card A)) β€’ a = 0 := ⟨λ h, gcd_nsmul_eq_zero _ h $ card_nsmul_eq_zero, Ξ» h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card A) in by rw [hm, mul_comm, mul_nsmul, h, nsmul_zero]⟩ /-- TODO: Generalise to `finite_cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, Ξ» h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group end fintype section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : βˆ€ a : M, a ∈ S β†’ βˆ€ n : β„•, a ^ (n + 1) ∈ S := Ξ» a ha, nat.rec (by rwa [zero_add, pow_one]) (Ξ» n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ←nat.sub_add_cancel (order_of_pos a)], exact pow_mem a ha (order_of a - 1) }, mul_mem' := Ξ» a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := Ξ» a ha, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact (submonoid_of_idempotent S hS1 hS2).pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical, refine (set.eq_of_subset_of_card_le (Ξ» b hb, (congr_arg (∈ _) (one_mul b)).mp (set.mul_mem_mul one_mem hb)) (ge_of_eq _)).symm, change _ = fintype.card (_ * _ : set G), rw [←pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup
90de9f5c448ed0d33577c332a66c6040350ab6bd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/nat/sub_elim.lean
5d0569eb711c7594ba5d81e66da82b779307d6c0
[ "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,684
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Subtraction elimination for linear natural number arithmetic. Works by repeatedly rewriting goals of the preform `P[t-s]` into `P[x] ∧ (t = s + x ∨ (t ≀ s ∧ x = 0))`, where `x` is fresh. -/ import tactic.omega.nat.form namespace omega namespace nat open_locale omega.nat namespace preterm /-- Find subtraction inside preterm and return its operands -/ def sub_terms : preterm β†’ option (preterm Γ— preterm) | (& i) := none | (i ** n) := none | (t +* s) := t.sub_terms <|> s.sub_terms | (t -* s) := t.sub_terms <|> s.sub_terms <|> some (t,s) /-- Find (t - s) inside a preterm and replace it with variable k -/ def sub_subst (t s : preterm) (k : nat) : preterm β†’ preterm | t@(& m) := t | t@(m ** n) := t | (x +* y) := x.sub_subst +* y.sub_subst | (x -* y) := if x = t ∧ y = s then (1 ** k) else x.sub_subst -* y.sub_subst lemma val_sub_subst {k : nat} {x y : preterm} {v : nat β†’ nat} : βˆ€ {t : preterm}, t.fresh_index ≀ k β†’ (sub_subst x y k t).val (update k (x.val v - y.val v) v) = t.val v | (& m) h1 := rfl | (m ** n) h1 := begin have h2 : n β‰  k := ne_of_lt h1, simp only [sub_subst, preterm.val], rw update_eq_of_ne _ h2, end | (t +* s) h1 := begin simp only [sub_subst, val_add], apply fun_mono_2; apply val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (t -* s) h1 := begin simp only [sub_subst, val_sub], by_cases h2 : t = x ∧ s = y, { rw if_pos h2, simp only [val_var, one_mul], rw [update_eq, h2.left, h2.right] }, { rw if_neg h2, simp only [val_sub, sub_subst], apply fun_mono_2; apply val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right, } end end preterm namespace preform /-- Find subtraction inside preform and return its operands -/ def sub_terms : preform β†’ option (preterm Γ— preterm) | (t =* s) := t.sub_terms <|> s.sub_terms | (t ≀* s) := t.sub_terms <|> s.sub_terms | (Β¬* p) := p.sub_terms | (p ∨* q) := p.sub_terms <|> q.sub_terms | (p ∧* q) := p.sub_terms <|> q.sub_terms /-- Find (t - s) inside a preform and replace it with variable k -/ @[simp] def sub_subst (x y : preterm) (k : nat) : preform β†’ preform | (t =* s) := preterm.sub_subst x y k t =* preterm.sub_subst x y k s | (t ≀* s) := preterm.sub_subst x y k t ≀* preterm.sub_subst x y k s | (Β¬* p) := Β¬* p.sub_subst | (p ∨* q) := p.sub_subst ∨* q.sub_subst | (p ∧* q) := p.sub_subst ∧* q.sub_subst end preform /-- Preform which asserts that the value of variable k is the truncated difference between preterms t and s -/ def is_diff (t s : preterm) (k : nat) : preform := ((t =* (s +* (1 ** k))) ∨* (t ≀* s ∧* ((1 ** k) =* &0))) lemma holds_is_diff {t s : preterm} {k : nat} {v : nat β†’ nat} : v k = t.val v - s.val v β†’ (is_diff t s k).holds v := begin intro h1, simp only [preform.holds, is_diff, if_pos (eq.refl 1), preterm.val_add, preterm.val_var, preterm.val_const], cases le_total (t.val v) (s.val v) with h2 h2, { right, refine ⟨h2, _⟩, rw [h1, one_mul, tsub_eq_zero_iff_le], exact h2 }, { left, rw [h1, one_mul, add_comm, tsub_add_cancel_of_le h2] } end /-- Helper function for sub_elim -/ def sub_elim_core (t s : preterm) (k : nat) (p : preform) : preform := (preform.sub_subst t s k p) ∧* (is_diff t s k) /-- Return de Brujin index of fresh variable that does not occur in any of the arguments -/ def sub_fresh_index (t s : preterm) (p : preform) : nat := max p.fresh_index (max t.fresh_index s.fresh_index) /-- Return a new preform with all subtractions eliminated -/ def sub_elim (t s : preterm) (p : preform) : preform := sub_elim_core t s (sub_fresh_index t s p) p lemma sub_subst_equiv {k : nat} {x y : preterm} {v : nat β†’ nat} : βˆ€ p : preform, p.fresh_index ≀ k β†’ ((preform.sub_subst x y k p).holds (update k (x.val v - y.val v) v) ↔ (p.holds v)) | (t =* s) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply preterm.val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (t ≀* s) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply preterm.val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (Β¬* p) h1 := by { apply not_iff_not_of_iff, apply sub_subst_equiv p h1 } | (p ∨* q) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply propext; apply sub_subst_equiv _ (le_trans _ h1), apply le_max_left, apply le_max_right end | (p ∧* q) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply propext; apply sub_subst_equiv _ (le_trans _ h1), apply le_max_left, apply le_max_right end lemma sat_sub_elim {t s : preterm} {p : preform} : p.sat β†’ (sub_elim t s p).sat := begin intro h1, simp only [sub_elim, sub_elim_core], cases h1 with v h1, refine ⟨update (sub_fresh_index t s p) (t.val v - s.val v) v, _⟩, constructor, { apply (sub_subst_equiv p _).elim_right h1, apply le_max_left }, { apply holds_is_diff, rw update_eq, apply fun_mono_2; apply preterm.val_constant; intros x h2; rw update_eq_of_ne _ (ne.symm (ne_of_gt _)); apply lt_of_lt_of_le h2; apply le_trans _ (le_max_right _ _), apply le_max_left, apply le_max_right } end lemma unsat_of_unsat_sub_elim (t s : preterm) (p : preform) : (sub_elim t s p).unsat β†’ p.unsat := mt sat_sub_elim end nat end omega
b5532a5d9bfc6907bd7544ca7060828a81bb65d2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/category/CommRing/adjunctions.lean
d05c6c0c6064513a2612609a8f3fdbd86ae8f07f
[ "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
1,541
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes HΓΆlzl -/ import algebra.category.CommRing.basic import data.mv_polynomial /-! Multivariable polynomials on a type is the left adjoint of the forgetful functor from commutative rings to types. -/ noncomputable theory universe u open mv_polynomial open category_theory namespace CommRing open_locale classical /-- The free functor `Type u β₯€ CommRing` sending a type `X` to the multivariable (commutative) polynomials with variables `x : X`. -/ def free : Type u β₯€ CommRing := { obj := Ξ» Ξ±, of (mv_polynomial Ξ± β„€), map := Ξ» X Y f, (↑(rename f : _ →ₐ[β„€] _) : (mv_polynomial X β„€ β†’+* mv_polynomial Y β„€)), -- TODO these next two fields can be done by `tidy`, but the calls in `dsimp` and `simp` it -- generates are too slow. map_id' := Ξ» X, ring_hom.ext $ rename_id, map_comp' := Ξ» X Y Z f g, ring_hom.ext $ Ξ» p, (rename_rename f g p).symm } @[simp] lemma free_obj_coe {Ξ± : Type u} : (free.obj Ξ± : Type u) = mv_polynomial Ξ± β„€ := rfl @[simp] lemma free_map_coe {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} : ⇑(free.map f) = rename f := rfl /-- The free-forgetful adjunction for commutative rings. -/ def adj : free ⊣ forget CommRing := adjunction.mk_of_hom_equiv { hom_equiv := Ξ» X R, hom_equiv, hom_equiv_naturality_left_symm' := Ξ» _ _ Y f g, ring_hom.ext $ Ξ» x, evalβ‚‚_cast_comp f (int.cast_ring_hom Y) g x } end CommRing
d21d9b915d28ea731872597ecc3b70a68dec3b07
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/disjointed.lean
9b60b8f70bdea892271786aa3b2ec74b475f1dcc
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,082
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, YaΓ«l Dillies -/ import order.partial_sups /-! # Consecutive differences of sets This file defines the way to make a sequence of elements into a sequence of disjoint elements with the same partial sups. For a sequence `f : β„• β†’ Ξ±`, this new sequence will be `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 βŠ” f 1)`. It is actually unique, as `disjointed_unique` shows. ## Main declarations * `disjointed f`: The sequence `f 0`, `f 1 \ f 0`, `f 2 \ (f 0 βŠ” f 1)`, .... * `partial_sups_disjointed`: `disjointed f` has the same partial sups as `f`. * `disjoint_disjointed`: The elements of `disjointed f` are pairwise disjoint. * `disjointed_unique`: `disjointed f` is the only pairwise disjoint sequence having the same partial sups as `f`. * `supr_disjointed`: `disjointed f` has the same supremum as `f`. Limiting case of `partial_sups_disjointed`. We also provide set notation variants of some lemmas. ## TODO Find a useful statement of `disjointed_rec_succ`. One could generalize `disjointed` to any locally finite bot preorder domain, in place of `β„•`. Related to the TODO in the module docstring of `order.partial_sups`. -/ variables {Ξ± Ξ² : Type*} section generalized_boolean_algebra variables [generalized_boolean_algebra Ξ±] /-- If `f : β„• β†’ Ξ±` is a sequence of elements, then `disjointed f` is the sequence formed by subtracting each element from the nexts. This is the unique disjoint sequence whose partial sups are the same as the original sequence. -/ def disjointed (f : β„• β†’ Ξ±) : β„• β†’ Ξ± | 0 := f 0 | (n + 1) := f (n + 1) \ (partial_sups f n) @[simp] lemma disjointed_zero (f : β„• β†’ Ξ±) : disjointed f 0 = f 0 := rfl lemma disjointed_succ (f : β„• β†’ Ξ±) (n : β„•) : disjointed f (n + 1) = f (n + 1) \ (partial_sups f n) := rfl lemma disjointed_le_id : disjointed ≀ (id : (β„• β†’ Ξ±) β†’ β„• β†’ Ξ±) := begin rintro f n, cases n, { refl }, { exact sdiff_le } end lemma disjointed_le (f : β„• β†’ Ξ±) : disjointed f ≀ f := disjointed_le_id f lemma disjoint_disjointed (f : β„• β†’ Ξ±) : pairwise (disjoint on disjointed f) := begin refine (symmetric.pairwise_on disjoint.symm _).2 (Ξ» m n h, _), cases n, { exact (nat.not_lt_zero _ h).elim }, exact disjoint_sdiff_self_right.mono_left ((disjointed_le f m).trans (le_partial_sups_of_le f (nat.lt_add_one_iff.1 h))), end /-- An induction principle for `disjointed`. To define/prove something on `disjointed f n`, it's enough to define/prove it for `f n` and being able to extend through diffs. -/ def disjointed_rec {f : β„• β†’ Ξ±} {p : Ξ± β†’ Sort*} (hdiff : βˆ€ ⦃t i⦄, p t β†’ p (t \ f i)) : βˆ€ ⦃n⦄, p (f n) β†’ p (disjointed f n) | 0 := id | (n + 1) := Ξ» h, begin suffices H : βˆ€ k, p (f (n + 1) \ partial_sups f k), { exact H n }, rintro k, induction k with k ih, { exact hdiff h }, rw [partial_sups_succ, ←sdiff_sdiff_left], exact hdiff ih, end @[simp] lemma disjointed_rec_zero {f : β„• β†’ Ξ±} {p : Ξ± β†’ Sort*} (hdiff : βˆ€ ⦃t i⦄, p t β†’ p (t \ f i)) (hβ‚€ : p (f 0)) : disjointed_rec hdiff hβ‚€ = hβ‚€ := rfl -- TODO: Find a useful statement of `disjointed_rec_succ`. lemma monotone.disjointed_eq {f : β„• β†’ Ξ±} (hf : monotone f) (n : β„•) : disjointed f (n + 1) = f (n + 1) \ f n := by rw [disjointed_succ, hf.partial_sups_eq] @[simp] lemma partial_sups_disjointed (f : β„• β†’ Ξ±) : partial_sups (disjointed f) = partial_sups f := begin ext n, induction n with k ih, { rw [partial_sups_zero, partial_sups_zero, disjointed_zero] }, { rw [partial_sups_succ, partial_sups_succ, disjointed_succ, ih, sup_sdiff_self_right] } end /-- `disjointed f` is the unique sequence that is pairwise disjoint and has the same partial sups as `f`. -/ lemma disjointed_unique {f d : β„• β†’ Ξ±} (hdisj : pairwise (disjoint on d)) (hsups : partial_sups d = partial_sups f) : d = disjointed f := begin ext n, cases n, { rw [←partial_sups_zero d, hsups, partial_sups_zero, disjointed_zero] }, suffices h : d n.succ = partial_sups d n.succ \ partial_sups d n, { rw [h, hsups, partial_sups_succ, disjointed_succ, sup_sdiff, sdiff_self, bot_sup_eq] }, rw [partial_sups_succ, sup_sdiff, sdiff_self, bot_sup_eq, eq_comm, sdiff_eq_self_iff_disjoint], suffices h : βˆ€ m ≀ n, disjoint (partial_sups d m) (d n.succ), { exact h n le_rfl }, rintro m hm, induction m with m ih, { exact hdisj (nat.succ_ne_zero _).symm }, rw [partial_sups_succ, disjoint_iff, inf_sup_right, sup_eq_bot_iff, ←disjoint_iff, ←disjoint_iff], exact ⟨ih (nat.le_of_succ_le hm), hdisj (nat.lt_succ_of_le hm).ne⟩, end end generalized_boolean_algebra section complete_boolean_algebra variables [complete_boolean_algebra Ξ±] lemma supr_disjointed (f : β„• β†’ Ξ±) : (⨆ n, disjointed f n) = (⨆ n, f n) := supr_eq_supr_of_partial_sups_eq_partial_sups (partial_sups_disjointed f) lemma disjointed_eq_inf_compl (f : β„• β†’ Ξ±) (n : β„•) : disjointed f n = f n βŠ“ (β¨… i < n, (f i)ᢜ) := begin cases n, { rw [disjointed_zero, eq_comm, inf_eq_left], simp_rw le_infi_iff, exact Ξ» i hi, (i.not_lt_zero hi).elim }, simp_rw [disjointed_succ, partial_sups_eq_bsupr, sdiff_eq, compl_supr], congr, ext i, rw nat.lt_succ_iff, end end complete_boolean_algebra /-! ### Set notation variants of lemmas -/ lemma disjointed_subset (f : β„• β†’ set Ξ±) (n : β„•) : disjointed f n βŠ† f n := disjointed_le f n lemma Union_disjointed {f : β„• β†’ set Ξ±} : (⋃ n, disjointed f n) = (⋃ n, f n) := supr_disjointed f lemma disjointed_eq_inter_compl (f : β„• β†’ set Ξ±) (n : β„•) : disjointed f n = f n ∩ (β‹‚ i < n, (f i)ᢜ) := disjointed_eq_inf_compl f n lemma preimage_find_eq_disjointed (s : β„• β†’ set Ξ±) (H : βˆ€ x, βˆƒ n, x ∈ s n) [βˆ€ x n, decidable (x ∈ s n)] (n : β„•) : (Ξ» x, nat.find (H x)) ⁻¹' {n} = disjointed s n := by { ext x, simp [nat.find_eq_iff, disjointed_eq_inter_compl] }
88362a168f5577d6ef7c4e4615a545bf96064cca
048b0801f6dafb6486ca4f22bd0957671c3002ff
/src/util/io.lean
5db20f91b9a36b4e2e1d0e7c49c93987f008af70
[ "Apache-2.0" ]
permissive
Scikud/lean-gym
e0782e36389ecfa1605a0c12dc95f67014a0fa05
a1ca851b7c09eca1f72be2d059e3ed5536348b0b
refs/heads/main
1,693,940,033,482
1,633,522,864,000
1,633,522,864,000
419,793,692
0
0
null
null
null
null
UTF-8
Lean
false
false
1,074
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Stanislas Polu Helper functions to work with the io monad. -/ import system.io import tactic.gptf.utils.util section io open interaction_monad interaction_monad.result namespace io /-- verion of io.run_tactic' which does not suppress the exception msg -/ meta def run_tactic'' {Ξ±} (tac :tactic Ξ±) : io Ξ± := do { io.run_tactic $ do { result ← tactic.capture tac, match result with | (success val _) := pure val | (exception m_fmt _ _) := do { let fmt_msg := (m_fmt.get_or_else (Ξ» _, format!"n/a")) (), let msg := format!"[fatal] {fmt_msg}", tactic.trace msg, tactic.fail msg } end } } end io end io -- convenience function for command-line argument parsing meta def list.nth_except {Ξ±} : list Ξ± β†’ β„• β†’ string β†’ io Ξ± := Ξ» xs pos msg, match (xs.nth pos) with | (some result) := pure result | none := do io.fail' format!"must supply {msg} as argument {pos}" end
e774d240b2a2e52c5c4a87589e1e1f712dab3c61
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data/Nat.lean
a2c806b9eabc45fbef346adec6b4f34ea61d3896
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
333
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.Nat.Basic import Init.Data.Nat.Div import Init.Data.Nat.Gcd import Init.Data.Nat.Bitwise import Init.Data.Nat.Control import Init.Data.Nat.Log2
33e5c83eb300007959a204279423a85122f17d08
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/order/order_iso_nat.lean
1c13726b3b700472fb89ab949a32ba8c38d55166
[ "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
6,011
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.nat.basic import data.equiv.denumerable import data.set.finite import order.rel_iso import logic.function.iterate namespace rel_embedding variables {Ξ± : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} [is_strict_order Ξ± r] /-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/ def nat_lt (f : β„• β†’ Ξ±) (H : βˆ€ n:β„•, r (f n) (f (n+1))) : ((<) : β„• β†’ β„• β†’ Prop) β†ͺr r := of_monotone f $ Ξ» a b h, begin induction b with b IH, {exact (nat.not_lt_zero _ h).elim}, cases nat.lt_succ_iff_lt_or_eq.1 h with h e, { exact trans (IH h) (H _) }, { subst b, apply H } end @[simp] lemma nat_lt_apply {f : β„• β†’ Ξ±} {H : βˆ€ n:β„•, r (f n) (f (n+1))} {n : β„•} : nat_lt f H n = f n := rfl /-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/ def nat_gt (f : β„• β†’ Ξ±) (H : βˆ€ n:β„•, r (f (n+1)) (f n)) : ((>) : β„• β†’ β„• β†’ Prop) β†ͺr r := by haveI := is_strict_order.swap r; exact rel_embedding.swap (nat_lt f H) theorem well_founded_iff_no_descending_seq : well_founded r ↔ Β¬ nonempty (((>) : β„• β†’ β„• β†’ Prop) β†ͺr r) := ⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩, suffices βˆ€ a, acc r a β†’ βˆ€ n, a β‰  f n, from this (f 0) (h _) 0 rfl, Ξ» a ac, begin induction ac with a _ IH, intros n h, subst a, exact IH (f (n+1)) (o.2 (nat.lt_succ_self _)) _ rfl end, Ξ» N, ⟨λ a, classical.by_contradiction $ Ξ» na, let ⟨f, h⟩ := classical.axiom_of_choice $ show βˆ€ x : {a // Β¬ acc r a}, βˆƒ y : {a // Β¬ acc r a}, r y.1 x.1, from Ξ» ⟨x, h⟩, classical.by_contradiction $ Ξ» hn, h $ ⟨_, Ξ» y h, classical.by_contradiction $ Ξ» na, hn ⟨⟨y, na⟩, h⟩⟩ in N ⟨nat_gt (Ξ» n, (f^[n] ⟨a, na⟩).1) $ Ξ» n, by { rw [function.iterate_succ'], apply h }⟩⟩⟩ end rel_embedding namespace nat variables (s : set β„•) [decidable_pred s] [infinite s] /-- An order embedding from `β„•` to itself with a specified range -/ def order_embedding_of_set : β„• β†ͺo β„• := (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (Ξ» n, nat.subtype.lt_succ_self _))).trans (order_embedding.subtype s) /-- `nat.subtype.of_nat` as an order isomorphism between `β„•` and an infinite decidable subset. -/ noncomputable def subtype.order_iso_of_nat : β„• ≃o s := rel_iso.of_surjective (rel_embedding.order_embedding_of_lt_embedding (rel_embedding.nat_lt (nat.subtype.of_nat s) (Ξ» n, nat.subtype.lt_succ_self _))) nat.subtype.of_nat_surjective variable {s} @[simp] lemma order_embedding_of_set_apply {n : β„•} : order_embedding_of_set s n = subtype.of_nat s n := rfl @[simp] lemma subtype.order_iso_of_nat_apply {n : β„•} : subtype.order_iso_of_nat s n = subtype.of_nat s n := by { simp [subtype.order_iso_of_nat] } variable (s) @[simp] lemma order_embedding_of_set_range : set.range (nat.order_embedding_of_set s) = s := begin ext x, rw [set.mem_range, nat.order_embedding_of_set], split; intro h, { rcases h with ⟨y, rfl⟩, simp }, { refine ⟨(nat.subtype.order_iso_of_nat s).symm ⟨x, h⟩, _⟩, simp only [rel_embedding.coe_trans, rel_embedding.order_embedding_of_lt_embedding_apply, rel_embedding.nat_lt_apply, function.comp_app, order_embedding.coe_subtype], rw [← subtype.order_iso_of_nat_apply, order_iso.apply_symm_apply, subtype.coe_mk] } end end nat theorem exists_increasing_or_nonincreasing_subseq' {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (f : β„• β†’ Ξ±) : βˆƒ (g : β„• β†ͺo β„•), (βˆ€ n : β„•, r (f (g n)) (f (g (n + 1)))) ∨ (βˆ€ m n : β„•, m < n β†’ Β¬ r (f (g m)) (f (g n))) := begin classical, let bad : set β„• := { m | βˆ€ n, m < n β†’ Β¬ r (f m) (f n) }, by_cases hbad : infinite bad, { haveI := hbad, refine ⟨nat.order_embedding_of_set bad, or.intro_right _ (Ξ» m n mn, _)⟩, have h := set.mem_range_self m, rw nat.order_embedding_of_set_range bad at h, exact h _ ((order_embedding.lt_iff_lt _).2 mn) }, { rw [set.infinite_coe_iff, set.infinite, not_not] at hbad, obtain ⟨m, hm⟩ : βˆƒ m, βˆ€ n, m ≀ n β†’ Β¬ n ∈ bad, { by_cases he : hbad.to_finset.nonempty, { refine ⟨(hbad.to_finset.max' he).succ, Ξ» n hn nbad, nat.not_succ_le_self _ (hn.trans (hbad.to_finset.le_max' n (set.finite.mem_to_finset.2 nbad)))⟩ }, { exact ⟨0, Ξ» n hn nbad, he ⟨n, set.finite.mem_to_finset.2 nbad⟩⟩ } }, have h : βˆ€ (n : β„•), βˆƒ (n' : β„•), n < n' ∧ r (f (n + m)) (f (n' + m)), { intro n, have h := hm _ (le_add_of_nonneg_left n.zero_le), simp only [exists_prop, not_not, set.mem_set_of_eq, not_forall] at h, obtain ⟨n', hn1, hn2⟩ := h, obtain ⟨x, hpos, rfl⟩ := exists_pos_add_of_lt hn1, refine ⟨n + x, add_lt_add_left hpos n, _⟩, rw [add_assoc, add_comm x m, ← add_assoc], exact hn2 }, let g' : β„• β†’ β„• := @nat.rec (Ξ» _, β„•) m (Ξ» n gn, nat.find (h gn)), exact ⟨(rel_embedding.nat_lt (Ξ» n, g' n + m) (Ξ» n, nat.add_lt_add_right (nat.find_spec (h (g' n))).1 m)).order_embedding_of_lt_embedding, or.intro_left _ (Ξ» n, (nat.find_spec (h (g' n))).2)⟩ } end theorem exists_increasing_or_nonincreasing_subseq {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) [is_trans Ξ± r] (f : β„• β†’ Ξ±) : βˆƒ (g : β„• β†ͺo β„•), (βˆ€ m n : β„•, m < n β†’ r (f (g m)) (f (g n))) ∨ (βˆ€ m n : β„•, m < n β†’ Β¬ r (f (g m)) (f (g n))) := begin obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f, { refine ⟨g, or.intro_left _ (Ξ» m n mn, _)⟩, obtain ⟨x, rfl⟩ := le_iff_exists_add.1 (nat.succ_le_iff.2 mn), induction x with x ih, { apply hr }, { apply is_trans.trans _ _ _ _ (hr _), exact ih (lt_of_lt_of_le m.lt_succ_self (nat.le_add_right _ _)) } }, { exact ⟨g, or.intro_right _ hnr⟩ } end
5b2f865da4afb87ab346d9bc097180477bc9b8dd
d8820d2c92be8052d13f9c8f8c483a6e15c5f566
/src/M40002/M40002_C4.lean
d4603ec3ba1acb08236564597019d65f7e04749c
[]
no_license
JasonKYi/M4000x_LEAN_formalisation
4a19b84f6d0fe2e214485b8532e21cd34996c4b1
6e99793f2fcbe88596e27644f430e46aa2a464df
refs/heads/master
1,599,755,414,708
1,589,494,604,000
1,589,494,604,000
221,759,483
8
1
null
1,589,494,605,000
1,573,755,201,000
Lean
UTF-8
Lean
false
false
12,923
lean
-- M40002 (Analysis I) Chapter 4. Series import M40002.M40002_C3 namespace M40002 -- Definition of convergent sums def partial_sum_to (a : β„• β†’ ℝ) (n : β„•) := finset.sum (finset.range n) a notation `βˆ‘` a := partial_sum_to a def sum_converges_to (a : β„• β†’ ℝ) (l : ℝ) := (partial_sum_to a) β‡’ l notation a ` βˆ‘β‡’ ` l := sum_converges_to a l /- Maybe use this notation instead def X (f : real ->Prop) (x : real) := f x notation `βˆ‘` binders `, ` r:(scoped P, sum_converges_to P) := r infixr ` ⇛ `: 50 := X -/ def sum_convergent (a : β„• β†’ ℝ) := βˆƒ l : ℝ, a βˆ‘β‡’ l notation ` βˆ‘β‡’ ` a := sum_convergent a -- s n - s (n - 1) = a n lemma successive_diff {a : β„• β†’ ℝ} {n : β„•} : (partial_sum_to a (n + 1)) - (partial_sum_to a n) = a n := by {unfold partial_sum_to, rw finset.sum_range_succ, simp } -- βˆ‘ a is convergent implies a β†’ 0 theorem test_trivial (a : β„• β†’ ℝ) : (βˆ‘β‡’ a) β†’ a β‡’ 0 := begin intros h Ξ΅ hΞ΅, cases h with l hl, have : cauchy (partial_sum_to a) := by {rwa cauchy_iff_conv, use l, from hl }, cases this Ξ΅ hΞ΅ with N hN, use N, intros n hn, rw sub_zero (a n), suffices hΞ± : abs (partial_sum_to a n - partial_sum_to a (n + 1)) < Ξ΅, {rwa [abs_sub, successive_diff] at hΞ±}, apply hN n (n + 1), have : N ≀ n + 1 := by {linarith}, from ⟨hn, this⟩ end lemma succ_sum_def {a : β„• β†’ ℝ} : βˆ€ k : β„•, (βˆ‘ a) (nat.succ k) = (βˆ‘ a) k + a k := by {intro k, unfold partial_sum_to, rw finset.sum_range_succ, from add_comm (a k) (finset.sum (finset.range k) a) } -- If a β‰₯ 0, then ↑ (βˆ‘ a) lemma sum_mono_increasing {a : β„• β†’ ℝ} (h : βˆ€ n : β„•, 0 ≀ a n) : (βˆ‘ a) ↑ := begin intro n, rw succ_sum_def n, have hΞ² : 0 ≀ a n := h n, linarith end -- If a β‰₯ 0, then βˆ‘ a is convergent if βˆ‘ a is bounded above theorem sum_bdd_abv_conv {a : β„• β†’ ℝ} (h : βˆ€ n : β„•, 0 ≀ a n) : (seq_bounded_above (βˆ‘ a)) β†’ (βˆ‘β‡’ a) := begin intro hΞ±, apply mono_increasing_means_conv (βˆ‘ a) _, split, {from hΞ±}, {use 0, intro m, induction m with k hk, {unfold partial_sum_to, simp}, {rw succ_sum_def k, from add_nonneg hk (h k) }, }, from sum_mono_increasing h end -- Comparison Test. If 0 ≀ a ≀ b, and if βˆ‘ b converges then so do βˆ‘ a theorem test_comparison {a b : β„• β†’ ℝ} : (βˆ€ n : β„•, 0 ≀ a n ∧ a n ≀ b n) ∧ (βˆ‘β‡’ b) β†’ βˆ‘β‡’ a := begin rintro ⟨hΞ±, ⟨l, hl⟩⟩, apply sum_bdd_abv_conv, {intro n, from (hΞ± n).left }, {rcases converge_is_bdd (βˆ‘ b) ⟨l, hl⟩ with ⟨⟨N, hN⟩, blw⟩, use N, intro n, have : (βˆ‘ a) n ≀ (βˆ‘ b) n := by {induction n with k hk, unfold partial_sum_to, simp, repeat {rw succ_sum_def}, have : a k ≀ b k := (hΞ± k).right, linarith }, from le_trans this (hN n) } end -- Algebra of limits for sums lemma sum_add_sum_split {a b : β„• β†’ ℝ} : (βˆ‘ a) + (βˆ‘ b) = (βˆ‘ a + b) := begin rw [seq_add_seq, function.funext_iff], intro n, unfold partial_sum_to, induction n with k hk, {simp}, {repeat {rw finset.sum_range_succ}, rw [←hk, seq_add_seq], simp } end theorem add_sum_lim_conv {a b : β„• β†’ ℝ} {l m : ℝ} (h₁ : a βˆ‘β‡’ l) (hβ‚‚ : b βˆ‘β‡’ m) : (a + b) βˆ‘β‡’ (l + m) := begin unfold sum_converges_to, rw ←sum_add_sum_split, apply add_lim_conv, from ⟨h₁, hβ‚‚βŸ© end lemma scalar_mul_sum_split {a : β„• β†’ ℝ} {m : ℝ} : ((βˆ‘ a) Γ— m) = βˆ‘ (a Γ— m) := begin rw function.funext_iff, intro n, rw seq_mul_real, unfold partial_sum_to, induction n with k hk, {simp}, {rw [finset.sum_range_succ, add_mul, hk], have : a k * m = (a Γ— m) k := rfl, rwa [this, ←finset.sum_range_succ] } end theorem scalar_sum_lim_conv {a : β„• β†’ ℝ} {l m : ℝ} (h₁ : a βˆ‘β‡’ l) : (a Γ— m) βˆ‘β‡’ l * m := begin unfold sum_converges_to, rw ←scalar_mul_sum_split, apply mul_lim_conv, from h₁, from cons_conv end -- Defining absolute convergence noncomputable def abs_seq (a : β„• β†’ ℝ) (n : β„•) := abs (a n) def abs_sum_converge (a : β„• β†’ ℝ) := βˆ‘β‡’ abs_seq a -- Absolutely convergen implies normal convergence lemma sum_diff {a : β„• β†’ ℝ} {n m : β„•} (h₁ : n < m) : (βˆ‘ a) m - (βˆ‘ a) n = finset.sum (finset.Ico n m) a := begin unfold partial_sum_to, induction m with k hk, {exfalso, from nat.not_succ_le_zero n h₁}, {rw [finset.sum_range_succ, finset.sum_Ico_succ_top], swap, from nat.lt_succ_iff.mp h₁, simp, cases nat.lt_succ_iff_lt_or_eq.mp h₁, {rw [←sub_eq_add_neg, hk h]}, {rw h, simp} } end lemma sum_le (a b : β„• β†’ ℝ) {n m : β„•} (h₁ : βˆ€ n : β„•, a n ≀ b n) : finset.sum (finset.Ico n m) a ≀ finset.sum (finset.Ico n m) b := begin induction m with k hk, {rw finset.Ico.eq_empty_iff.mpr (zero_le n), simp}, {cases le_or_lt n k, {repeat {rw finset.sum_Ico_succ_top h}, apply add_le_add hk _, from h₁ k }, {rw finset.Ico.eq_empty_iff.mpr (nat.succ_le_iff.mpr h), simp } } end lemma sum_pos {a : β„• β†’ ℝ} {n m : β„•} (h₁ : βˆ€ k : β„•, 0 ≀ a k) : 0 ≀ finset.sum (finset.Ico n m) a := begin induction m with k hk, {rw finset.Ico.eq_empty_iff.mpr (zero_le n), simp}, {cases le_or_lt n k, {rw finset.sum_Ico_succ_top h, from add_nonneg hk (h₁ k) }, {rw finset.Ico.eq_empty_iff.mpr (nat.succ_le_iff.mpr h), simp } } end lemma sum_triangle {a : β„• β†’ ℝ} {n m : β„•} : abs (finset.sum (finset.Ico n m) a) ≀ finset.sum (finset.Ico n m) (abs_seq a) := begin induction m with k hk, {rw finset.Ico.eq_empty_iff.mpr (zero_le n), simp}, {cases le_or_lt n k, {repeat {rw finset.sum_Ico_succ_top h}, apply le_trans (abs_add (finset.sum (finset.Ico n k) a) (a k)), show abs (finset.sum (finset.Ico n k) a) + abs (a k) ≀ finset.sum (finset.Ico n k) (abs_seq a) + abs (a k), suffices : abs (finset.sum (finset.Ico n k) a) ≀ finset.sum (finset.Ico n k) (abs_seq a), simpa, assumption }, {rw finset.Ico.eq_empty_iff.mpr (nat.succ_le_iff.mpr h), simp } } end lemma neg_sum {a : β„• β†’ ℝ} {n m : β„•} : - finset.sum (finset.Ico n m) a = finset.sum (finset.Ico n m) (a Γ— -1) := begin induction m with k hk, {rw finset.Ico.eq_empty_iff.mpr (zero_le n), simp}, {cases le_or_lt n k, {repeat {rw finset.sum_Ico_succ_top h}, unfold seq_mul_real, simp }, {rw finset.Ico.eq_empty_iff.mpr (nat.succ_le_iff.mpr h), simp } } end theorem abs_conv_to_conv {a : β„• β†’ ℝ} : abs_sum_converge a β†’ βˆ‘β‡’ a := begin intro h₁, suffices : cauchy (βˆ‘ a), cases cauchy_iff_conv.mp this with l hl, use l, from hl, have hcauchy : cauchy (βˆ‘ abs_seq a) := cauchy_iff_conv.mpr h₁, unfold cauchy at hcauchy, intros Ξ΅ hΞ΅, cases hcauchy Ξ΅ hΞ΅ with N hN, use N, intros n m hβ‚‚, replace hN : abs ((βˆ‘abs_seq a) n - (βˆ‘abs_seq a) m) < Ξ΅ := hN n m hβ‚‚, cases lt_trichotomy n m, swap, cases h, {rw h, simp, from hΞ΅}, {rw sum_diff h, rw sum_diff h at hN, apply lt_of_le_of_lt _ hN, rw abs_le, split, swap, {have : βˆ€ k : β„•, a k ≀ abs_seq a k := Ξ» k : β„•, by {from le_max_left (a k) (- a k)}, apply le_trans (sum_le a (abs_seq a) this), from le_max_left (finset.sum (finset.Ico m n) (abs_seq a)) (-finset.sum (finset.Ico m n) (abs_seq a)) }, {rw abs_of_nonneg, swap, {apply sum_pos, intro k, from abs_nonneg (a k)}, {rw neg_sum, apply sum_le, intro n, unfold seq_mul_real, simp, rw neg_le, from le_max_right (a n) (-a n) } } }, {rw [abs_sub, sum_diff h], rw [abs_sub, sum_diff h] at hN, apply lt_of_le_of_lt _ hN, rw abs_le, split, swap, {have : βˆ€ k : β„•, a k ≀ abs_seq a k := Ξ» k : β„•, by {from le_max_left (a k) (- a k)}, apply le_trans (sum_le a (abs_seq a) this), from le_max_left (finset.sum (finset.Ico n m) (abs_seq a)) (-finset.sum (finset.Ico n m) (abs_seq a)) }, {rw abs_of_nonneg, swap, {apply sum_pos, intro k, from abs_nonneg (a k)}, {rw neg_sum, apply sum_le, intro n, unfold seq_mul_real, simp, rw neg_le, from le_max_right (a n) (-a n) } } } end -- set_option trace.simplify.rewrite true -- Sandwich theorem for sums theorem test_sum_sandwich {a b c : β„• β†’ ℝ} {h₁ : βˆ€ n : β„•, c n ≀ a n ∧ a n ≀ b n} : (βˆ‘β‡’ c) ∧ (βˆ‘β‡’ b) β†’ βˆ‘β‡’ a := begin intro hβ‚‚, have hcauchyb : cauchy βˆ‘ b := conv_to_cauchy (βˆ‘ b) hβ‚‚.right, have hcauchyc : cauchy βˆ‘ c := conv_to_cauchy (βˆ‘ c) hβ‚‚.left, suffices : cauchy (βˆ‘ a), cases cauchy_iff_conv.mp this with l hl, use l, from hl, intros Ξ΅ hΞ΅, cases hcauchyb Ξ΅ hΞ΅ with N₁ hN₁, cases hcauchyc Ξ΅ hΞ΅ with Nβ‚‚ hNβ‚‚, let N : β„• := max N₁ Nβ‚‚, use N, intros n m hnm, cases lt_trichotomy n m, rw [abs_sub, abs_lt], split, -- These parts are essentially the same {have : Nβ‚‚ ≀ n ∧ Nβ‚‚ ≀ m := by {split, apply le_trans _ hnm.left, from le_max_right N₁ Nβ‚‚, apply le_trans _ hnm.right, from le_max_right N₁ Nβ‚‚ }, replace hβ‚‚ : -Ξ΅ < (βˆ‘c) m - (βˆ‘c) n := by {have hΞ± : abs ((βˆ‘c) n - (βˆ‘c) m) < Ξ΅ := hNβ‚‚ n m this, rw abs_sub at hΞ±, from (abs_lt.mp hΞ±).left }, apply lt_of_lt_of_le hβ‚‚, repeat {rw sum_diff}, apply sum_le, intro n, from (h₁ n).left, repeat {assumption} }, -- 1 {have : N₁ ≀ n ∧ N₁ ≀ m := by {split, apply le_trans _ hnm.left, from le_max_left N₁ Nβ‚‚, apply le_trans _ hnm.right, from le_max_left N₁ Nβ‚‚ }, replace hβ‚‚ : (βˆ‘b) m - (βˆ‘b) n < Ξ΅ := by {have hΞ± : abs ((βˆ‘b) n - (βˆ‘b) m) < Ξ΅ := hN₁ n m this, rw abs_sub at hΞ±, from (abs_lt.mp hΞ±).right }, apply lt_of_le_of_lt _ hβ‚‚, repeat {rw sum_diff}, apply sum_le, intro n, from (h₁ n).right, repeat {assumption} }, cases h, {rw h, simp, from hΞ΅}, {rw abs_lt, split, -- 2 {have : Nβ‚‚ ≀ n ∧ Nβ‚‚ ≀ m := by {split, apply le_trans _ hnm.left, from le_max_right N₁ Nβ‚‚, apply le_trans _ hnm.right, from le_max_right N₁ Nβ‚‚ }, replace hβ‚‚ : -Ξ΅ < (βˆ‘c) n - (βˆ‘c) m := by {have hΞ± : abs ((βˆ‘c) n - (βˆ‘c) m) < Ξ΅ := hNβ‚‚ n m this, from (abs_lt.mp hΞ±).left }, apply lt_of_lt_of_le hβ‚‚, repeat {rw sum_diff}, apply sum_le, intro n, from (h₁ n).left, repeat {assumption} }, -- 3 {have : N₁ ≀ n ∧ N₁ ≀ m := by {split, apply le_trans _ hnm.left, from le_max_left N₁ Nβ‚‚, apply le_trans _ hnm.right, from le_max_left N₁ Nβ‚‚ }, replace hβ‚‚ : (βˆ‘b) n - (βˆ‘b) m < Ξ΅ := by {have hΞ± : abs ((βˆ‘b) n - (βˆ‘b) m) < Ξ΅ := hN₁ n m this, from (abs_lt.mp hΞ±).right }, apply lt_of_le_of_lt _ hβ‚‚, repeat {rw sum_diff}, apply sum_le, intro n, from (h₁ n).right, repeat {assumption} } } end end M40002
de618cabb3ee0aa2f8eaffc42822f9532103aea3
648d81761ea888cc089e98077fce63a63e28e11f
/LeanErrorLocation.lean
dd69a96e832d98a844f8d0d9de40fe508ae1c830
[ "MIT" ]
permissive
zygi/lean-error-location
a578d5bc3f0b4d63037035ffe7041a7f949512f9
6a5a169b8fc80b2d5a30dded3adfa2ff684ecd92
refs/heads/master
1,679,507,973,901
1,616,213,777,000
1,616,213,777,000
349,624,081
0
0
null
1,616,213,778,000
1,616,213,576,000
Lean
UTF-8
Lean
false
false
2,255
lean
import Lean.Elab.Term import AssertCmd namespace LeanErrorLocation open Lean open Lean.Elab.Term -- This library exports two macros: -- 1) `__lineNum__` : gets replaced with an instance of the CodeLocation structure below. -- 2) `withCL[...]` : expects an argument `(f: CodeLocation -> Ξ±)` and replaces it with `(f __lineNum__)`. -- -- As an example, also exports `mkIOUserError`, a wrapper to construct an IO.userError with code -- location. Example usage: -- `throw withCL[mkIOUserError "error"]` -- will return `IO.userError "error at {codeloc}"` -- -- Note: remember that the location you're getting at macro expansion time. If you do -- ``` -- def a := toString __lineNum__ -- #eval a -- ``` -- you'll get the code location of the line with `def a`, not the one with `#eval`. structure CodeLocation where fileName: String posInFile: Position deriving Repr, BEq, Inhabited instance : ToString CodeLocation where toString cl := s!"{cl.fileName}:{cl.posInFile.line}:{cl.posInFile.column}" syntax (name:=lineNumMacro) "__lineNum__" : term @[termElab lineNumMacro] def expandLineNumMacro : TermElab := fun stx _ => do let ctx ← read let arg := stx.getArg 0 match arg with | Syntax.atom i _ => do let posInFile ← match i.getPos? with | none => Lean.Elab.throwUnsupportedSyntax | some x => x let resolvedPos := ctx.fileMap.toPosition posInFile let newStx : Syntax ← `(CodeLocation.mk ($(Syntax.mkStrLit ctx.fileName)) (Position.mk $(Syntax.mkNumLit $ toString resolvedPos.line) $(Syntax.mkNumLit $ toString resolvedPos.column))) elabTerm newStx none | _ => Lean.Elab.throwUnsupportedSyntax macro "withCL[" fn:term "]" : term=> `(($fn) __lineNum__) def mkIOUserError (s: String) (cl: CodeLocation) := IO.userError s!"{s} at {cl}" section Test def arg1 := toString __lineNum__ #assert (arg1 == "<input>:57:21" || arg1 == "LeanErrorLocation.lean:57:21") == true def arg2 := withCL[mkIOUserError "tragedy! horror!"].toString #assert (arg2 == toString (IO.userError "tragedy! horror! at <input>:60:12") || arg2 == toString (IO.userError "tragedy! horror! at LeanErrorLocation.lean:60:12")) == true end Test end LeanErrorLocation
c9776cc1972db69a64da12e793ae32b0563ff523
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/cardinal.lean
a398efb2fb04b20840d98eeaf255fcf55cba812b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,068
lean
/- Copyright (c) 2021 Chris Hughes, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Junyan Xu -/ import data.polynomial.basic import set_theory.cardinal.ordinal /-! # Cardinality of Polynomial Ring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The reuslt in this file is that the cardinality of `R[X]` is at most the maximum of `#R` and `β„΅β‚€`. -/ universe u open_locale cardinal polynomial open cardinal namespace polynomial @[simp] lemma cardinal_mk_eq_max {R : Type u} [semiring R] [nontrivial R] : #R[X] = max (#R) β„΅β‚€ := (to_finsupp_iso R).to_equiv.cardinal_eq.trans $ by { rw [add_monoid_algebra, mk_finsupp_lift_of_infinite, lift_uzero, max_comm], refl } lemma cardinal_mk_le_max {R : Type u} [semiring R] : #R[X] ≀ max (#R) β„΅β‚€ := begin casesI subsingleton_or_nontrivial R, { exact (mk_eq_one _).trans_le (le_max_of_le_right one_le_aleph_0) }, { exact cardinal_mk_eq_max.le }, end end polynomial
03c72dba755147372da8697d8de7c01842717bff
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/vector_bundle/prod.lean
b0f43c8ed41d78860b717cd4845eafdf0e051a93
[ "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
11,463
lean
/- Copyright Β© 2022 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Floris van Doorn -/ import topology.vector_bundle.basic /-! # Direct sum of two vector bundles If `E₁ : B β†’ Type*` and `Eβ‚‚ : B β†’ Type*` define two topological vector bundles over `R` with fiber models `F₁` and `Fβ‚‚`, we define the bundle of direct sums `E₁ ×ᡇ Eβ‚‚ := Ξ» x, E₁ x Γ— Eβ‚‚ x`. We can endow `E₁ ×ᡇ Eβ‚‚` with a topological vector bundle structure: `bundle.prod.topological_vector_bundle`. A similar construction (which is yet to be formalized) can be done for the vector bundle of continuous linear maps from `E₁ x` to `Eβ‚‚ x` with fiber a type synonym `vector_bundle_continuous_linear_map R F₁ E₁ Fβ‚‚ Eβ‚‚ x := (E₁ x β†’L[R] Eβ‚‚ x)` (and with the topology inherited from the norm-topology on `F₁ β†’L[R] Fβ‚‚`, without the need to define the strong topology on continuous linear maps between general topological vector spaces). Likewise for tensor products of topological vector bundles, exterior algebras, and so on, where the topology can be defined using a norm on the fiber model if this helps. ## Tags Vector bundle -/ noncomputable theory open bundle set open_locale classical variables (R π•œ : Type*) {B : Type*} (F : Type*) (E : B β†’ Type*) namespace topological_vector_bundle section defs variables (E₁ : B β†’ Type*) (Eβ‚‚ : B β†’ Type*) variables [topological_space (total_space E₁)] [topological_space (total_space Eβ‚‚)] /-- Equip the total space of the fibrewise product of two topological vector bundles `E₁`, `Eβ‚‚` with the induced topology from the diagonal embedding into `total_space E₁ Γ— total_space Eβ‚‚`. -/ instance prod.topological_space : topological_space (total_space (E₁ ×ᡇ Eβ‚‚)) := topological_space.induced (Ξ» p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space Eβ‚‚))) (by apply_instance : topological_space (total_space E₁ Γ— total_space Eβ‚‚)) /-- The diagonal map from the total space of the fibrewise product of two topological vector bundles `E₁`, `Eβ‚‚` into `total_space E₁ Γ— total_space Eβ‚‚` is `inducing`. -/ lemma prod.inducing_diag : inducing (Ξ» p, (⟨p.1, p.2.1⟩, ⟨p.1, p.2.2⟩) : total_space (E₁ ×ᡇ Eβ‚‚) β†’ total_space E₁ Γ— total_space Eβ‚‚) := ⟨rfl⟩ end defs variables [nondiscrete_normed_field R] [topological_space B] variables (F₁ : Type*) [normed_group F₁] [normed_space R F₁] (E₁ : B β†’ Type*) [topological_space (total_space E₁)] [Ξ  x, add_comm_monoid (E₁ x)] [Ξ  x, module R (E₁ x)] variables (Fβ‚‚ : Type*) [normed_group Fβ‚‚] [normed_space R Fβ‚‚] (Eβ‚‚ : B β†’ Type*) [topological_space (total_space Eβ‚‚)] [Ξ  x, add_comm_monoid (Eβ‚‚ x)] [Ξ  x, module R (Eβ‚‚ x)] namespace trivialization variables (e₁ : trivialization R F₁ E₁) (eβ‚‚ : trivialization R Fβ‚‚ Eβ‚‚) include e₁ eβ‚‚ variables {R F₁ E₁ Fβ‚‚ Eβ‚‚} /-- Given trivializations `e₁`, `eβ‚‚` for vector bundles `E₁`, `Eβ‚‚` over a base `B`, the forward function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `Eβ‚‚`. -/ def prod.to_fun' : total_space (E₁ ×ᡇ Eβ‚‚) β†’ B Γ— (F₁ Γ— Fβ‚‚) := Ξ» p, ⟨p.1, (e₁ ⟨p.1, p.2.1⟩).2, (eβ‚‚ ⟨p.1, p.2.2⟩).2⟩ variables {e₁ eβ‚‚} lemma prod.continuous_to_fun : continuous_on (prod.to_fun' e₁ eβ‚‚) (@total_space.proj B (E₁ ×ᡇ Eβ‚‚) ⁻¹' (e₁.base_set ∩ eβ‚‚.base_set)) := begin let f₁ : total_space (E₁ ×ᡇ Eβ‚‚) β†’ total_space E₁ Γ— total_space Eβ‚‚ := Ξ» p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space Eβ‚‚)), let fβ‚‚ : total_space E₁ Γ— total_space Eβ‚‚ β†’ (B Γ— F₁) Γ— (B Γ— Fβ‚‚) := Ξ» p, ⟨e₁ p.1, eβ‚‚ p.2⟩, let f₃ : (B Γ— F₁) Γ— (B Γ— Fβ‚‚) β†’ B Γ— F₁ Γ— Fβ‚‚ := Ξ» p, ⟨p.1.1, p.1.2, p.2.2⟩, have hf₁ : continuous f₁ := (prod.inducing_diag E₁ Eβ‚‚).continuous, have hfβ‚‚ : continuous_on fβ‚‚ (e₁.source Γ—Λ’ eβ‚‚.source) := e₁.to_local_homeomorph.continuous_on.prod_map eβ‚‚.to_local_homeomorph.continuous_on, have hf₃ : continuous f₃ := (continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd), refine ((hf₃.comp_continuous_on hfβ‚‚).comp hf₁.continuous_on _).congr _, { rw [e₁.source_eq, eβ‚‚.source_eq], exact maps_to_preimage _ _ }, rintros ⟨b, v₁, vβ‚‚βŸ© ⟨hb₁, hbβ‚‚βŸ©, simp only [prod.to_fun', prod.mk.inj_iff, eq_self_iff_true, and_true], rw e₁.coe_fst, rw [e₁.source_eq, mem_preimage], exact hb₁, end variables (e₁ eβ‚‚) /-- Given trivializations `e₁`, `eβ‚‚` for vector bundles `E₁`, `Eβ‚‚` over a base `B`, the inverse function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `Eβ‚‚`. -/ def prod.inv_fun' (p : B Γ— (F₁ Γ— Fβ‚‚)) : total_space (E₁ ×ᡇ Eβ‚‚) := ⟨p.1, e₁.symm p.1 p.2.1, eβ‚‚.symm p.1 p.2.2⟩ variables {e₁ eβ‚‚} lemma prod.left_inv {x : total_space (E₁ ×ᡇ Eβ‚‚)} (h : x ∈ @total_space.proj B (E₁ ×ᡇ Eβ‚‚) ⁻¹' (e₁.base_set ∩ eβ‚‚.base_set)) : prod.inv_fun' e₁ eβ‚‚ (prod.to_fun' e₁ eβ‚‚ x) = x := begin obtain ⟨x, v₁, vβ‚‚βŸ© := x, obtain ⟨h₁ : x ∈ e₁.base_set, hβ‚‚ : x ∈ eβ‚‚.base_set⟩ := h, simp only [prod.to_fun', prod.inv_fun', symm_apply_apply_mk, h₁, hβ‚‚] end lemma prod.right_inv {x : B Γ— F₁ Γ— Fβ‚‚} (h : x ∈ (e₁.base_set ∩ eβ‚‚.base_set) Γ—Λ’ (univ : set (F₁ Γ— Fβ‚‚))) : prod.to_fun' e₁ eβ‚‚ (prod.inv_fun' e₁ eβ‚‚ x) = x := begin obtain ⟨x, w₁, wβ‚‚βŸ© := x, obtain ⟨⟨h₁ : x ∈ e₁.base_set, hβ‚‚ : x ∈ eβ‚‚.base_set⟩, -⟩ := h, simp only [prod.to_fun', prod.inv_fun', apply_mk_symm, h₁, hβ‚‚] end lemma prod.continuous_inv_fun : continuous_on (prod.inv_fun' e₁ eβ‚‚) ((e₁.base_set ∩ eβ‚‚.base_set) Γ—Λ’ (univ : set (F₁ Γ— Fβ‚‚))) := begin rw (prod.inducing_diag E₁ Eβ‚‚).continuous_on_iff, have H₁ : continuous (Ξ» p : B Γ— F₁ Γ— Fβ‚‚, ((p.1, p.2.1), (p.1, p.2.2))) := (continuous_id.prod_map continuous_fst).prod_mk (continuous_id.prod_map continuous_snd), refine (e₁.continuous_on_symm.prod_map eβ‚‚.continuous_on_symm).comp H₁.continuous_on _, exact Ξ» x h, ⟨⟨h.1.1, mem_univ _⟩, ⟨h.1.2, mem_univ _⟩⟩ end variables (e₁ eβ‚‚) variables [Ξ  x : B, topological_space (E₁ x)] [Ξ  x : B, topological_space (Eβ‚‚ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R Fβ‚‚ Eβ‚‚] /-- Given trivializations `e₁`, `eβ‚‚` for vector bundles `E₁`, `Eβ‚‚` over a base `B`, the induced trivialization for the direct sum of `E₁` and `Eβ‚‚`, whose base set is `e₁.base_set ∩ eβ‚‚.base_set`. -/ @[nolint unused_arguments] def prod : trivialization R (F₁ Γ— Fβ‚‚) (E₁ ×ᡇ Eβ‚‚) := { to_fun := prod.to_fun' e₁ eβ‚‚, inv_fun := prod.inv_fun' e₁ eβ‚‚, source := (@total_space.proj B (E₁ ×ᡇ Eβ‚‚)) ⁻¹' (e₁.base_set ∩ eβ‚‚.base_set), target := (e₁.base_set ∩ eβ‚‚.base_set) Γ—Λ’ (set.univ : set (F₁ Γ— Fβ‚‚)), map_source' := Ξ» x h, ⟨h, set.mem_univ _⟩, map_target' := Ξ» x h, h.1, left_inv' := Ξ» x, prod.left_inv, right_inv' := Ξ» x, prod.right_inv, open_source := begin refine (e₁.open_base_set.inter eβ‚‚.open_base_set).preimage _, have : continuous (@total_space.proj B E₁) := continuous_proj R B F₁, exact this.comp (prod.inducing_diag E₁ Eβ‚‚).continuous.fst, end, open_target := (e₁.open_base_set.inter eβ‚‚.open_base_set).prod is_open_univ, continuous_to_fun := prod.continuous_to_fun, continuous_inv_fun := prod.continuous_inv_fun, base_set := e₁.base_set ∩ eβ‚‚.base_set, open_base_set := e₁.open_base_set.inter eβ‚‚.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := Ξ» x h, rfl, linear' := Ξ» x ⟨h₁, hβ‚‚βŸ©, (((e₁.linear h₁).mk' _).prod_map ((eβ‚‚.linear hβ‚‚).mk' _)).is_linear } @[simp] lemma base_set_prod : (prod e₁ eβ‚‚).base_set = e₁.base_set ∩ eβ‚‚.base_set := rfl variables {e₁ eβ‚‚} lemma prod_apply {x : B} (hx₁ : x ∈ e₁.base_set) (hxβ‚‚ : x ∈ eβ‚‚.base_set) (v₁ : E₁ x) (vβ‚‚ : Eβ‚‚ x) : prod e₁ eβ‚‚ ⟨x, (v₁, vβ‚‚)⟩ = ⟨x, e₁.continuous_linear_equiv_at x hx₁ v₁, eβ‚‚.continuous_linear_equiv_at x hxβ‚‚ vβ‚‚βŸ© := rfl lemma prod_symm_apply (x : B) (w₁ : F₁) (wβ‚‚ : Fβ‚‚) : (prod e₁ eβ‚‚).to_local_equiv.symm (x, w₁, wβ‚‚) = ⟨x, e₁.symm x w₁, eβ‚‚.symm x wβ‚‚βŸ© := rfl end trivialization open trivialization variables [Ξ  x : B, topological_space (E₁ x)] [Ξ  x : B, topological_space (Eβ‚‚ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R Fβ‚‚ Eβ‚‚] /-- The product of two vector bundles is a vector bundle. -/ instance _root_.bundle.prod.topological_vector_bundle : topological_vector_bundle R (F₁ Γ— Fβ‚‚) (E₁ ×ᡇ Eβ‚‚) := { total_space_mk_inducing := Ξ» b, begin rw (prod.inducing_diag E₁ Eβ‚‚).inducing_iff, exact (total_space_mk_inducing R F₁ E₁ b).prod_mk (total_space_mk_inducing R Fβ‚‚ Eβ‚‚ b), end, trivialization_atlas := (Ξ» (p : trivialization R F₁ E₁ Γ— trivialization R Fβ‚‚ Eβ‚‚), p.1.prod p.2) '' (trivialization_atlas R F₁ E₁ Γ—Λ’ trivialization_atlas R Fβ‚‚ Eβ‚‚), trivialization_at := Ξ» b, (trivialization_at R F₁ E₁ b).prod (trivialization_at R Fβ‚‚ Eβ‚‚ b), mem_base_set_trivialization_at := Ξ» b, ⟨mem_base_set_trivialization_at R F₁ E₁ b, mem_base_set_trivialization_at R Fβ‚‚ Eβ‚‚ b⟩, trivialization_mem_atlas := Ξ» b, ⟨(_, _), ⟨trivialization_mem_atlas R F₁ E₁ b, trivialization_mem_atlas R Fβ‚‚ Eβ‚‚ b⟩, rfl⟩, continuous_on_coord_change := begin rintros _ ⟨⟨e₁, eβ‚‚βŸ©, ⟨he₁, heβ‚‚βŸ©, rfl⟩ _ ⟨⟨e₁', eβ‚‚'⟩, ⟨he₁', heβ‚‚'⟩, rfl⟩, have := continuous_on_coord_change e₁ he₁ e₁' he₁', have := continuous_on_coord_change eβ‚‚ heβ‚‚ eβ‚‚' heβ‚‚', refine (((continuous_on_coord_change e₁ he₁ e₁' he₁').mono _).prod_mapL R ((continuous_on_coord_change eβ‚‚ heβ‚‚ eβ‚‚' heβ‚‚').mono _)).congr _; dsimp only [base_set_prod] with mfld_simps, { mfld_set_tac }, { mfld_set_tac }, { rintro b hb, rw [continuous_linear_map.ext_iff], rintro ⟨v₁, vβ‚‚βŸ©, show (e₁.prod eβ‚‚).coord_change (e₁'.prod eβ‚‚') b (v₁, vβ‚‚) = (e₁.coord_change e₁' b v₁, eβ‚‚.coord_change eβ‚‚' b vβ‚‚), rw [e₁.coord_change_apply e₁', eβ‚‚.coord_change_apply eβ‚‚', (e₁.prod eβ‚‚).coord_change_apply'], exacts [rfl, hb, ⟨hb.1.2, hb.2.2⟩, ⟨hb.1.1, hb.2.1⟩] } end } variables {R F₁ E₁ Fβ‚‚ Eβ‚‚} @[simp] lemma trivialization.continuous_linear_equiv_at_prod {e₁ : trivialization R F₁ E₁} {eβ‚‚ : trivialization R Fβ‚‚ Eβ‚‚} {x : B} (hx₁ : x ∈ e₁.base_set) (hxβ‚‚ : x ∈ eβ‚‚.base_set) : (e₁.prod eβ‚‚).continuous_linear_equiv_at x ⟨hx₁, hxβ‚‚βŸ© = (e₁.continuous_linear_equiv_at x hx₁).prod (eβ‚‚.continuous_linear_equiv_at x hxβ‚‚) := begin ext1, funext v, obtain ⟨v₁, vβ‚‚βŸ© := v, rw [(e₁.prod eβ‚‚).continuous_linear_equiv_at_apply, trivialization.prod], exact (congr_arg prod.snd (prod_apply hx₁ hxβ‚‚ v₁ vβ‚‚) : _) end end topological_vector_bundle
d02159d0490d1aa2909537ac15da7001b4cf7ee6
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/connected.lean
11d8ba3cb8447f19cf2e8593b86f1075e8e64ec1
[ "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
8,800
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.const import category_theory.discrete_category import category_theory.eq_to_hom /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟢ jβ‚‚` implies `F j₁ = F jβ‚‚` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `jβ‚‚`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X Γ— -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X Γ— -)`. -/ universes v₁ vβ‚‚ u₁ uβ‚‚ open category_theory.category namespace category_theory section connected -- See note [default priority] set_option default_priority 100 /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X β¨― - preserves connected limits. -/ class connected (J : Type vβ‚‚) [category.{v₁} J] extends inhabited J := (iso_constant : Ξ  {Ξ± : Type vβ‚‚} (F : J β₯€ discrete Ξ±), F β‰… (functor.const J).obj (F.obj default)) end connected variables {J : Type vβ‚‚} [category.{v₁} J] /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [connected J] {Ξ± : Type vβ‚‚} (F : J β₯€ discrete Ξ±) (j : J) : F.obj j = F.obj (default J) := ((connected.iso_constant F).hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ def connected.of_any_functor_const_on_obj [inhabited J] (h : βˆ€ {Ξ± : Type vβ‚‚} (F : J β₯€ discrete Ξ±), βˆ€ (j : J), F.obj j = F.obj (default J)) : connected J := { iso_constant := Ξ» Ξ± F, nat_iso.of_components (Ξ» B, eq_to_iso (h F B)) (Ξ» _ _ _, subsingleton.elim _ _) } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟢ jβ‚‚` implies `F j₁ = F jβ‚‚`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [connected J] {Ξ± : Type vβ‚‚} (F : J β†’ Ξ±) (h : βˆ€ (j₁ jβ‚‚ : J) (f : j₁ ⟢ jβ‚‚), F j₁ = F jβ‚‚) (j : J) : F j = F (default J) := any_functor_const_on_obj { obj := F, map := Ξ» _ _ f, eq_to_hom (h _ _ f) } j /-- `J` is connected if: given any function `F : J β†’ Ξ±` which is constant for any `j₁, jβ‚‚` for which there is a morphism `j₁ ⟢ jβ‚‚`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ def connected.of_constant_of_preserves_morphisms [inhabited J] (h : βˆ€ {Ξ± : Type vβ‚‚} (F : J β†’ Ξ±), (βˆ€ {j₁ jβ‚‚ : J} (f : j₁ ⟢ jβ‚‚), F j₁ = F jβ‚‚) β†’ (βˆ€ j : J, F j = F (default J))) : connected J := connected.of_any_functor_const_on_obj (Ξ» _ F, h F.obj (Ξ» _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If `default J` is in the set `p`, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `connected.of_induct`. -/ lemma induct_on_objects [connected J] (p : set J) (h0 : default J ∈ p) (h1 : βˆ€ {j₁ jβ‚‚ : J} (f : j₁ ⟢ jβ‚‚), j₁ ∈ p ↔ jβ‚‚ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (Ξ» k, ulift.up (k ∈ p)) (Ξ» j₁ jβ‚‚ f, _) j) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component of J containing the default is all of J, then J is connected. The converse of `induct_on_objects`. -/ def connected.of_induct [inhabited J] (h : βˆ€ (p : set J), default J ∈ p β†’ (βˆ€ {j₁ jβ‚‚ : J} (f : j₁ ⟢ jβ‚‚), j₁ ∈ p ↔ jβ‚‚ ∈ p) β†’ βˆ€ (j : J), j ∈ p) : connected J := connected.of_constant_of_preserves_morphisms (Ξ» Ξ± F a, h {j | F j = F (default J)} rfl (Ξ» _ _ f, by simp [a f] )) /-- j₁ and jβ‚‚ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ jβ‚‚ : J) : Prop := nonempty (j₁ ⟢ jβ‚‚) ∨ nonempty (jβ‚‚ ⟢ j₁) /-- `j₁` and `jβ‚‚` are related by `zigzag` if there is a chain of morphisms from `j₁` to `jβ‚‚`, with backward morphisms allowed. -/ @[reducible] def zigzag : J β†’ J β†’ Prop := relation.refl_trans_gen zag /-- Any equivalence relation containing (⟢) holds for all pairs of a connected category. -/ lemma equiv_relation [connected J] (r : J β†’ J β†’ Prop) (hr : _root_.equivalence r) (h : βˆ€ {j₁ jβ‚‚ : J} (f : j₁ ⟢ jβ‚‚), r j₁ jβ‚‚) : βˆ€ (j₁ jβ‚‚ : J), r j₁ jβ‚‚ := begin have z: βˆ€ (j : J), r (default J) j := induct_on_objects (Ξ» k, r (default J) k) (hr.1 (default J)) (Ξ» _ _ f, ⟨λ t, hr.2.2 t (h f), Ξ» t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma connected_zigzag [connected J] (j₁ jβ‚‚ : J) : zigzag j₁ jβ‚‚ := equiv_relation _ (mk_equivalence _ relation.reflexive_refl_trans_gen (relation.refl_trans_gen.symmetric (Ξ» _ _ _, by rwa [zag, or_comm])) relation.transitive_refl_trans_gen) (Ξ» _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an inhabited category are related by `zigzag`, the category is connected. -/ def zigzag_connected [inhabited J] (h : βˆ€ (j₁ jβ‚‚ : J), zigzag j₁ jβ‚‚) : connected J := begin apply connected.of_induct, intros, have: βˆ€ (j₁ jβ‚‚ : J), zigzag j₁ jβ‚‚ β†’ (j₁ ∈ p ↔ jβ‚‚ ∈ p), { introv k, induction k, { refl }, { rw k_ih, rcases k_a_1 with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply a_1 k_a_1, apply (a_1 k_a_1).symm } }, rwa this j (default J) (h _ _) end lemma exists_zigzag' [connected J] (j₁ jβ‚‚ : J) : βˆƒ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = jβ‚‚ := list.exists_chain_of_relation_refl_trans_gen (connected_zigzag _ _) /-- If any two objects in an inhabited category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ def connected_of_zigzag [inhabited J] (h : βˆ€ (j₁ jβ‚‚ : J), βˆƒ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = jβ‚‚) : connected J := begin apply connected.of_induct, intros p d k j, obtain ⟨l, zags, lst⟩ := h j (default J), apply list.chain.induction p l zags lst _ d, rintros _ _ (⟨⟨_⟩⟩ | ⟨⟨_⟩⟩), { exact (k a).2 }, { exact (k a).1 } end variables {C : Type uβ‚‚} [category.{vβ‚‚} C] /-- For objects `X Y : C`, any natural transformation `Ξ± : const X ⟢ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_connected [conn : connected J] {X Y : C} (Ξ± : (functor.const J).obj X ⟢ (functor.const J).obj Y) : βˆ€ (j : J), Ξ±.app j = (Ξ±.app (default J) : X ⟢ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟢ Y) (Ξ» j, Ξ±.app j) (Ξ» _ _ f, (by { have := Ξ±.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) end category_theory
9b7b02533f8d971b8cfc79524e3586583bff8985
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/funext_issue.lean
e2631918764aea4a271f57cf182829b7fd37c4a5
[ "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
119
lean
universes u example (Ξ± : Type u) (p : Prop) (a b : Ξ±) (h : p β†’ a = b) : (Ξ» x : p, a) = (Ξ» x : p, b) := funext h
419ac69f0b09e903eaa33d1bd0bb86ec3005837a
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/dia.lean
5d22841ed15f6b24f3c43e9b69995eda043cc561
[ "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
2,127
lean
import macros theorem bool_inhab : inhabited Bool := inhabited_intro true -- Excluded middle from eps_ax, boolext, funext, and subst theorem em_new (p : Bool) : p ∨ Β¬ p := let u := @eps Bool bool_inhab (Ξ» x, x = true ∨ p), v := @eps Bool bool_inhab (Ξ» x, x = false ∨ p) in have Hu : u = true ∨ p, from @eps_ax Bool bool_inhab (Ξ» x, x = true ∨ p) true (or_introl (refl true) p), have Hv : v = false ∨ p, from @eps_ax Bool bool_inhab (Ξ» x, x = false ∨ p) false (or_introl (refl false) p), have H1 : u β‰  v ∨ p, from or_elim Hu (assume Hut : u = true, or_elim Hv (assume Hvf : v = false, have Hne : u β‰  v, from subst (subst true_ne_false (symm Hut)) (symm Hvf), or_introl Hne p) (assume Hp : p, or_intror (u β‰  v) Hp)) (assume Hp : p, or_intror (u β‰  v) Hp), have H2 : p β†’ u = v, from assume Hp : p, have Hpred : (Ξ» x, x = true ∨ p) = (Ξ» x, x = false ∨ p), from funext (take x : Bool, have Hl : (x = true ∨ p) β†’ (x = false ∨ p), from assume A, or_intror (x = false) Hp, have Hr : (x = false ∨ p) β†’ (x = true ∨ p), from assume A, or_intror (x = true) Hp, show (x = true ∨ p) = (x = false ∨ p), from boolext Hl Hr), show u = v, from @subst (Bool β†’ Bool) (Ξ» x : Bool, (@eq Bool x true) ∨ p) (Ξ» x : Bool, (@eq Bool x false) ∨ p) (Ξ» q : Bool β†’ Bool, @eps Bool bool_inhab (Ξ» x : Bool, (@eq Bool x true) ∨ p) = @eps Bool bool_inhab q) (@refl Bool (@eps Bool bool_inhab (Ξ» x : Bool, (@eq Bool x true) ∨ p))) Hpred, have H3 : u β‰  v β†’ Β¬ p, from contrapos H2, or_elim H1 (assume Hne : u β‰  v, or_intror p (H3 Hne)) (assume Hp : p, or_introl Hp (Β¬ p))
7bb0d4f92e135929b06d1eb1906c920108a97e01
caa1512363b76923d0e9cdb716122a5c26c3c6bc
/src/eigenvectors/algebraically_closed.lean
55ee7eae6adb3d80b816f002454859c91712786e
[]
no_license
apurvanakade/cvx
deb20e425ce478159a98e1ffc0d37f9c88a89280
b47784831339df5a3e45f5cddd84edc545f95808
refs/heads/master
1,687,403,288,536
1,555,930,740,000
1,555,930,740,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,337
lean
import analysis.complex.polynomial import ring_theory.principal_ideal_domain import linear_algebra.dimension open polynomial open vector_space cardinal principal_ideal_domain submodule -- TODO: move lemma polynomial.not_is_unit_X_sub_C {Ξ± : Type} [integral_domain Ξ±] [decidable_eq Ξ±]: βˆ€ a : Ξ±, Β¬ is_unit (X - C a) := begin intros a ha, let ha' := degree_eq_zero_of_is_unit ha, rw [degree_X_sub_C] at ha', apply nat.zero_ne_one (option.injective_some _ ha'.symm) end -- TODO: move to dimension.lean lemma linear_independed_le_dim {Ξ± Ξ² : Type} [discrete_field Ξ±] [add_comm_group Ξ²] [vector_space Ξ± Ξ²] {I : set Ξ²} (hI : linear_independent Ξ± I): cardinal.mk I ≀ dim Ξ± Ξ² := calc cardinal.mk I = dim Ξ± (span Ξ± I) : (dim_span hI).symm ... ≀ dim Ξ± Ξ² : dim_submodule_le (span Ξ± I) /-- algebraically closed field -/ class algebraically_closed (K : Type) extends discrete_field K := (exists_root {p : polynomial K} : 0 < degree p β†’ βˆƒ a, is_root p a) namespace algebraically_closed variables {K : Type} [algebraically_closed K] lemma degree_le_one_of_irreducible (p : polynomial K) : irreducible p β†’ p.degree ≀ 1 := begin by_cases h_cases : 0 < p.degree, { assume hp : irreducible p, show degree p ≀ 1, { cases (algebraically_closed.exists_root h_cases) with a ha, have h_p_eq_mul : (X - C a) * (p / (X - C a)) = p, { apply mul_div_eq_iff_is_root.2 ha }, have h_unit : is_unit (p / (X - C a)), from or.resolve_left (hp.2 (X - C a) (p / (X - C a)) h_p_eq_mul.symm) (polynomial.not_is_unit_X_sub_C _), show degree p ≀ 1, { rw h_p_eq_mul.symm, apply trans (degree_mul_le (X - C a) (p / (X - C a))), rw [degree_X_sub_C, degree_eq_zero_of_is_unit h_unit], simp [le_refl] } } }, { exact Ξ»_, le_trans (le_of_not_gt h_cases) (with_bot.some_le_some.2 (nat.le_succ 0)) } end variables {V : Type} [add_comm_group V] [vector_space K V] [f : V β†’β‚—[K] V] variables (h_dim : dim K V < omega) variable {x : V} set_option class.instance_max_depth 41 #check linear_independed_le_dim #check linear_independed_le_dim lemma exists_eigenvector : βˆƒ (x : V) (c : K), f.to_fun x = c β€’ x := begin let s := Ξ» x, set.range (Ξ» n : β„•, (f ^ n).to_fun x), --TODO: should be multiset ... have h : βˆ€ x, Β¬ linear_independent K (s x), { intros x hs, let H:= linear_independed_le_dim hs, } end set_option class.instance_max_depth 32 end algebraically_closed noncomputable instance complex.algebraically_closed : algebraically_closed β„‚ := { exists_root := (Ξ» p hp, complex.exists_root hp) } #check complex.exists_root end set_option class.instance_max_depth 32 open principal_ideal_domain #check factors (p : polynomial β„‚) #check factors_spec (p : polynomial β„‚) -- better euclidean_domain -> principle_ideal_domain -> factors #check polynomial.evalβ‚‚ (Ξ»c, c β€’ linear_map.id) _ p #print irreducible. example : polynomial.evalβ‚‚ (Ξ»c, c β€’ linear_map.id) (linear_map.id : Ξ² β†’β‚—[Ξ±] Ξ²) (multiset.prod (factors (p : polynomial β„‚))) = multiset.prod (multiset.map polynomial.evalβ‚‚ (Ξ»c, c β€’ linear_map.id) (linear_map.id : Ξ± β†’β‚—[β„‚] Ξ±) (factors (p : polynomial β„‚))) := by library_search #check polynomial.mul_div_eq_iff_is_root
e51399b0a60ef5f8a07388447d3063754db384b7
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/blog/video.lean
3a1d6b7b24f2bd928e8dd51438248bf1c3e64599
[]
no_license
roro47/xena
6389bcd7dcf395656a2c85cfc90a4366e9b825bb
237910190de38d6ff43694ffe3a9b68f79363e6c
refs/heads/master
1,598,570,061,948
1,570,052,567,000
1,570,052,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
200
lean
#exit Type ℝ β„š β„€ group G ring R modular_form f ... Ο€ : ℝ ℝ : Type β„• = {0, 1, 2, 3, ...} βˆ€ s : β„‚, ΞΆ(s) = 0 β†’ s ∈ β„€ ∨ Re(s) = 1/2
3207f869a9e023c0e2e879618bd595718448a2be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed/group/pointwise.lean
8cb7806fbb3daed2a385c9fe16423006cf204f0c
[ "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
7,811
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, YaΓ«l Dillies -/ import analysis.normed.group.basic import topology.metric_space.hausdorff_distance /-! # Properties of pointwise addition of sets in normed groups We explore the relationships between pointwise addition of sets in normed groups, and the norm. Notably, we show that the sum of bounded sets remain bounded. -/ open metric set open_locale pointwise topological_space variables {E : Type*} section seminormed_group variables [seminormed_group E] {Ξ΅ Ξ΄ : ℝ} {s t : set E} {x y : E} @[to_additive] lemma metric.bounded.mul (hs : bounded s) (ht : bounded t) : bounded (s * t) := begin obtain ⟨Rs, hRs⟩ : βˆƒ R, βˆ€ x ∈ s, β€–xβ€– ≀ R := hs.exists_norm_le', obtain ⟨Rt, hRt⟩ : βˆƒ R, βˆ€ x ∈ t, β€–xβ€– ≀ R := ht.exists_norm_le', refine bounded_iff_forall_norm_le'.2 ⟨Rs + Rt, _⟩, rintro z ⟨x, y, hx, hy, rfl⟩, exact norm_mul_le_of_le (hRs x hx) (hRt y hy), end @[to_additive] lemma metric.bounded.inv : bounded s β†’ bounded s⁻¹ := by { simp_rw [bounded_iff_forall_norm_le', ←image_inv, ball_image_iff, norm_inv'], exact id } @[to_additive] lemma metric.bounded.div (hs : bounded s) (ht : bounded t) : bounded (s / t) := (div_eq_mul_inv _ _).symm.subst $ hs.mul ht.inv end seminormed_group section seminormed_comm_group variables [seminormed_comm_group E] {Ξ΅ Ξ΄ : ℝ} {s t : set E} {x y : E} section emetric open emetric @[to_additive] lemma inf_edist_inv (x : E) (s : set E) : inf_edist x⁻¹ s = inf_edist x s⁻¹ := eq_of_forall_le_iff $ Ξ» r, by simp_rw [le_inf_edist, ←image_inv, ball_image_iff, edist_inv] @[simp, to_additive] lemma inf_edist_inv_inv (x : E) (s : set E) : inf_edist x⁻¹ s⁻¹ = inf_edist x s := by rw [inf_edist_inv, inv_inv] end emetric variables (Ξ΅ Ξ΄ s t x y) @[simp, to_additive] lemma inv_thickening : (thickening Ξ΄ s)⁻¹ = thickening Ξ΄ s⁻¹ := by { simp_rw [thickening, ←inf_edist_inv], refl } @[simp, to_additive] lemma inv_cthickening : (cthickening Ξ΄ s)⁻¹ = cthickening Ξ΄ s⁻¹ := by { simp_rw [cthickening, ←inf_edist_inv], refl } @[simp, to_additive] lemma inv_ball : (ball x Ξ΄)⁻¹ = ball x⁻¹ Ξ΄ := by { simp_rw [ball, ←dist_inv], refl } @[simp, to_additive] lemma inv_closed_ball : (closed_ball x Ξ΄)⁻¹ = closed_ball x⁻¹ Ξ΄ := by { simp_rw [closed_ball, ←dist_inv], refl } @[to_additive] lemma singleton_mul_ball : {x} * ball y Ξ΄ = ball (x * y) Ξ΄ := by simp only [preimage_mul_ball, image_mul_left, singleton_mul, div_inv_eq_mul, mul_comm y x] @[to_additive] lemma singleton_div_ball : {x} / ball y Ξ΄ = ball (x / y) Ξ΄ := by simp_rw [div_eq_mul_inv, inv_ball, singleton_mul_ball] @[to_additive] lemma ball_mul_singleton : ball x Ξ΄ * {y} = ball (x * y) Ξ΄ := by rw [mul_comm, singleton_mul_ball, mul_comm y] @[to_additive] lemma ball_div_singleton : ball x Ξ΄ / {y} = ball (x / y) Ξ΄ := by simp_rw [div_eq_mul_inv, inv_singleton, ball_mul_singleton] @[to_additive] lemma singleton_mul_ball_one : {x} * ball 1 Ξ΄ = ball x Ξ΄ := by simp @[to_additive] lemma singleton_div_ball_one : {x} / ball 1 Ξ΄ = ball x Ξ΄ := by simp [singleton_div_ball] @[to_additive] lemma ball_one_mul_singleton : ball 1 Ξ΄ * {x} = ball x Ξ΄ := by simp [ball_mul_singleton] @[to_additive] lemma ball_one_div_singleton : ball 1 Ξ΄ / {x} = ball x⁻¹ Ξ΄ := by simp [ball_div_singleton] @[to_additive] lemma smul_ball_one : x β€’ ball 1 Ξ΄ = ball x Ξ΄ := by { ext, simp [mem_smul_set_iff_inv_smul_mem, inv_mul_eq_div, dist_eq_norm_div] } @[simp, to_additive] lemma singleton_mul_closed_ball : {x} * closed_ball y Ξ΄ = closed_ball (x * y) Ξ΄ := by simp only [mul_comm y x, preimage_mul_closed_ball, image_mul_left, singleton_mul, div_inv_eq_mul] @[simp, to_additive] lemma singleton_div_closed_ball : {x} / closed_ball y Ξ΄ = closed_ball (x / y) Ξ΄ := by simp_rw [div_eq_mul_inv, inv_closed_ball, singleton_mul_closed_ball] @[simp, to_additive] lemma closed_ball_mul_singleton : closed_ball x Ξ΄ * {y} = closed_ball (x * y) Ξ΄ := by simp [mul_comm _ {y}, mul_comm y] @[simp, to_additive] lemma closed_ball_div_singleton : closed_ball x Ξ΄ / {y} = closed_ball (x / y) Ξ΄ := by simp [div_eq_mul_inv] @[to_additive] lemma singleton_mul_closed_ball_one : {x} * closed_ball 1 Ξ΄ = closed_ball x Ξ΄ := by simp @[to_additive] lemma singleton_div_closed_ball_one : {x} / closed_ball 1 Ξ΄ = closed_ball x Ξ΄ := by simp @[to_additive] lemma closed_ball_one_mul_singleton : closed_ball 1 Ξ΄ * {x} = closed_ball x Ξ΄ := by simp @[to_additive] lemma closed_ball_one_div_singleton : closed_ball 1 Ξ΄ / {x} = closed_ball x⁻¹ Ξ΄ := by simp @[simp, to_additive] lemma smul_closed_ball_one : x β€’ closed_ball 1 Ξ΄ = closed_ball x Ξ΄ := by { ext, simp [mem_smul_set_iff_inv_smul_mem, inv_mul_eq_div, dist_eq_norm_div] } @[to_additive] lemma mul_ball_one : s * ball 1 Ξ΄ = thickening Ξ΄ s := begin rw thickening_eq_bUnion_ball, convert Unionβ‚‚_mul (Ξ» x (_ : x ∈ s), {x}) (ball (1 : E) Ξ΄), exact s.bUnion_of_singleton.symm, ext x y, simp_rw [singleton_mul_ball, mul_one], end @[to_additive] lemma div_ball_one : s / ball 1 Ξ΄ = thickening Ξ΄ s := by simp [div_eq_mul_inv, mul_ball_one] @[to_additive] lemma ball_mul_one : ball 1 Ξ΄ * s = thickening Ξ΄ s := by rw [mul_comm, mul_ball_one] @[to_additive] lemma ball_div_one : ball 1 Ξ΄ / s = thickening Ξ΄ s⁻¹ := by simp [div_eq_mul_inv, ball_mul_one] @[simp, to_additive] lemma mul_ball : s * ball x Ξ΄ = x β€’ thickening Ξ΄ s := by rw [←smul_ball_one, mul_smul_comm, mul_ball_one] @[simp, to_additive] lemma div_ball : s / ball x Ξ΄ = x⁻¹ β€’ thickening Ξ΄ s := by simp [div_eq_mul_inv] @[simp, to_additive] lemma ball_mul : ball x Ξ΄ * s = x β€’ thickening Ξ΄ s := by rw [mul_comm, mul_ball] @[simp, to_additive] lemma ball_div : ball x Ξ΄ / s = x β€’ thickening Ξ΄ s⁻¹ := by simp [div_eq_mul_inv] variables {Ξ΅ Ξ΄ s t x y} @[to_additive] lemma is_compact.mul_closed_ball_one (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) : s * closed_ball 1 Ξ΄ = cthickening Ξ΄ s := begin rw hs.cthickening_eq_bUnion_closed_ball hΞ΄, ext x, simp only [mem_mul, dist_eq_norm_div, exists_prop, mem_Union, mem_closed_ball, exists_and_distrib_left, mem_closed_ball_one_iff, ← eq_div_iff_mul_eq'', exists_eq_right], end @[to_additive] lemma is_compact.div_closed_ball_one (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) : s / closed_ball 1 Ξ΄ = cthickening Ξ΄ s := by simp [div_eq_mul_inv, hs.mul_closed_ball_one hΞ΄] @[to_additive] lemma is_compact.closed_ball_one_mul (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) : closed_ball 1 Ξ΄ * s = cthickening Ξ΄ s := by rw [mul_comm, hs.mul_closed_ball_one hΞ΄] @[to_additive] lemma is_compact.closed_ball_one_div (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) : closed_ball 1 Ξ΄ / s = cthickening Ξ΄ s⁻¹ := by simp [div_eq_mul_inv, mul_comm, hs.inv.mul_closed_ball_one hΞ΄] @[to_additive] lemma is_compact.mul_closed_ball (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) (x : E) : s * closed_ball x Ξ΄ = x β€’ cthickening Ξ΄ s := by rw [←smul_closed_ball_one, mul_smul_comm, hs.mul_closed_ball_one hΞ΄] @[to_additive] lemma is_compact.div_closed_ball (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) (x : E) : s / closed_ball x Ξ΄ = x⁻¹ β€’ cthickening Ξ΄ s := by simp [div_eq_mul_inv, mul_comm, hs.mul_closed_ball hΞ΄] @[to_additive] lemma is_compact.closed_ball_mul (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) (x : E) : closed_ball x Ξ΄ * s = x β€’ cthickening Ξ΄ s := by rw [mul_comm, hs.mul_closed_ball hΞ΄] @[to_additive] lemma is_compact.closed_ball_div (hs : is_compact s) (hΞ΄ : 0 ≀ Ξ΄) (x : E) : closed_ball x Ξ΄ * s = x β€’ cthickening Ξ΄ s := by simp [div_eq_mul_inv, mul_comm, hs.closed_ball_mul hΞ΄] end seminormed_comm_group
4ecf7a319ed53c7281f3d8893d35d2da37c68fbf
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Widget/InteractiveCode.lean
92112ca9bcf3590001f6de593e1e9738d03634a9
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
4,939
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.PrettyPrinter import Lean.Server.Rpc.Basic import Lean.Widget.TaggedText /-! RPC infrastructure for storing and formatting code fragments, in particular `Expr`s, with environment and subexpression information. -/ namespace Lean.Widget open Server -- TODO: Some of the `WithBlah` types exist mostly because we cannot derive multi-argument RPC wrappers. -- They will be gone eventually. structure InfoWithCtx where ctx : Elab.ContextInfo lctx : LocalContext info : Elab.Info deriving Inhabited, RpcEncoding with { withRef := true } structure CodeToken where info : WithRpcRef InfoWithCtx -- TODO(WN): add fields for semantic highlighting -- kind : Lsp.SymbolKind deriving Inhabited, RpcEncoding /-- Pretty-printed syntax (usually but not necessarily an `Expr`) with embedded `Info`s. -/ abbrev CodeWithInfos := TaggedText CodeToken def CodeWithInfos.pretty (tt : CodeWithInfos) := tt.stripTags open Expr in /-- Find a subexpression of `e` using the pretty-printer address scheme. -/ -- NOTE(WN): not currently in use partial def traverse (e : Expr) (addr : Nat) : MetaM (LocalContext Γ— Expr):= do let e ← Meta.instantiateMVars e go (tritsLE [] addr |>.drop 1) (← getLCtx) e where tritsLE (acc : List Nat) (n : Nat) : List Nat := if n == 0 then acc else tritsLE (n % 3 :: acc) (n / 3) go (addr : List Nat) (lctx : LocalContext) (e : Expr) : MetaM (LocalContext Γ— Expr) := do match addr with | [] => (lctx, e) | a::as => do let go' (e' : Expr) := do go as (← getLCtx) e' let eExpr ← match a, e with | 0, app e₁ eβ‚‚ _ => go' e₁ | 1, app e₁ eβ‚‚ _ => go' eβ‚‚ | 0, lam _ e₁ eβ‚‚ _ => go' e₁ | 1, lam n e₁ eβ‚‚ data => Meta.withLocalDecl n data.binderInfo e₁ fun fvar => go' (eβ‚‚.instantiate1 fvar) | 0, forallE _ e₁ eβ‚‚ _ => go' e₁ | 1, forallE n e₁ eβ‚‚ data => Meta.withLocalDecl n data.binderInfo e₁ fun fvar => go' (eβ‚‚.instantiate1 fvar) | 0, letE _ e₁ eβ‚‚ e₃ _ => go' e₁ | 1, letE _ e₁ eβ‚‚ e₃ _ => go' eβ‚‚ | 2, letE n e₁ eβ‚‚ e₃ _ => Meta.withLetDecl n e₁ eβ‚‚ fun fvar => do go' (e₃.instantiate1 fvar) | 0, mdata _ e₁ _ => go' e₁ | 0, proj _ _ e₁ _ => go' e₁ | _, _ => (lctx, e) -- panic! s!"cannot descend {a} into {e.expr}" -- TODO(WN): should the two fns below go in `Lean.PrettyPrinter` ? open PrettyPrinter in private def formatWithOpts (e : Expr) (optsPerPos : Delaborator.OptionsPerPos) : MetaM (Format Γ— Std.RBMap Nat Elab.Info compare) := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let opts ← getOptions let (stx, infos) ← PrettyPrinter.delabCore currNamespace openDecls e let stx := sanitizeSyntax stx |>.run' { options := opts } let stx ← PrettyPrinter.parenthesizeTerm stx let fmt ← PrettyPrinter.formatTerm stx return (fmt, infos) /-- Pretty-print the expression and its subexpression information. -/ def formatInfos (e : Expr) : MetaM (Format Γ— Std.RBMap Nat Elab.Info compare) := formatWithOpts e {} /-- Like `formatInfos` but with `pp.all` set at the top-level expression. -/ def formatExplicitInfos (e : Expr) : MetaM (Format Γ— Std.RBMap Nat Elab.Info compare) := let optsPerPos := Std.RBMap.ofList [(1, KVMap.empty.setBool `pp.all true)] formatWithOpts e optsPerPos /-- Tags a pretty-printed `Expr` with infos from the delaborator. -/ partial def tagExprInfos (ctx : Elab.ContextInfo) (lctx : LocalContext) (infos : Std.RBMap Nat Elab.Info compare) (tt : TaggedText (Nat Γ— Nat)) : CodeWithInfos := go tt where go (tt : TaggedText (Nat Γ— Nat)) := tt.rewrite fun (n, _) subTt => match infos.find? n with | none => go subTt | some i => TaggedText.tag ⟨WithRpcRef.mk { ctx, lctx, info := i }⟩ (go subTt) def exprToInteractive (e : Expr) : MetaM CodeWithInfos := do let (fmt, infos) ← formatInfos e let tt := TaggedText.prettyTagged fmt let ctx := { env := ← getEnv mctx := ← getMCtx options := ← getOptions currNamespace := ← getCurrNamespace openDecls := ← getOpenDecls fileMap := arbitrary } tagExprInfos ctx (← getLCtx) infos tt def exprToInteractiveExplicit (e : Expr) : MetaM CodeWithInfos := do let (fmt, infos) ← formatExplicitInfos e let tt := TaggedText.prettyTagged fmt let ctx := { env := ← getEnv mctx := ← getMCtx options := ← getOptions currNamespace := ← getCurrNamespace openDecls := ← getOpenDecls fileMap := arbitrary } tagExprInfos ctx (← getLCtx) infos tt end Lean.Widget
37f4cf865fa49f0f9a3d9c7200f7b09839aa225e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/algebra/group_power/lemmas.lean
41c7d40f74f870c0fa613acf5a7a974060dc89c3
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,639
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 algebra.group_power.basic import algebra.invertible import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ 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β‚‚} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : βˆ€ n : β„•, n β€’β„• (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n β€’β„• (1 : A), zero_nsmul _, Ξ» _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : β„•) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : βˆ€ (a : A) (n : β„•), (list.repeat a n).sum = n β€’β„• a := @list.prod_repeat (multiplicative A) _ @[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 instance invertible_pow (m : M) [invertible m] (n : β„•) : invertible (m ^ n) := { inv_of := β…Ÿ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : β„•) [invertible (m ^ n)] : β…Ÿ(m ^ n) = β…Ÿm ^ n := @invertible_unique M _ (m ^ n) (m ^ n) rfl β€Ή_β€Ί (invertible_pow m n) lemma is_unit.pow {m : M} (n : β„•) : is_unit m β†’ is_unit (m ^ n) := Ξ» ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : β„•) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : β„•) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact nat.sub_add_cancel (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : β„•) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end end monoid theorem nat.nsmul_eq_mul (m n : β„•) : m β€’β„• n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : β„€) : n β€’β„€ (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : βˆ€ n : β„€, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : βˆ€ (a : A) (i : β„€), (i + 1) β€’β„€ a = i β€’β„€ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : β„€) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : β„€) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : β„€) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : β„€) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : βˆ€ (a : A) (i j : β„€), (i + j) β€’β„€ a = i β€’β„€ a + j β€’β„€ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : β„€) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : β„€) (a : A) : (m - n) β€’β„€ a = m β€’β„€ a - n β€’β„€ a := by simpa only [sub_eq_add_neg] using @gpow_sub (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 := int.induction_on n (by simp) (Ξ» n ihn, by simp [mul_add, gpow_add, ihn]) (Ξ» n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) 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, gpow_bit0, gpow_one] theorem bit1_gsmul : βˆ€ (a : A) (n : β„€), bit1 n β€’β„€ a = n β€’β„€ a + n β€’β„€ a + a := @gpow_bit1 (multiplicative A) _ @[simp] 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 _ _)] @[simp] 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 @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : β„€) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : β„€} (hk : (0:β„€) < k) : 0 < k β€’β„€ a := begin lift k to β„• using int.le_of_lt hk, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : β„€} (ha : 0 ≀ a) (h : n ≀ m) : n β€’β„€ a ≀ m β€’β„€ a := calc n β€’β„€ a = n β€’β„€ a + 0 : (add_zero _).symm ... ≀ n β€’β„€ a + (m - n) β€’β„€ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m β€’β„€ a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : β„€} (ha : 0 < a) (h : n < m) : n β€’β„€ a < m β€’β„€ a := calc n β€’β„€ a = n β€’β„€ a + 0 : (add_zero _).symm ... < n β€’β„€ a + (m - n) β€’β„€ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m β€’β„€ a : by { rw [← add_gsmul], simp } lemma abs_nsmul {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (n : β„•) (a : Ξ±) : abs (n β€’β„• a) = n β€’β„• abs a := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_gsmul {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (n : β„€) (a : Ξ±) : abs (n β€’β„€ a) = (abs n) β€’β„€ abs a := begin by_cases n0 : 0 ≀ n, { lift n to β„• using n0, simp only [abs_nsmul, coe_nat_abs, gsmul_coe_nat] }, { lift (- n) to β„• using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n β€’β„€ a), ← neg_gsmul, ← abs_neg n, ← h], convert abs_nsmul m _, simp only [coe_nat_abs, gsmul_coe_nat] }, end lemma abs_add_eq_add_abs_le {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] {a b : Ξ±} (hle : a ≀ b) : abs (a + b) = abs a + abs b ↔ (0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0) := begin by_cases a0 : 0 ≀ a; by_cases b0 : 0 ≀ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : Ξ±) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (abs (a + b) = -a + b ↔ b ≀ 0) ↔ (abs (a + b) = abs a + abs b ↔ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, Ξ» h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≀ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : Ξ±) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {Ξ± : Type*} [linear_ordered_add_comm_group Ξ±] (a b : Ξ±) : abs (a + b) = abs a + abs b ↔ (0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0) := begin by_cases ab : a ≀ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≀ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : β„€} (ha : 0 < a) : n β€’β„€ a ≀ m β€’β„€ a ↔ n ≀ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : β„€} (ha : 0 < a) : n β€’β„€ a < m β€’β„€ a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : β„•} (ha : 0 < a) : n β€’β„• a ≀ m β€’β„• a ↔ n ≀ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : β„•} (ha : 0 < a) : n β€’β„• a < m β€’β„• a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : β„•) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A β†’ with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : β„•) : n β€’β„• a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : β„•) (a : R) : n β€’β„• a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : β„•) : n β€’β„• (a * b) = a * (n β€’β„• b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : β„•) : n β€’β„• (a * b) = n β€’β„• a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[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 [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 [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, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : βˆ€ n, n β€’β„€ a = n * a | (n : β„•) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ β€’β„• _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : β„€) : n β€’β„€ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] 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] section ordered_semiring variable [ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≀ a * a` and `0 ≀ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≀ a * a) (Hsqr' : 0 ≀ (1 + a) * (1 + a)) (H : 0 ≀ 2 + a) : βˆ€ (n : β„•), 1 + (n : R) * a ≀ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≀ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsqr H)) Hsqr, calc 1 + (↑(n + 2) : R) * 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 [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≀ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsqr' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] 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_lt_pow_iff_of_lt_one {a : R} {n m : β„•} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (Ξ» (n : order_dual β„•), a ^ (id n : β„•)) := Ξ» m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end 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 ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : βˆ€ n : β„•, 0 ≀ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≀ r) := begin have : 0 ≀ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (Ξ» h, or.inl h.symm) (Ξ» hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : β„•} @[simp] lemma abs_pow (a : R) (n : β„•) : abs (a ^ n) = abs a ^ n := abs_hom.to_monoid_hom.map_pow a n @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ Ξ» h', not_le.2 h $ pow_nonneg h' _, Ξ» h, mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≀ a ^ bit1 n ↔ 0 ≀ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≀ 0 ↔ a ≀ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff theorem pow_even_nonneg (a : R) (hn : even n) : 0 ≀ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k theorem pow_even_pos (ha : a β‰  0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k theorem pow_odd_nonneg (ha : 0 ≀ a) (hn : odd n) : 0 ≀ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonneg_iff.mpr ha theorem pow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_pos_iff.mpr ha theorem pow_odd_nonpos (ha : a ≀ 0) (hn : odd n) : a ^ n ≀ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha theorem pow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma strict_mono_pow_bit1 (n : β„•) : strict_mono (Ξ» a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : β„•`, `-2 ≀ a`. -/ theorem one_add_mul_le_pow (H : -2 ≀ a) (n : β„•) : 1 + (n : R) * a ≀ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≀ a) (n : β„•) : 1 + (n : R) * (a - 1) ≀ a ^ n := have -2 ≀ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : β„•) : (n : K) ≀ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≀ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : β„•) : (n : K) ≀ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_pow_two (u : units β„€) : u ^ 2 = 1 := (pow_two u).symm β–Έ units_mul_self u 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] @[simp] lemma nat_abs_pow_two (x : β„€) : (x.nat_abs ^ 2 : β„€) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] lemma abs_le_self_pow_two (a : β„€) : (int.nat_abs a : β„€) ≀ a ^ 2 := by { rw [← int.nat_abs_pow_two a, pow_two], norm_cast, apply nat.le_mul_self } lemma le_self_pow_two (b : β„€) : b ≀ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_pow_two _) end int 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_nsmul] } } /-- 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, zero_nsmul x, Ξ» m n, add_nsmul _ _ _⟩, inv_fun := Ξ» f, f 1, left_inv := one_nsmul, right_inv := Ξ» f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- 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_int $ one_gsmul (f 1) } 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 @[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative β„€) : gpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative β„€ β†’* G) : (gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : β„•) : multiples_hom A x n = n β€’β„• x := rfl @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : β„• β†’+ A) : (multiples_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : β„€) : gmultiples_hom A x n = n β€’β„€ x := rfl @[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : β„€ β†’+ A) : (gmultiples_hom A).symm f = f 1 := rfl lemma monoid_hom.apply_mnat [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] @[ext] lemma monoid_hom.ext_mnat [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 [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative β„€ β†’* M) (n : multiplicative β„€) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mint [group M] ⦃f g : multiplicative β„€ β†’* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ Ξ» n, by rw [f.apply_mint, g.apply_mint, h] lemma add_monoid_hom.apply_nat [add_monoid M] (f : β„• β†’+ M) (n : β„•) : f n = n β€’β„• (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : β„€ β†’+ M) (n : β„€) : f n = n β€’β„€ (f 1) := by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative β„• β†’* M) := { map_mul' := Ξ» a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative β„€ β†’* G) := { map_mul' := Ξ» a b, monoid_hom.ext $ by simp [mul_gpow], ..gpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (β„• β†’+ A) := { map_add' := Ξ» a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom [add_comm_group A] : A ≃+ (β„€ β†’+ A) := { map_add' := Ξ» a b, add_monoid_hom.ext $ by simp [gsmul_add], ..gmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative β„•) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative β„• β†’* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative β„€) : gpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative β„€ β†’* G) : (gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : β„•) : multiples_add_hom A x n = n β€’β„• x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : β„• β†’+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : β„€) : gmultiples_add_hom A x n = n β€’β„€ x := rfl @[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : β„€ β†’+ A) : (gmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : β„•) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : β„•) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : β„•) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : βˆ€ m : β„€, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : β„•) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : β„€) : semiconj_by a ((m : β„€) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : β„€) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : β„€) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : β„•) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : β„•) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : β„•) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : β„•) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : β„•) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : β„•) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : β„€) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : β„€) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : β„€) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : β„€) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : β„€) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : β„€) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative β„•) (b : β„•) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : β„•) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative β„€) (b : β„•) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative β„€) (b : β„€) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : β„€) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : β„•) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : β„•) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : β„•) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mα΅’α΅–) (n : β„•) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
addf2527dca53b4362a17c8a22ba97f60fe5d38d
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/combinatorial_lemma/lem97.lean
4992df83fcf79e7f8a3293377c81bd8bd978132b
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,985
lean
import algebra.group.basic import analysis.convex.cone import linear_algebra.dual import algebra.ordered_ring import ring_theory.finiteness import linear_algebra.free_module import for_mathlib.Gordan /-! # Lemma 9.7 of [Analytic] In this file we state and prove 9.7 of [Analytic]. The proof in the pdf is short, but combinatorics can be fiddly. However it is almost certain that this file could be a lot shorter. -/ open_locale nnreal big_operators classical variables {Ξ› : Type*} [add_comm_group Ξ›] variable {ΞΉ : Type*} noncomputable theory open classical subtype function embedding /-- A technical auxiliary lemma used in the proof of `lem97_pos`. -/ lemma aux_1 {N : β„•} {l : ΞΉ β†’ Ξ›} {Sβ‚€ : finset (Ξ› β†’+ β„€)} (hSβ‚€ : submodule.span β„• ↑Sβ‚€ = explicit_dual_set l) : let ψ : ({x // x ∈ Sβ‚€} β†’ fin N) β†’ Ξ› β†’+ β„€ := Ξ» (y : {x // x ∈ Sβ‚€} β†’ fin N), βˆ‘ (s : {x // x ∈ Sβ‚€}) in Sβ‚€.attach, (y s).val β€’ s.val, B : finset (Ξ› β†’+ β„€) := finset.image ψ finset.univ in βˆ€ (b : Ξ› β†’+ β„€), b ∈ B β†’ b ∈ explicit_dual_set l := begin intros ψ B b hb, rcases finset.mem_image.mp hb with ⟨y, ⟨hy₁, rfl⟩⟩, rw [← hSβ‚€], apply mem_span_finset.mpr, refine ⟨λ x : (Ξ› β†’+ β„€), if H: x ∈ Sβ‚€ then (y ⟨x, H⟩ : β„•) else 0, _⟩, rw ← finset.sum_attach, refine finset.sum_congr rfl (Ξ» s hs, _), simp only [*, dif_pos, dite_eq_ite, val_eq_coe, if_true, finset.coe_mem, finset.mk_coe] end /-- A technical auxiliary lemma used in the proof of `lem97_pos`. -/ lemma aux_2 {N : β„•} (hN : 0 < N) {l : ΞΉ β†’ Ξ›} {Sβ‚€ : finset (Ξ› β†’+ β„€)} (hSβ‚€ : submodule.span β„• ↑Sβ‚€ = explicit_dual_set l) {f r : (Ξ› β†’+ β„€) β†’ β„•} : let Y : Type u_1 := {x // x ∈ Sβ‚€} β†’ fin N, ψ : Y β†’ Ξ› β†’+ β„€ := Ξ» (y : Y), βˆ‘ (s : {x // x ∈ Sβ‚€}) in Sβ‚€.attach, (y s).val β€’ s.val, B : finset (Ξ› β†’+ β„€) := finset.image ψ finset.univ, g : (Ξ› β†’+ β„€) β†’ fin N := Ξ» (i : Ξ› β†’+ β„€), ⟨f i % N, nat.mod_lt _ hN⟩, x' : Ξ› β†’+ β„€ := βˆ‘ (i : Ξ› β†’+ β„€) in Sβ‚€, (g i).val β€’ i in f = ↑g + N β€’ r β†’ x' = βˆ‘ (i : Ξ› β†’+ β„€) in Sβ‚€, (g i).val β€’ i β†’ x' ∈ B β†’ βˆ€ (i : ΞΉ), x' (l i) ≀ (β‡‘βˆ‘ (i : Ξ› β†’+ β„€) in Sβ‚€, f i β€’ i) (l i) := begin intros Y ψ B g x' hr hx' H i, dsimp [x'], rw [sub_nonpos.symm, sub_eq_add_neg, ← add_monoid_hom.neg_apply, ← finset.sum_neg_distrib, add_monoid_hom.finset_sum_apply, add_monoid_hom.finset_sum_apply, ← finset.sum_add_distrib], swap, apply_instance, simp only [← add_monoid_hom.add_apply, ← nsmul_eq_smul, ← gsmul_coe_nat, ← neg_gsmul, gsmul_eq_smul, ← add_smul], simp only [add_monoid_hom.add_apply, add_monoid_hom.smul_apply, pi.add_apply, pi.neg_apply, int.coe_nat_mod, pi.smul_apply, add_monoid_hom.neg_apply], apply finset.sum_nonpos, intros z hz, replace hz : z ∈ explicit_dual_set l, { rw [← submodule.span_singleton_le_iff_mem, ← hSβ‚€], exact submodule.span_mono (set.singleton_subset_iff.mpr hz) }, replace hz : 0 ≀ z (l i) := rfl.mpr hz i, simp only [- add_neg_le_iff_le_add', tactic.ring.add_neg_eq_sub, smul_sub], rw sub_smul, rw [← int.coe_nat_mod, sub_le_iff_le_add, zero_add], simp only [has_scalar.smul, gsmul_int_int], exact (mul_le_mul_of_nonneg_right (int.coe_nat_le.mpr (nat.mod_le (f z) N)) hz), end /-- A technical auxiliary lemma used in the proof of `lem97_pos`. -/ lemma aux_3 {N : β„•} (hN : 0 < N) {l : ΞΉ β†’ Ξ›} {Sβ‚€ : finset (Ξ› β†’+ β„€)} (hSβ‚€ : submodule.span β„• ↑Sβ‚€ = explicit_dual_set l) : let Y : Type u_1 := {x // x ∈ Sβ‚€} β†’ fin N, ψ : Y β†’ Ξ› β†’+ β„€ := Ξ» (y : Y), βˆ‘ (s : {x // x ∈ Sβ‚€}) in Sβ‚€.attach, (y s).val β€’ s.val, B : finset (Ξ› β†’+ β„€) := finset.image ψ finset.univ in βˆ€ (x : Ξ› β†’+ β„€), x ∈ explicit_dual_set l β†’ (βˆƒ (x' : Ξ› β†’+ β„€) (H : x' ∈ B) (y : Ξ› β†’+ β„€), x = N β€’ y + x' ∧ βˆ€ (i : ΞΉ), x' (l i) ≀ x (l i)) := begin intros Y ψ B x hx, rw [← hSβ‚€, mem_span_finset] at hx, rcases hx with ⟨f, rfl⟩, let g : (Ξ› β†’+ β„€) β†’ (fin N) := (Ξ» i, ⟨f i % N, nat.mod_lt (f i) hN⟩), obtain ⟨r, hr⟩ : βˆƒ (r : (Ξ› β†’+ β„€) β†’ β„•), f = ↑g + N β€’ r, { use Ξ» x, (f x - g x) / N, refine funext (Ξ» z, (_ : f z = g z + N * ((f z - f z % N) / N))), rw [nat.mul_div_cancel' (nat.dvd_sub_mod _)], exact (nat.add_sub_cancel' (nat.mod_le _ _)).symm }, set x' := βˆ‘ (i : Ξ› β†’+ β„€) in Sβ‚€, (g i).val β€’ i with hx', have H : x' ∈ B, { refine finset.mem_image.mpr ⟨g ∘ val, finset.mem_univ _, _⟩, convert finset.sum_attach, refl }, refine ⟨x', _, βˆ‘ (i : Ξ› β†’+ β„€) in Sβ‚€, r i β€’ i, _, _⟩, { refine finset.mem_image.mpr ⟨g ∘ val, finset.mem_univ _, _⟩, convert finset.sum_attach, refl }, { rw [hr, finset.smul_sum, ← finset.sum_add_distrib], simp_rw [← smul_assoc, ← add_smul, add_comm (N β€’ _) _], refl }, exact aux_2 hN hSβ‚€ hr hx' H, end /-- The proof of Lemma 9.7 of `Analytic.pdf` under the additional assumption that (in the notation of the paper) Ξ»α΅’(x)β‰₯0 for all i. -/ lemma lem97_pos [module.finite β„€ Ξ›] [module.free β„€ Ξ›] [fintype ΞΉ] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) : βˆƒ B : finset (Ξ› β†’+ β„€), (βˆ€ b ∈ B, b ∈ (explicit_dual_set l)) ∧ βˆ€ x : Ξ› β†’+ β„€, x ∈ (explicit_dual_set l) β†’ βˆƒ (x' ∈ B) (y : Ξ› β†’+ β„€), x = N β€’ y + x' ∧ βˆ€ i, x' (l i) ≀ x (l i) := begin obtain ⟨Sβ‚€, hSβ‚€βŸ© := explicit_gordan l, let Y : Type* := { x // x ∈ Sβ‚€ } β†’ (fin N), let ψ : Y β†’ Ξ› β†’+ β„€ := Ξ» y : Y, βˆ‘ s in finset.attach Sβ‚€, (y s).1 β€’ s.val, exact ⟨finset.image ψ finset.univ, aux_1 hSβ‚€, aux_3 hN hSβ‚€βŸ©, end section sign_vectors def nonzero_sign : β„€ β†’ units β„€ := Ξ» n, if 0 ≀ n then 1 else -1 def sign_vectors (ΞΉ : Type*) := (ΞΉ β†’ units β„€) instance sign_vectors_inhabited : inhabited (sign_vectors ΞΉ) := ⟨(Ξ» i, 1)⟩ def fintype_sign_vectors [fintype ΞΉ] : fintype (sign_vectors ΞΉ) := pi.fintype /-- Given a list l of elements of Ξ› and a functional x, (pos_vector l x) is the sign-vector of the values of x (l i). -/ def pos_vector (l : ΞΉ β†’ Ξ›) (x : Ξ› β†’+ β„€) : sign_vectors ΞΉ := Ξ» i, nonzero_sign (x (l i)) instance smul_signs : has_scalar (sign_vectors ΞΉ) (ΞΉ β†’ Ξ›) := { smul := Ξ» Ξ΅ l i, (Ξ΅ i : β„€) β€’ l i } lemma pos_vector_nonneg (l : ΞΉ β†’ Ξ›) (x : Ξ› β†’+ β„€) (j : ΞΉ) : 0 ≀ x ((pos_vector l x β€’ l) j) := begin rw [pos_vector, nonzero_sign], simp only [has_scalar.smul, add_monoid_hom.map_gsmul, gsmul_int_int], split_ifs, { convert h, simp }, { simp, linarith } end lemma smul_to_explicit_dual_set (l : ΞΉ β†’ Ξ›) (x : Ξ› β†’+ β„€) : x ∈ (explicit_dual_set ((pos_vector l x) β€’ l)) := Ξ» j, pos_vector_nonneg l x j lemma pos_vector_id_if_nonneg (l : ΞΉ β†’ Ξ›) (x : Ξ› β†’+ β„€) (i : ΞΉ) : 0 ≀ x (l i) β†’ (pos_vector l x β€’ l) i = l i := begin intro hx, simp only [pos_vector, nonzero_sign, has_scalar.smul, id.def], rw [if_pos hx],-- units.coe_one, one_gsmul], simp, end lemma pos_vector_neg_if_neg (l : ΞΉ β†’ Ξ›) (x : Ξ› β†’+ β„€) (i : ΞΉ) : x (l i) < 0 β†’ ((pos_vector l x) β€’ l) i = - l i := begin intro hx, simp only [pos_vector, nonzero_sign, has_scalar.smul, id.def], rw [if_neg (not_le.mpr hx)], simp, end end sign_vectors /-- Given a list l, a vector of signs Ξ΅ (and a positive integer N), (pos_A l Ξ΅) is a finite set of functionals satisfying the requirements of Lemma 9.7 of [Analytic] with respect to all functionals which are positive on all ((Ξ΅ β€’ l) i)'s. Its existence was established in lem97_pos above. -/ def pos_A [fintype ΞΉ] [module.finite β„€ Ξ›] [module.free β„€ Ξ›] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) (Ξ΅ : sign_vectors ΞΉ) : finset (Ξ› β†’+ β„€) := some (lem97_pos N hN (Ξ΅ β€’ l)) lemma posA_to_explicit [fintype ΞΉ] [module.finite β„€ Ξ›] [module.free β„€ Ξ›] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) (Ξ΅ : sign_vectors ΞΉ) (x' : Ξ› β†’+ β„€) (H : x' ∈ pos_A N hN l Ξ΅) : x' ∈ explicit_dual_set (Ξ΅ β€’ l) := (some_spec (lem97_pos N hN (Ξ΅ β€’ l))).1 x' H lemma exists_good_pair [fintype ΞΉ] [module.finite β„€ Ξ›] [module.free β„€ Ξ›] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) (Ξ΅ : sign_vectors ΞΉ) (x : Ξ› β†’+ β„€) (H : x ∈ (explicit_dual_set (Ξ΅ β€’ l))) : βˆƒ x' y : (Ξ› β†’+ β„€), x' ∈ pos_A N hN l Ξ΅ ∧ x = N β€’ y + x' ∧ βˆ€ i, x' ((Ξ΅ β€’ l) i) ≀ x ((Ξ΅ β€’ l) i) := begin obtain ⟨x', hx', ⟨y, hy⟩⟩ := (some_spec (lem97_pos N hN (Ξ΅ β€’ l))).2 x H, exact ⟨x', y, hx', hy⟩, end /- The remainder of this file is proofs of two versions of Lemma 9.7, namely `lem97` and `lem97'`. -/ /-- Lemma 9.7 of [Analytic]. See also the (mathematically indistinguishable) variant `lem97'`. -/ lemma lem97 [fintype ΞΉ] [module.finite β„€ Ξ›] [module.free β„€ Ξ›] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) : βˆƒ A : finset (Ξ› β†’+ β„€), βˆ€ x : Ξ› β†’+ β„€, βˆƒ (x' ∈ A) (y : Ξ› β†’+ β„€), x = N β€’ y + x' ∧ βˆ€ i, (0 ≀ x' (l i) ∧ 0 ≀ (x - x') (l i)) ∨ (x' (l i) ≀ 0 ∧ (x - x') (l i) ≀ 0) := begin refine ⟨(@finset.univ (sign_vectors ΞΉ) (fintype_sign_vectors)).bUnion (pos_A N hN l), Ξ» x, _⟩, have hx : x ∈ (explicit_dual_set ((pos_vector l x) β€’ l)) := smul_to_explicit_dual_set l x, obtain ⟨x', y, mem_x', hy, hx'⟩ := exists_good_pair N hN l (pos_vector l x) x hx, refine ⟨x', _, _⟩, { refine finset.mem_bUnion.mpr ⟨pos_vector l x, _, mem_x'⟩, simp only [finset.mem_univ] }, { refine ⟨y, hy, Ξ» i, _⟩, have h_pos' : x' ∈ explicit_dual_set ((pos_vector l x) β€’ l) := posA_to_explicit N hN l (pos_vector l x) x' mem_x', replace h_pos' : 0 ≀ x' (((pos_vector l x) β€’ l) i) := h_pos' _, by_cases h_pos : 0 ≀ x (l i), { have h_posvect_id : ((pos_vector l x) β€’ l) i = l i := pos_vector_id_if_nonneg l x i h_pos, replace h_pos' : 0 ≀ x' (l i) := h_pos'.trans (le_of_eq (congr_arg x' h_posvect_id)), refine or.inl ⟨h_pos', _⟩, rw ← h_posvect_id, simp only [sub_nonneg, add_monoid_hom.sub_apply, hx'] }, { specialize hx' i, have h_posvect_neg : ((pos_vector l x) β€’ l) i = - l i := pos_vector_neg_if_neg l x i (not_le.mp h_pos), rw [h_posvect_neg] at *, replace h_pos' : x' (l i) ≀ 0, { rw [x'.map_neg] at h_pos', exact neg_nonneg.mp h_pos' }, refine or.inr ⟨h_pos', _⟩, simpa only [neg_le_neg_iff, add_monoid_hom.sub_apply, add_monoid_hom.map_neg, sub_nonpos] using hx' } } end lemma os.monotone_pow {R : Type*} [ordered_semiring R] (k : β„•) (R0 : βˆ€ r : R, 0 ≀ r) : monotone (Ξ» n : R, n ^ k) := Ξ» x y xy, pow_le_pow_of_le_left (R0 _) xy k lemma nat.monotone_pow (k : β„•) : monotone (Ξ» n : β„•, n ^ k) := os.monotone_pow k nat.zero_le --Ξ» x y xy, pow_le_pow_of_le_left x.zero_le xy k lemma nat.strict_mono_pow {k : β„•} (k0 : 0 < k) : strict_mono (Ξ» n : β„•, n ^ k) := Ξ» x y xy, pow_lt_pow_of_lt_left xy x.zero_le k0 lemma nat.injective_pow {k : β„•} (k0 : 0 < k) : function.injective (Ξ» n : β„•, n ^ k) := injective_of_increasing (<) (<) _ (nat.strict_mono_pow k0) lemma int.nat_abs_eq_self (a : β„€) : (a.nat_abs : β„€) = a ↔ 0 ≀ a := ⟨λ h, by { rw ← h, exact int.coe_zero_le a.nat_abs }, Ξ» h, int.nat_abs_of_nonneg h⟩ lemma abs_add_eq_iff_abs_mul_eq {R : Type*} [linear_ordered_comm_ring R] {a b : R} : abs (a + b) = abs a + abs b ↔ abs (a * b) = a * b := begin refine ⟨λ h, _, Ξ» h, _⟩, { simpa [abs_mul, eq_comm, add_pow_two, mul_assoc] using (congr_arg (Ξ» x : R, x ^ 2) h) }, { rcases (mul_nonneg_iff.mp (abs_eq_self.mp h)) with ⟨a0, b0⟩ | ⟨a0, b0⟩, { rw [abs_of_nonneg a0, abs_of_nonneg b0, abs_of_nonneg (add_nonneg a0 b0)] }, { rw [abs_of_nonpos a0, abs_of_nonpos b0, abs_of_nonpos (add_nonpos a0 b0), neg_add] } } end lemma nat_abs_add_eq_iff_nat_abs_mul_eq {a b : β„€} : int.nat_abs (a + b) = a.nat_abs + b.nat_abs ↔ ((a * b).nat_abs : β„€) = a * b := begin rw [← int.abs_eq_nat_abs, ← abs_add_eq_iff_abs_mul_eq, int.abs_eq_nat_abs, int.abs_eq_nat_abs, int.abs_eq_nat_abs], norm_cast, end lemma nat_abs_add_eq_iff (a b : β„€) : int.nat_abs (a + b) = int.nat_abs a + int.nat_abs b ↔ (0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0) := nat_abs_add_eq_iff_nat_abs_mul_eq.trans ((int.nat_abs_eq_self _).trans mul_nonneg_iff) -- rw [nat_abs_add_eq_iff_nat_abs_mul_eq, int.nat_abs_eq_self],exact mul_nonneg_iff, lemma nat_smul_nat_abs (a : β„•) (b : β„€) : a β€’ b.nat_abs = (a β€’ b).nat_abs := begin nth_rewrite 0 [← int.nat_abs_of_nat a], rw [smul_eq_mul, ← int.nat_abs_mul, ← smul_eq_mul], apply congr_arg, rw [algebra.id.smul_eq_mul, nsmul_eq_mul, int.nat_cast_eq_coe_nat], end /-- Lemma 9.7 of [Analytic]. See also the (mathematically indistinguishable) variant `lem97`. -/ lemma lem97' [fintype ΞΉ] [module.finite β„€ Ξ›] [module.free β„€ Ξ›] (N : β„•) (hN : 0 < N) (l : ΞΉ β†’ Ξ›) : βˆƒ A : finset (Ξ› β†’+ β„€), βˆ€ x : Ξ› β†’+ β„€, βˆƒ (x' ∈ A) (y : Ξ› β†’+ β„€), x = N β€’ y + x' ∧ βˆ€ i, (x (l i)).nat_abs = N * (y (l i)).nat_abs + (x' (l i)).nat_abs := begin obtain ⟨A, hA⟩ := lem97 N hN l, refine ⟨A, Ξ» x, _⟩, rcases hA x with ⟨x', mem_x', y, rfl, hx'⟩, refine ⟨x', mem_x', y, rfl, Ξ» i, _⟩, specialize hx' i, rw [← nat_abs_add_eq_iff, add_sub_cancel, add_monoid_hom.coe_smul, pi.smul_apply] at hx', rw [add_monoid_hom.add_apply, add_monoid_hom.coe_smul, pi.smul_apply, add_comm, hx', add_comm, add_left_inj, ← nat_smul_nat_abs, smul_eq_mul], end -- TODO -- #lint- -- /- The `doc_blame` linter reports: -/ -- /- DEFINITIONS ARE MISSING DOCUMENTATION STRINGS: -/ -- #print nonzero_sign /- def missing doc string -/ -- #print sign_vectors /- def missing doc string -/ -- #print fintype_sign_vectors /- def missing doc string -/
8c613dbdfbe763108df51f7a85fa5b7a1dd878e8
fe84e287c662151bb313504482b218a503b972f3
/src/group_theory/self_map.lean
5298680e1804dce1d9394eb7f8376d4ffadbc189
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
1,968
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland We define the monoid of self-maps of a type, and show that monoid homomorphisms `M β†’ (self_map X)` give actions of `M` on `X`. -/ import algebra.group group_theory.group_action variable (T : Type*) def self_map (T : Type*) : Type* := (T β†’ T) instance [fintype T] [decidable_eq T] : fintype (self_map T) := by {dsimp[self_map],apply_instance} instance [fintype T] [decidable_eq T] : decidable_eq (self_map T) := by {dsimp[self_map],apply_instance} instance self_map_monoid (T : Type*) : monoid (self_map T) := { mul := Ξ» f g x, f (g x), mul_assoc := Ξ» f g h, by {funext,refl}, one := Ξ» x, x, one_mul := Ξ» f, by {funext,refl}, mul_one := Ξ» f, by {funext,refl}, } namespace self_map @[simp] lemma one_app (t : T) : (1 : self_map T) t = t := rfl @[simp] lemma mul_app (f g : self_map T) (t : T) : (f * g) t = f (g t) := rfl def units_equiv : units (self_map T) ≃ equiv.perm T := { to_fun := Ξ» u, equiv.mk u.val u.inv (begin intro x, change (u.inv * u.val) x = x, rw[u.inv_val], refl, end) (begin intro x, change (u.val * u.inv) x = x, rw[u.val_inv], refl, end), inv_fun := Ξ» v, units.mk v.to_fun v.inv_fun (by {funext,exact v.right_inv x}) (by {funext,exact v.left_inv x}), left_inv := Ξ» u,begin ext,refl, end, right_inv := Ξ» v,begin ext,refl end } variable {T} instance : mul_action (self_map T) T := { smul := Ξ» f x, f x, one_smul := Ξ» x, rfl, mul_smul := Ξ» f g x, rfl } def mul_action_of_hom {M X : Type*} [monoid M] (act : M β†’* self_map X) : mul_action M X := @mul_action.mk M X _ ⟨λ m x, (act m) x⟩ (Ξ» x,by { change (act 1) x = x, rw[act.map_one], refl }) (Ξ» m n x,by {change act (m * n) x = act m (act n x), rw[act.map_mul], refl}) end self_map