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
3486e050256b444d9e1baac914b43a638f80cb45
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/nat/exp.lean
c0d1cc177eb77a361bf7252e13d9d583d5cf533e
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,792
lean
/- This module defines an exponentiation function where the exponent is a natural number, and the base is a monoid. It uses an efficient sum of squares method to support large exponents. -/ import .simplify_eq universe u namespace nat section exp parameter {α : Type u} parameter [inst : monoid α] include inst def exp.f (x : α) (b:bool) (n : ℕ) (r:α) : α := if b then x * r * r else r * r def exp (x : α) (n : ℕ) : α := nat.binary_rec 1 (exp.f x) n theorem exp_zero : ∀ (x : α) , exp x 0 = 1 := begin intro x, unfold exp, unfold binary_rec, simp [eq.mpr], end theorem exp_one (x : α) : exp x 1 = x := begin unfold exp, unfold binary_rec, simp [exp.f, eq.mpr], dsimp [div2_one], unfold binary_rec, simp [eq.mpr], rw if_pos, constructor, end theorem exp_bit (x : α) (b:bool) (n:ℕ) : exp x (bit b n) = (if b then x else 1) * exp x n * exp x n := begin transitivity, unfold1 exp, rw binary_rec_eq, simp [exp.f], cases b; simp [exp], rw if_neg, rw if_neg, simp, contradiction, contradiction, rw if_pos, rw if_pos, constructor, constructor, dsimp [exp.f], rw if_neg, simp, contradiction, end theorem exp_bit0 (x : α) (n:ℕ) : exp x (bit0 n) = exp x n * exp x n := begin have p := exp_bit x ff n, simp [bit] at p, rw if_neg at p, simp at p, exact p, contradiction, end theorem exp_bit1 (x : α) (n:ℕ) : exp x (bit1 n) = x * (exp x n * exp x n) := begin have p := exp_bit x tt n, simp [bit, mul_assoc] at p, exact p, end theorem exp_succ_identities : ∀(x:α)(n:ℕ), x * exp x n = exp x (succ n) ∧ exp x n * x = exp x (succ n) := begin intros x n, revert x, revert n, apply @nat.binary_rec (λ(n:ℕ), (∀(x : α), x * exp x n = exp x (succ n) ∧ exp x n * x = exp x (succ n))), { simp [exp_one, exp_zero], }, { intros b n ind x, have ind_left := λx, (ind x).left, have ind_right := λx, (ind x).right, cases b, case tt { simp only [ bit, cond ], rw [ nat.succ_bit1, exp_bit0, exp_bit1 ], apply and.intro, { transitivity, rw [← mul_assoc x (exp x n), ind_left, ← ind_right], -- Collect first successor rw [mul_assoc, ind_left], -- Collect second rw [← mul_assoc, ind_left], }, { rw [mul_assoc, mul_assoc, ind_right], rw [← mul_assoc, ind_left], } }, case ff { simp only [bit, cond], rw [← nat.bit1_eq_succ_bit0, exp_bit0, exp_bit1], apply and.intro, { trivial, }, { -- Move extra x from right to left. rw [mul_assoc, ind_right], rw [← ind_left, ← mul_assoc, ind_right, ← ind_left], rw [mul_assoc], } } } end end exp end nat
daa5c1b2dca7121cd6ed0e8292caa9d1901628d3
500f65bb93c499cd35c3254d894d762208cae042
/src/category/traversable/basic.lean
ea0860feee26638ea9f00c0eb1cd9cf01ea10b07
[ "Apache-2.0" ]
permissive
PatrickMassot/mathlib
c39dc0ff18bbde42f1c93a1642f6e429adad538c
45df75b3c9da159fe3192fa7f769dfbec0bd6bda
refs/heads/master
1,623,168,646,390
1,566,940,765,000
1,566,940,765,000
115,220,590
0
1
null
1,514,061,524,000
1,514,061,524,000
null
UTF-8
Lean
false
false
5,608
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.cache import category.applicative /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html Traversable collections are a generalization of functors. Whereas functors (such as `list`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email -> io response` that takes an email address, sends an email and wait for a response. If we have a list `guests : list email`, using calling `invite` using `map` gives us the following: `map invite guests : list (io response)`. It is not what we need. We need something of type `io (list response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : io (list response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `io` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: https://en.wikibooks.org/wiki/Haskell/Traversable ## Main definitions * `traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * is_lawful_traversable - laws ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at http://www.soi.city.ac.uk/~ross/papers/Applicative.html. * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator. * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at http://arxiv.org/pdf/1202.2919. Synopsis -/ open function (hiding comp) universes u v w section applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] structure applicative_transformation : Type (max (u+1) v w) := (app : ∀ α : Type u, F α → G α) (preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x) (preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y) end applicative_transformation namespace applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] instance : has_coe_to_fun (applicative_transformation F G) := { F := λ _, Π {α}, F α → G α, coe := λ a, a.app } variables {F G} variables (η : applicative_transformation F G) @[functor_norm] lemma preserves_pure : ∀ {α} (x : α), η (pure x) = pure x := η.preserves_pure' @[functor_norm] lemma preserves_seq : ∀ {α β : Type u} (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y := η.preserves_seq' @[functor_norm] lemma preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by rw [← pure_seq_eq_map, η.preserves_seq]; simp with functor_norm end applicative_transformation open applicative_transformation class traversable (t : Type u → Type u) extends functor t := (traverse : Π {m : Type u → Type u} [applicative m] {α β}, (α → m β) → t α → m (t β)) open functor export traversable (traverse) section functions variables {t : Type u → Type u} variables {m : Type u → Type v} [applicative m] variables {α β : Type u} variables {f : Type u → Type u} [applicative f] def sequence [traversable t] : t (f α) → f (t α) := traverse id end functions class is_lawful_traversable (t : Type u → Type u) [traversable t] extends is_lawful_functor t : Type (u+1) := (id_traverse : ∀ {α} (x : t α), traverse id.mk x = x ) (comp_traverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α β γ} (f : β → F γ) (g : α → G β) (x : t α), traverse (comp.mk ∘ map f ∘ g) x = comp.mk (map (traverse f) (traverse g x))) (traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α), traverse (id.mk ∘ f) x = id.mk (f <$> x)) (naturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α β} (f : α → F β) (x : t α), η (traverse f x) = traverse (@η _ ∘ f) x) instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section variables {F : Type u → Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ instance : traversable list := ⟨@list.traverse⟩ end namespace sum variables {σ : Type u} variables {F : Type u → Type u} variables [applicative F] protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x end sum instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
d73ee30ffdddef6fc360dd01ca4cb71cc099f0ff
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1405.lean
47d54b7c915a42cc9201e31801d8b2053ec31eb1
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
418
lean
import data.real.basic def fn_ub (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, f x ≤ a def fn_has_ub (f : ℝ → ℝ) := ∃ a, fn_ub f a open_locale classical variable (f : ℝ → ℝ) -- BEGIN example (h : ¬ fn_has_ub f) : ∀ a, ∃ x, f x > a := begin contrapose! h, exact h end example (x : ℝ) (h : ∀ ε > 0, x ≤ ε) : x ≤ 0 := begin contrapose! h, use x / 2, split; linarith end -- END
48e3fdf1f47cb36cc713b42f53d945d58ed18e62
43390109ab88557e6090f3245c47479c123ee500
/src/M1P2/sheet_8.lean
5dec8c9ce02836be5b27f0f4d17e24bb3ddf23b7
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,113
lean
import algebra.ring algebra.group_power data.nat.prime data.nat.prime data.nat.basic data.int.modeq algebra.group_power group_theory.subgroup algebra.group data.set.basic open nat variables {R : Type*} [ring R] -- 1. (a) Suppose n > 1 is a power of a prime number. Give a formula for the number of elements in the group (Z×n ; ·), explaining your answer. -- euler totient function --ef euler_tot (n : ℕ) --theorem (ha: prime p) (n α : nat) (hp : n = p^α) : -- (b) Find natural numbers n,m such that the residue class [m]n ∈ Z×n has order 5. -- theorem sheet8_q1_b (m n : ℕ) -- *2. Show that the following sets are rings with the given binary operations. In each case, describe the units. -- (a) The set {a/b ∈ Q| b odd} ,with the usual + and · b --def s₁ : {a/b ∈ ℚ ∣ b = 2k+1} -- (b) The set of all functions f : [0,1] −→ C, with + and · given by (f₁ + f₂)(x) = f₁(x) + f₂(x), (f₁ · f₂)(x) = f₁(x)f₂(x). --def s₂ : -- (c) The set P(N) of all subsets of N, with the operations X+Y=X∪Y\X∩Y (the symmetric difference of X and Y), X·Y =X∩Y. -- 3. Suppose R is a ring and S ⊆ R. Devise a criterion which enables you to check whether S with the operations inherited from R is a ring (i.e. invent a test for being a subring). If R is a ring with unity, does your criterion imply that S is a ring with unity? √√√ -- 4. Let d ∈ Z and Q[√d] = {x+y d|x,y∈Q}. Prove that Q[√d]is a ring with the usual operations + and · in C. -- Show that every non-zero element of Q[√d]is a unit (so Q[√d] is a field). -- 5. (a) Suppose that f(x) ∈ C[x] is non-zero and has n distinct roots. Prove that deg f ≥ n. -- (b) Let f(x) ∈ R[x] be a polynomial with real coefficients. Show that if a ∈ C is a root of f(x), then its complex conjugate a is also a root of f(x). Deduce that if f(x) is an irreducible polynomial in R[x] then deg f ≤ 2. -- 6. (a) Let f(x) ∈ Q[x] be a polynomial of degree at most 3 which has no rational root. Prove that f(x) is irreducible. -- (b) Show that the polynomial f(x) = x^3 + x^2 + x + 3 is irreducible in Q[x].
defd7fac953b79b11dde7a86021a8b5f6eed0c77
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/category/Module/abelian.lean
39d78be0584d1981c2e203a2ada3563e73e64e4a
[ "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,318
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Module.kernels import algebra.category.Module.limits import category_theory.abelian.exact /-! # The category of left R-modules is abelian. Additionally, two linear maps are exact in the categorical sense iff `range f = ker g`. -/ open category_theory open category_theory.limits noncomputable theory universes v u namespace Module variables {R : Type u} [ring R] {M N : Module.{v} R} (f : M ⟶ N) /-- In the category of modules, every monomorphism is normal. -/ def normal_mono (hf : mono f) : normal_mono f := { Z := of R f.range.quotient, g := f.range.mkq, w := linear_map.range_mkq_comp _, is_limit := is_kernel.iso_kernel _ _ (kernel_is_limit _) /- The following [invalid Lean code](https://github.com/leanprover-community/lean/issues/341) might help you understand what's going on here: ``` calc M ≃ₗ[R] f.ker.quotient : (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] r.range.mkq.ker : linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm ``` -/ (linear_equiv.to_Module_iso' (linear_equiv.trans (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm (linear_equiv.trans (linear_map.quot_ker_equiv_range f) (linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm)))) $ by { ext, refl } } /-- In the category of modules, every epimorphism is normal. -/ def normal_epi (hf : epi f) : normal_epi f := { W := of R f.ker, g := f.ker.subtype, w := linear_map.comp_ker_subtype _, is_colimit := is_cokernel.cokernel_iso _ _ (cokernel_is_colimit _) (linear_equiv.to_Module_iso' /- The following invalid Lean code might help you understand what's going on here: ``` calc f.ker.subtype.range.quotient ≃ₗ[R] f.ker.quotient : submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _) ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] N : linear_equiv.of_top _ (range_eq_top_of_epi _) ``` -/ (linear_equiv.trans (linear_equiv.trans (submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _)) (linear_map.quot_ker_equiv_range f)) (linear_equiv.of_top _ (range_eq_top_of_epi _)))) $ by { ext, refl } } /-- The category of R-modules is abelian. -/ instance : abelian (Module R) := { has_finite_products := by { dsimp [has_finite_products], apply_instance }, has_kernels := by apply_instance, has_cokernels := has_cokernels_Module, normal_mono := λ X Y, normal_mono, normal_epi := λ X Y, normal_epi } variables {O : Module.{v} R} (g : N ⟶ O) open linear_map local attribute [instance] preadditive.has_equalizers_of_has_kernels theorem exact_iff : exact f g ↔ f.range = g.ker := begin rw abelian.exact_iff' f g (kernel_is_limit _) (cokernel_is_colimit _), exact ⟨λ h, le_antisymm (range_le_ker_iff.2 h.1) (ker_le_range_iff.2 h.2), λ h, ⟨range_le_ker_iff.1 $ le_of_eq h, ker_le_range_iff.1 $ le_of_eq h.symm⟩⟩ end end Module
40b6d0d00666c59190730abcab48d909a9a7cdbf
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Parser/Basic.lean
791ed6a18c5f2d4fb5b6622e70c3f5d64a777cc3
[ "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
70,098
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `parser! p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ import Lean.Data.Trie import Lean.Data.Position import Lean.Syntax import Lean.ToExpr import Lean.Environment import Lean.Attributes import Lean.Message import Lean.Compiler.InitAttr import Lean.ResolveName namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /- Return character after position `pos` -/ def getNext (input : String) (pos : Nat) : Char := input.get (input.next pos) /- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := evalPrec! max def leadPrec : Nat := evalPrec! lead def minPrec : Nat := evalPrec! min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := Std.PersistentHashMap.insert s k () /- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable insideQuot : Bool := false suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : Nat) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, we just return `s` s else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, pos, cache, err⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ def mkEOIError (s : ParserState) : ParserState := s.mkUnexpectedError "end of input" def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s => if p s.stxStack.back then s else s.mkUnexpectedError msg @[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } @[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser := ⟨andthen⟩ @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } @[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg @[inline] def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } def checkInsideQuotFn : ParserFn := fun c s => if c.insideQuot then s else s.mkUnexpectedError "unexpected syntax outside syntax quotation" @[inline] def checkInsideQuot : Parser := { info := epsilonInfo, fn := checkInsideQuotFn } def checkOutsideQuotFn : ParserFn := fun c s => if !c.insideQuot then s else s.mkUnexpectedError "unexpected syntax inside syntax quotation" @[inline] def checkOutsideQuot : Parser := { info := epsilonInfo, fn := checkOutsideQuotFn } def toggleInsideQuotFn (p : ParserFn) : ParserFn := fun c s => if c.suppressInsideQuot then p c s else p { c with insideQuot := !c.insideQuot } s @[inline] def toggleInsideQuot (p : Parser) : Parser := { info := p.info, fn := toggleInsideQuotFn p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> trailingNodeAux n p def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors else s | none => s @[inline] def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q true @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos match p c s with | ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } @[inline] def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos @[inline] def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then if iniPos == s.pos then s.restore iniSz iniPos else s else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" else manyAux p c s @[inline] def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz @[inline] def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz @[inline] def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := let sz := s.stackSize let pos := s.pos let s := p c s if s.hasError then if s.pos > pos then s else if pOpt then let s := s.restore sz pos s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete let s := s.pushSyntax Syntax.missing s.mkNode nullKind iniSz else let sz := s.stackSize let pos := s.pos let s := sep c s if s.hasError then let s := s.restore sz pos s.mkNode nullKind iniSz else parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } @[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } @[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } @[inline] def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then s.mkEOIError else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then s.mkEOIError else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then s -- "/--" doc comment is an actual token else andthenFn (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s @[inline] def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := { leading := leading, pos := startPos, trailing := trailing : SourceInfo } s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s def binNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.bsize ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk.bsize let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } tk s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := { leading := leading, trailing := trailing, pos := startPos : SourceInfo } let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) let stopPart := s.pos let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s if s.hasError then s else let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s.mkErrorAt "invalid Name literal" startPos else let stx := s.stxStack.back match stx with | Syntax.ident _ rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString]) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := match s with | ⟨stack, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn c s if s.hasError then (s.restore iniSz iniPos, none) else let stx := s.stxStack.back (s.restore iniSz iniPos, some stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, some tkc.token) else peekTokenAux c s /- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s @[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let startPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorsAt expected startPos else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos | _ => s.mkErrorsAt expected startPos def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } @[inline] def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") @[inline] def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | some { trailing := some trailing, .. } => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universes (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let startPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorAt errorMsg startPos else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos | _ => s.mkErrorAt errorMsg startPos @[inline] def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } @[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | some { trailing := some trailing, .. } => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? $ fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } @[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] @[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s @[inline] def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } @[inline] def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorAt "identifier" iniPos else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s | _ => s.mkErrorAt "identifier" iniPos @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => let node := stack.back let stack := stack.shrink startStackSize let stack := stack.push node ⟨stack, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. After executing `p`, remove `left`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (p : ParserFn) : ParserFn := fun c s => let startSize := s.stackSize match left? with | none => let s := p c s if s.hasError then s else -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s else invalidLongestMatchParser s | some left => let s := s.pushSyntax left let s := p c s if s.hasError then s else -- stack contains `[..., left, result ]` we must remove `left` if s.stackSize == startSize + 2 then -- `p` created one node, then we just remove `left` and keep it let r := s.stxStack.back let s := s.shrinkStack startSize -- remove `r` and `left` s.pushSyntax r -- add `r` back else invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let s := s.restore prevSize startPos let s := runLongestMatchParser left? p c s match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.restore prevSize prevStopPos, prevPrio) -- keep prev else (s, prio) | none, some _ => -- prev succeeded, current failed (s.restore prevSize prevStopPos, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError prevSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio) else (s.mergeErrors prevSize oldError, prio) | some _, none => -- prev failed, current succeeded let successNode := s.stxStack.back let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack (s.pushSyntax successNode, prio) -- put successNode back on the stack def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => runLongestMatchParser left? p.1.fn | p::ps => fun c s => let startSize := s.stackSize let startPos := s.pos let s := runLongestMatchParser left? p.1.fn c s if s.hasError then let s := s.shrinkStack startSize longestMatchFnAux left? startSize startPos p.2 ps c s else longestMatchFnAux left? startSize startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s @[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg @[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } @[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg @[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } @[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.pos } s } @[inline] def withoutPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => let pos := c.fileMap.toPosition s.pos p.fn { c with savedPos? := none } s } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" @[inline] def eoi : Parser := { fn := eoiFn } open Std (RBMap RBMap.empty) /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | some (Syntax.atom _ sym) => find (Name.mkSimple sym) | some (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | some (Syntax.node k _) => find k | _ => (s, []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations @[inline] def termParser (prec : Nat := 0) : Parser := categoryParser `term prec /- ============== -/ /- Antiquotations -/ /- ============== -/ /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun c s => s.pushSyntax mkNullNode } -- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> toggleInsideQuot termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. Both forms can also be used with an appended `*` to turn them into an antiquotation "splice". If `kind` is given, it will additionally be checked when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser := let kind := (kind.getD Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := let (s, stx?) := peekToken c s match stx? with | some stx@(Syntax.atom _ sym) => sym == "$" | _ => false @[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ @[inline] def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.insideQuot && c.env.contains declName then evalParserConst declName c s else p.fn c s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior let ps := tables.leadingParsers ++ ps if ps.isEmpty then s.mkError (toString kind) else let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState := let s := mkResult s iniSz -- Stack contains `[..., left, result]` -- We must remove `left` let result := s.stxStack.back let s := s.popSyntax.popSyntax s.pushSyntax result partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if ps.isEmpty && tables.trailingParsers.isEmpty then s -- no available trailing parser else let left := s.stxStack.back let iniSz := s.stackSize let iniPos := s.pos let s := trailingLoopStep tables left ps c s if s.hasError then if s.pos == iniPos then s.restore iniSz iniPos else s else let s := mkTrailingResult s iniSz trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ @[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variables {β : Type} {m : Type → Type} [Monad m] @[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b @[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) @[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
803ea9f81fc1ae5fc84728c12b0933445930c6c8
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/witt_vector/basic.lean
92143c761e0e82fda82f4c6cc55a0be81dcbfc1d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,409
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.mv_polynomial.counit import data.mv_polynomial.invertible import ring_theory.witt_vector.defs /-! # Witt vectors This file verifies that the ring operations on `witt_vector p R` satisfy the axioms of a commutative ring. ## Main definitions * `witt_vector.map`: lifts a ring homomorphism `R →+* S` to a ring homomorphism `𝕎 R →+* 𝕎 S`. * `witt_vector.ghost_component n x`: evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. This is a ring homomorphism. * `witt_vector.ghost_map`: a ring homomorphism `𝕎 R →+* (ℕ → R)`, obtained by packaging all the ghost components together. If `p` is invertible in `R`, then the ghost map is an equivalence, which we use to define the ring operations on `𝕎 R`. * `witt_vector.comm_ring`: the ring structure induced by the ghost components. ## Notation We use notation `𝕎 R`, entered `\bbW`, for the Witt vectors over `R`. ## Implementation details As we prove that the ghost components respect the ring operations, we face a number of repetitive proofs. To avoid duplicating code we factor these proofs into a custom tactic, only slightly more powerful than a tactic macro. This tactic is not particularly useful outside of its applications in this file. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ noncomputable theory open mv_polynomial function open_locale big_operators variables {p : ℕ} {R S T : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] [comm_ring T] variables {α : Type*} {β : Type*} local notation `𝕎` := witt_vector p -- type as `\bbW` open_locale witt namespace witt_vector /-- `f : α → β` induces a map from `𝕎 α` to `𝕎 β` by applying `f` componentwise. If `f` is a ring homomorphism, then so is `f`, see `witt_vector.map f`. -/ def map_fun (f : α → β) : 𝕎 α → 𝕎 β := λ x, mk _ (f ∘ x.coeff) namespace map_fun lemma injective (f : α → β) (hf : injective f) : injective (map_fun f : 𝕎 α → 𝕎 β) := λ x y h, ext $ λ n, hf (congr_arg (λ x, coeff x n) h : _) lemma surjective (f : α → β) (hf : surjective f) : surjective (map_fun f : 𝕎 α → 𝕎 β) := λ x, ⟨mk _ (λ n, classical.some $ hf $ x.coeff n), by { ext n, dsimp [map_fun], rw classical.some_spec (hf (x.coeff n)) }⟩ variables (f : R →+* S) (x y : 𝕎 R) /-- Auxiliary tactic for showing that `map_fun` respects the ring operations. -/ meta def map_fun_tac : tactic unit := `[ext n, show f (aeval _ _) = aeval _ _, rw map_aeval, apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, ext ⟨i, k⟩, fin_cases i; refl] include hp /- We do not tag these lemmas as `@[simp]` because they will be bundled in `map` later on. -/ lemma zero : map_fun f (0 : 𝕎 R) = 0 := by map_fun_tac lemma one : map_fun f (1 : 𝕎 R) = 1 := by map_fun_tac lemma add : map_fun f (x + y) = map_fun f x + map_fun f y := by map_fun_tac lemma sub : map_fun f (x - y) = map_fun f x - map_fun f y := by map_fun_tac lemma mul : map_fun f (x * y) = map_fun f x * map_fun f y := by map_fun_tac lemma neg : map_fun f (-x) = -map_fun f x := by map_fun_tac lemma nsmul (n : ℕ) : map_fun f (n • x) = n • map_fun f x := by map_fun_tac lemma zsmul (z : ℤ) : map_fun f (z • x) = z • map_fun f x := by map_fun_tac lemma pow (n : ℕ) : map_fun f (x^ n) = map_fun f x ^ n := by map_fun_tac end map_fun end witt_vector section tactic setup_tactic_parser open tactic /-- An auxiliary tactic for proving that `ghost_fun` respects the ring operations. -/ meta def tactic.interactive.ghost_fun_tac (φ fn : parse parser.pexpr) : tactic unit := do fn ← to_expr ```(%%fn : fin _ → ℕ → R), `(fin %%k → _ → _) ← infer_type fn, `[ext n], `[dunfold witt_vector.has_zero witt_zero witt_vector.has_one witt_one witt_vector.has_neg witt_neg witt_vector.has_mul witt_mul witt_vector.has_sub witt_sub witt_vector.has_add witt_add witt_vector.has_nat_scalar witt_nsmul witt_vector.has_int_scalar witt_zsmul witt_vector.has_nat_pow witt_pow ], to_expr ```(congr_fun (congr_arg (@peval R _ %%k) (witt_structure_int_prop p %%φ n)) %%fn) >>= note `this none, `[simpa [ghost_fun, aeval_rename, aeval_bind₁, (∘), uncurry, peval, eval] using this] end tactic namespace witt_vector /-- Evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. This function will be bundled as the ring homomorphism `witt_vector.ghost_map` once the ring structure is available, but we rely on it to set up the ring structure in the first place. -/ private def ghost_fun : 𝕎 R → (ℕ → R) := λ x n, aeval x.coeff (W_ ℤ n) section ghost_fun include hp /- The following lemmas are not `@[simp]` because they will be bundled in `ghost_map` later on. -/ variables (x y : 𝕎 R) omit hp local attribute [simp] lemma matrix_vec_empty_coeff {R} (i j) : @coeff p R (matrix.vec_empty i) j = (matrix.vec_empty i : ℕ → R) j := by rcases i with ⟨_ | _ | _ | _ | i_val, ⟨⟩⟩ include hp private lemma ghost_fun_zero : ghost_fun (0 : 𝕎 R) = 0 := by ghost_fun_tac 0 ![] private lemma ghost_fun_one : ghost_fun (1 : 𝕎 R) = 1 := by ghost_fun_tac 1 ![] private lemma ghost_fun_add : ghost_fun (x + y) = ghost_fun x + ghost_fun y := by ghost_fun_tac (X 0 + X 1) ![x.coeff, y.coeff] private lemma ghost_fun_sub : ghost_fun (x - y) = ghost_fun x - ghost_fun y := by ghost_fun_tac (X 0 - X 1) ![x.coeff, y.coeff] private lemma ghost_fun_mul : ghost_fun (x * y) = ghost_fun x * ghost_fun y := by ghost_fun_tac (X 0 * X 1) ![x.coeff, y.coeff] private lemma ghost_fun_neg : ghost_fun (-x) = - ghost_fun x := by ghost_fun_tac (-X 0) ![x.coeff] private lemma ghost_fun_nsmul (m : ℕ) : ghost_fun (m • x) = m • ghost_fun x := by ghost_fun_tac (m • X 0) ![x.coeff] private lemma ghost_fun_zsmul (m : ℤ) : ghost_fun (m • x) = m • ghost_fun x := by ghost_fun_tac (m • X 0) ![x.coeff] private lemma ghost_fun_pow (m : ℕ) : ghost_fun (x ^ m) = ghost_fun x ^ m := by ghost_fun_tac (X 0 ^ m) ![x.coeff] end ghost_fun variables (p) (R) /-- The bijection between `𝕎 R` and `ℕ → R`, under the assumption that `p` is invertible in `R`. In `witt_vector.ghost_equiv` we upgrade this to an isomorphism of rings. -/ private def ghost_equiv' [invertible (p : R)] : 𝕎 R ≃ (ℕ → R) := { to_fun := ghost_fun, inv_fun := λ x, mk p $ λ n, aeval x (X_in_terms_of_W p R n), left_inv := begin intro x, ext n, have := bind₁_witt_polynomial_X_in_terms_of_W p R n, apply_fun (aeval x.coeff) at this, simpa only [aeval_bind₁, aeval_X, ghost_fun, aeval_witt_polynomial] end, right_inv := begin intro x, ext n, have := bind₁_X_in_terms_of_W_witt_polynomial p R n, apply_fun (aeval x) at this, simpa only [aeval_bind₁, aeval_X, ghost_fun, aeval_witt_polynomial] end } include hp local attribute [instance] private def comm_ring_aux₁ : comm_ring (𝕎 (mv_polynomial R ℚ)) := (ghost_equiv' p (mv_polynomial R ℚ)).injective.comm_ring (ghost_fun) ghost_fun_zero ghost_fun_one ghost_fun_add ghost_fun_mul ghost_fun_neg ghost_fun_sub ghost_fun_nsmul ghost_fun_zsmul ghost_fun_pow local attribute [instance] private def comm_ring_aux₂ : comm_ring (𝕎 (mv_polynomial R ℤ)) := (map_fun.injective _ $ map_injective (int.cast_ring_hom ℚ) int.cast_injective).comm_ring _ (map_fun.zero _) (map_fun.one _) (map_fun.add _) (map_fun.mul _) (map_fun.neg _) (map_fun.sub _) (map_fun.nsmul _) (map_fun.zsmul _) (map_fun.pow _) /-- The commutative ring structure on `𝕎 R`. -/ instance : comm_ring (𝕎 R) := (map_fun.surjective _ $ counit_surjective _).comm_ring (map_fun $ mv_polynomial.counit _) (map_fun.zero _) (map_fun.one _) (map_fun.add _) (map_fun.mul _) (map_fun.neg _) (map_fun.sub _) (map_fun.nsmul _) (map_fun.zsmul _) (map_fun.pow _) variables {p R} /-- `witt_vector.map f` is the ring homomorphism `𝕎 R →+* 𝕎 S` naturally induced by a ring homomorphism `f : R →+* S`. It acts coefficientwise. -/ def map (f : R →+* S) : 𝕎 R →+* 𝕎 S := { to_fun := map_fun f, map_zero' := map_fun.zero f, map_one' := map_fun.one f, map_add' := map_fun.add f, map_mul' := map_fun.mul f } lemma map_injective (f : R →+* S) (hf : injective f) : injective (map f : 𝕎 R → 𝕎 S) := map_fun.injective f hf lemma map_surjective (f : R →+* S) (hf : surjective f) : surjective (map f : 𝕎 R → 𝕎 S) := map_fun.surjective f hf @[simp] lemma map_coeff (f : R →+* S) (x : 𝕎 R) (n : ℕ) : (map f x).coeff n = f (x.coeff n) := rfl /-- `witt_vector.ghost_map` is a ring homomorphism that maps each Witt vector to the sequence of its ghost components. -/ def ghost_map : 𝕎 R →+* ℕ → R := { to_fun := ghost_fun, map_zero' := ghost_fun_zero, map_one' := ghost_fun_one, map_add' := ghost_fun_add, map_mul' := ghost_fun_mul } /-- Evaluates the `n`th Witt polynomial on the first `n` coefficients of `x`, producing a value in `R`. -/ def ghost_component (n : ℕ) : 𝕎 R →+* R := (pi.eval_ring_hom _ n).comp ghost_map lemma ghost_component_apply (n : ℕ) (x : 𝕎 R) : ghost_component n x = aeval x.coeff (W_ ℤ n) := rfl @[simp] lemma ghost_map_apply (x : 𝕎 R) (n : ℕ) : ghost_map x n = ghost_component n x := rfl section invertible variables (p R) [invertible (p : R)] /-- `witt_vector.ghost_map` is a ring isomorphism when `p` is invertible in `R`. -/ def ghost_equiv : 𝕎 R ≃+* (ℕ → R) := { .. (ghost_map : 𝕎 R →+* (ℕ → R)), .. (ghost_equiv' p R) } @[simp] lemma ghost_equiv_coe : (ghost_equiv p R : 𝕎 R →+* (ℕ → R)) = ghost_map := rfl lemma ghost_map.bijective_of_invertible : function.bijective (ghost_map : 𝕎 R → ℕ → R) := (ghost_equiv p R).bijective end invertible /-- `witt_vector.coeff x 0` as a `ring_hom` -/ @[simps] def constant_coeff : 𝕎 R →+* R := { to_fun := λ x, x.coeff 0, map_zero' := by simp, map_one' := by simp, map_add' := add_coeff_zero, map_mul' := mul_coeff_zero } instance [nontrivial R] : nontrivial (𝕎 R) := constant_coeff.domain_nontrivial end witt_vector
4079f90fb18847bca1174609b4a87b39eaa957a9
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/match2.lean
493a05216e30683b17b7243aa5f5b08c6cee3c24
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
280
lean
inductive imf (f : nat → nat) : nat → Type | mk1 : ∀ (a : nat), imf (f a) | mk2 : imf (f 0 + 1) definition inv_2 (f : nat → nat) : ∀ (b : nat), imf f b → {x : nat // x > b} → nat | .(f a) (imf.mk1 .(f) a) x := a | .(f 0 + 1) (imf.mk2 .(f)) x := subtype.val x
eabd8f4876cfa3ac56b2d31aba62d623bd7e4b72
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Parser/Command.lean
fc49da29437ee75b1bfc4bed46d06cb72d35b03a
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,862
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term import Lean.Parser.Do namespace Lean namespace Parser /-- Syntax quotation for terms and (lists of) commands. We prefer terms, so ambiguous quotations like `` `($x $y) `` will be parsed as an application, not two commands. Use `` `($x:command $y:command) `` instead. Multiple command will be put in a `` `null `` node, but a single command will not (so that you can directly match against a quotation in a command kind's elaborator). -/ -- TODO: use two separate quotation parsers with parser priorities instead @[builtinTermParser] def Term.quot := leading_parser "`(" >> incQuotDepth (termParser <|> many1Unbox commandParser) >> ")" @[builtinTermParser] def Term.precheckedQuot := leading_parser "`" >> Term.quot namespace Command def namedPrio := leading_parser (atomic ("(" >> nonReservedSymbol "priority") >> " := " >> priorityParser >> ")") def optNamedPrio := optional namedPrio def «private» := leading_parser "private " def «protected» := leading_parser "protected " def visibility := «private» <|> «protected» def «noncomputable» := leading_parser "noncomputable " def «unsafe» := leading_parser "unsafe " def «partial» := leading_parser "partial " def declModifiers (inline : Bool) := leading_parser optional docComment >> optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >> optional visibility >> optional «noncomputable» >> optional «unsafe» >> optional «partial» def declId := leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") def declSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.typeSpec def optDeclSig := leading_parser many (ppSpace >> (Term.simpleBinderWithoutType <|> Term.bracketedBinder)) >> Term.optType def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls def «abbrev» := leading_parser "abbrev " >> declId >> optDeclSig >> declVal def «def» := leading_parser "def " >> declId >> optDeclSig >> declVal def «theorem» := leading_parser "theorem " >> declId >> declSig >> declVal def «constant» := leading_parser "constant " >> declId >> declSig >> optional declValSimple def «instance» := leading_parser Term.attrKind >> "instance " >> optNamedPrio >> optional declId >> declSig >> declVal def «axiom» := leading_parser "axiom " >> declId >> declSig def «example» := leading_parser "example " >> declSig >> declVal def inferMod := leading_parser atomic (symbol "{" >> "}") def ctor := leading_parser "\n| " >> declModifiers true >> ident >> optional inferMod >> optDeclSig def derivingClasses := sepBy1 (group (ident >> optional (" with " >> Term.structInst))) ", " def optDeriving := leading_parser optional (atomic ("deriving " >> notSymbol "instance") >> derivingClasses) def «inductive» := leading_parser "inductive " >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def classInductive := leading_parser atomic (group (symbol "class " >> "inductive ")) >> declId >> optDeclSig >> optional (symbol ":=" <|> "where") >> many ctor >> optDeriving def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser manyIndent (ppLine >> checkColGe >>(structExplicitBinder <|> structImplicitBinder <|> structInstBinder <|> structSimpleBinder)) def structCtor := leading_parser atomic (declModifiers true >> ident >> optional inferMod >> " :: ") def structureTk := leading_parser "structure " def classTk := leading_parser "class " def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def «structure» := leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >> optDeriving @[builtinCommandParser] def declaration := leading_parser declModifiers false >> («abbrev» <|> «def» <|> «theorem» <|> «constant» <|> «instance» <|> «axiom» <|> «example» <|> «inductive» <|> classInductive <|> «structure») @[builtinCommandParser] def «deriving» := leading_parser "deriving " >> "instance " >> derivingClasses >> " for " >> sepBy1 ident ", " @[builtinCommandParser] def «section» := leading_parser "section " >> optional ident @[builtinCommandParser] def «namespace» := leading_parser "namespace " >> ident @[builtinCommandParser] def «end» := leading_parser "end " >> optional ident @[builtinCommandParser] def «variable» := leading_parser "variable" >> many1 Term.bracketedBinder @[builtinCommandParser] def «universe» := leading_parser "universe " >> many1 ident @[builtinCommandParser] def check := leading_parser "#check " >> termParser @[builtinCommandParser] def check_failure := leading_parser "#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check @[builtinCommandParser] def reduce := leading_parser "#reduce " >> termParser @[builtinCommandParser] def eval := leading_parser "#eval " >> termParser @[builtinCommandParser] def synth := leading_parser "#synth " >> termParser @[builtinCommandParser] def exit := leading_parser "#exit" @[builtinCommandParser] def print := leading_parser "#print " >> (ident <|> strLit) @[builtinCommandParser] def printAxioms := leading_parser "#print " >> nonReservedSymbol "axioms " >> ident @[builtinCommandParser] def «resolve_name» := leading_parser "#resolve_name " >> ident @[builtinCommandParser] def «init_quot» := leading_parser "init_quot" def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit @[builtinCommandParser] def «set_option» := leading_parser "set_option " >> ident >> ppSpace >> optionValue def eraseAttr := leading_parser "-" >> ident @[builtinCommandParser] def «attribute» := leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "] " >> many1 ident @[builtinCommandParser] def «export» := leading_parser "export " >> ident >> "(" >> many1 ident >> ")" def openHiding := leading_parser atomic (ident >> "hiding") >> many1 ident def openRenamingItem := leading_parser ident >> unicodeSymbol "→" "->" >> ident def openRenaming := leading_parser atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", " def openOnly := leading_parser atomic (ident >> "(") >> many1 ident >> ")" def openSimple := leading_parser many1 ident def openDecl := openHiding <|> openRenaming <|> openOnly <|> openSimple @[builtinCommandParser] def «open» := leading_parser "open " >> openDecl @[builtinCommandParser] def «mutual» := leading_parser "mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >> ppDedent (ppLine >> "end") @[builtinCommandParser] def «initialize» := leading_parser optional visibility >> "initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «builtin_initialize» := leading_parser optional visibility >> "builtin_initialize " >> optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq @[builtinCommandParser] def «in» := trailing_parser " in " >> commandParser /- This is an auxiliary command for generation constructor injectivity theorems for inductive types defined at `Prelude.lean`. It is meant for bootstrapping purposes only. -/ @[builtinCommandParser] def genInjectiveTheorems := leading_parser "gen_injective_theorems% " >> ident @[runBuiltinParserAttributeHooks] abbrev declModifiersF := declModifiers false @[runBuiltinParserAttributeHooks] abbrev declModifiersT := declModifiers true builtin_initialize register_parser_alias "declModifiers" declModifiersF register_parser_alias "nestedDeclModifiers" declModifiersT register_parser_alias "declId" declId register_parser_alias "declSig" declSig register_parser_alias "declVal" declVal register_parser_alias "optDeclSig" optDeclSig register_parser_alias "openDecl" openDecl end Command namespace Term @[builtinTermParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> " in " >> termParser @[builtinTermParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser end Term namespace Tactic @[builtinTacticParser] def «open» := leading_parser:leadPrec "open " >> Command.openDecl >> " in " >> tacticSeq @[builtinTacticParser] def «set_option» := leading_parser:leadPrec "set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq end Tactic end Parser end Lean
2509bbe66762db3399cb9f58cfef7e2900e36d33
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/eval_constant.lean
3a27af08d3376693e041a17b1e4747d279c60d16
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
242
lean
open tactic run_cmd do e ← to_expr `(nat.add), fn ← eval_expr (nat → nat → nat) e, trace (fn 10 20) run_cmd do e ← to_expr `(λ x y : nat, x + x + y), fn ← eval_expr (nat → nat → nat) e, trace (fn 10 20)
cd0db63568b34c1dc7e5b3637ea020af2a569d36
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/set/intervals/basic.lean
acd0f4d3f4e7f969f372db261ebf9516edd4cf00
[ "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
30,916
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, Yury Kudryashov -/ import algebra.order_functions import data.set.basic /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨lt_of_lt_of_le ha hx.1, lt_of_le_of_lt hx.2 hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', lt_of_le_of_lt h' h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by simp [← Ioi_union_left, insert_subset, *]) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end end partial_order section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iic h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le bc (h ca)) end /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Ico_union_Ici lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_le_of_lt h)) Ioi_subset_Ioc_union_Ioi lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx))) Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Icc_union_Ici /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right) Iio_subset_Iio_union_Ico lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Ioc lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ioo lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Icc lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ variable {c : α} lemma Ioo_subset_Ioo_union_Ici : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ici lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section decidable_linear_order variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} end decidable_linear_order section decidable_linear_ordered_add_comm_group variables {α : Type u} [decidable_linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp* }, { use max x (x + dy), simp [*, le_refl] } end end decidable_linear_ordered_add_comm_group end set
88bbd021ddc89a7de8679552b1ec9183181c45c5
9ee042bf34eebe0464f0f80c0db14ceb048dab10
/src/Lean/Elab/PreDefinition/WF/PackMutual.lean
5cba177731bcf8f6e51a8a3c6c9188c5aefd0176
[ "Apache-2.0" ]
permissive
dexmagic/lean4
7507e7b07dc9f49db45df5ebd011886367dc2a6c
48764b60d5bac337eaff4bf8a3d63a216e1d9e03
refs/heads/master
1,692,156,265,016
1,633,276,980,000
1,633,339,480,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,284
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic namespace Lean.Elab.WF open Meta private def getDomains (preDefs : Array PreDefinition) : Array Expr := preDefs.map fun preDef => preDef.type.bindingDomain! /-- Combine different function domains `ds` using `Sum`s -/ private def mkNewDomain (ds : Array Expr) : MetaM Expr := do let mut r := ds.back for d in ds.pop.reverse do r ← mkAppM ``Sum #[d, r] return r private def getCodomainLevel (preDef : PreDefinition) : MetaM Level := forallBoundedTelescope preDef.type (some 1) fun _ body => getLevel body /-- Return the universe level for the codomain of the given definitions. This method produces an error if the codomains are in different universe levels. -/ private def getCodomainsLevel (preDefs : Array PreDefinition) : MetaM Level := do let r ← getCodomainLevel preDefs[0] for preDef in preDefs[1:] do unless (← isLevelDefEq r (← getCodomainLevel preDef)) do throwError "invalid mutual definition, result types must be in the same universe level" return r /-- Create the codomain for the new function that "combines" different `preDefs` See: `packMutual` -/ private partial def mkNewCoDomain (x : Expr) (preDefs : Array PreDefinition) : MetaM Expr := do let u ← getCodomainsLevel preDefs let rec go (x : Expr) (i : Nat) : MetaM Expr := do if i < preDefs.size - 1 then let xType ← whnfD (← inferType x) assert! xType.isAppOfArity ``Sum 2 let xTypeArgs := xType.getAppArgs let casesOn := mkConst (mkCasesOnName ``Sum) (mkLevelSucc u :: xType.getAppFn.constLevels!) let casesOn := mkAppN casesOn xTypeArgs -- parameters let casesOn := mkApp casesOn (← mkLambdaFVars #[x] (mkSort u)) -- motive let casesOn := mkApp casesOn x -- major let minor1 ← withLocalDeclD (← mkFreshUserName `_x) xTypeArgs[0] fun x => mkLambdaFVars #[x] (preDefs[i].type.bindingBody!.instantiate1 x) let minor2 ← withLocalDeclD (← mkFreshUserName `_x) xTypeArgs[1] fun x => do mkLambdaFVars #[x] (← go x (i+1)) return mkApp2 casesOn minor1 minor2 else return preDefs[i].type.bindingBody!.instantiate1 x go x 0 /-- Combine/pack the values of the different definitions in a single value `x` is `Sum`, and we use `Sum.casesOn` to select the appropriate `preDefs.value`. See: `packMutual`. Remark: this method does not replace the nested recursive `preDefs` applications. This step is performed by `transform` with the following `post` method. -/ private partial def packValues (x : Expr) (codomain : Expr) (preDefs : Array PreDefinition) : MetaM Expr := do let mvar ← mkFreshExprSyntheticOpaqueMVar codomain let rec go (mvarId : MVarId) (x : FVarId) (i : Nat) : MetaM Unit := do if i < preDefs.size - 1 then let #[s₁, s₂] ← cases mvarId x | unreachable! assignExprMVar s₁.mvarId (mkApp preDefs[i].value s₁.fields[0]).headBeta go s₂.mvarId s₂.fields[0].fvarId! (i+1) else assignExprMVar mvarId (mkApp preDefs[i].value (mkFVar x)).headBeta go mvar.mvarId! x.fvarId! 0 instantiateMVars mvar /-- Auxiliary function for replacing nested `preDefs` recursive calls in `e` with the new function `newFn`. See: `packMutual` -/ private partial def post (preDefs : Array PreDefinition) (domain : Expr) (newFn : Name) (e : Expr) : MetaM TransformStep := do if let Expr.app (Expr.const declName us _) arg _ := e then if let some fidx := preDefs.findIdx? (·.declName == declName) then let rec mkNewArg (i : Nat) (type : Expr) : MetaM Expr := do if i == preDefs.size - 1 then return arg else (← whnfD type).withApp fun f args => do assert! args.size == 2 if i == fidx then return mkApp3 (mkConst ``Sum.inl f.constLevels!) args[0] args[1] arg else let r ← mkNewArg (i+1) args[1] return mkApp3 (mkConst ``Sum.inr f.constLevels!) args[0] args[1] r return TransformStep.done <| mkApp (mkConst newFn us) (← mkNewArg 0 domain) return TransformStep.done e /-- If `preDefs.size > 1`, combine different functions in a single one using `Sum`. This method assumes all `preDefs` have arity 1, and have already been processed using `packDomain`. Here is a small example. Suppose the input is ``` f x := match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => a | Nat.succ n, a, b => (g ⟨x.1, n, a, b⟩).fst g x := match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => (a, b) | Nat.succ n, a, b => (h ⟨x.1, n, a, b⟩, a) h x => match x.2.1, x.2.2.1, x.2.2.2 with | 0, a, b => b | Nat.succ n, a, b => f ⟨x.1, n, a, b⟩ ``` this method produces the following pre definition ``` f._mutual x := Sum.casesOn x (fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => a | Nat.succ n, a, b => (f._mutual (Sum.inr (Sum.inl ⟨val.1, n, a, b⟩))).fst fun val => Sum.casesOn val (fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => (a, b) | Nat.succ n, a, b => (f._mutual (Sum.inr (Sum.inr ⟨val.1, n, a, b⟩)), a) fun val => match val.2.1, val.2.2.1, val.2.2.2 with | 0, a, b => b | Nat.succ n, a, b => f._mutual (Sum.inl ⟨val.1, n, a, b⟩) ``` -/ def packMutual (preDefs : Array PreDefinition) : MetaM PreDefinition := do if preDefs.size == 1 then return preDefs[0] let domain ← mkNewDomain (getDomains preDefs) withLocalDeclD (← mkFreshUserName `_x) domain fun x => do let codomain ← mkNewCoDomain x preDefs let type ← mkForallFVars #[x] codomain let value ← packValues x codomain preDefs let newFn := preDefs[0].declName ++ `_mutual let preDefNew := { preDefs[0] with declName := newFn, type, value } addAsAxiom preDefNew let value ← transform value (post := post preDefs domain newFn) let value ← mkLambdaFVars #[x] value return { preDefNew with value } end Lean.Elab.WF
86db4d83ef1c1e0d110dfa9cf94e9ab20ce624ff
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/polyhedral_lattice/int.lean
ba5ebeb1dd97bb5d68ecd9af34bd5f285827124f
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,145
lean
import analysis.normed_space.int import polyhedral_lattice.basic /-! # The integers are a polyhedral lattice. The integers, with its usual norm, are a polyhedral lattice. -/ noncomputable theory open_locale big_operators lemma int.sum_units_to_nat_smul (n : ℤ) : ∑ (i : units ℤ), int.to_nat (i * n) • (i : ℤ) = n := begin rw [units_int.univ, finset.sum_insert], swap, dec_trivial, simp only [neg_mul_eq_neg_mul_symm, mul_one, int.nat_cast_eq_coe_nat, one_mul, nsmul_eq_mul, units.coe_one, units.coe_neg_one, mul_neg_eq_neg_mul_symm, finset.sum_singleton, ← sub_eq_add_neg, int.to_nat_sub_to_nat_neg], end instance int.polyhedral_lattice : polyhedral_lattice ℤ := { polyhedral' := begin refine ⟨units ℤ, infer_instance, coe, _⟩, intro n, refine ⟨λ e, int.to_nat (e * n), (int.sum_units_to_nat_smul _).symm, _⟩, simp only [int.norm_coe_units, mul_one, nat.cast_one, one_mul, units_int.univ], show ∥n∥ = ((1 * n).to_nat) + (↑(((-1) * n).to_nat) + 0), simp only [neg_mul_eq_neg_mul_symm, add_zero, one_mul], exact (int.to_nat_add_to_nat_neg_eq_norm _).symm, end }
318f23a69eff63460a2b673937cb3be3b730ac74
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/matchunit.lean
bfed4ce66f3200c9ae3d5359504882ce21609ac8
[ "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
149
lean
def f (a : Unit) : Nat := match a with | PUnit.unit => 10 #print f def g (a : Unit) : Unit := match a with | b@(PUnit.unit) => b #print g
e17fe7a472dbc6c5618a184cc5a0a4f79896d839
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/blast_back2.lean
50924336cc51243bff25101f69b349d5e0719ee7
[ "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
457
lean
constant r : nat → Prop constant s : nat → Prop constant p : nat → Prop definition q (a : nat) := p a lemma rq₁ [intro] [priority 20] : ∀ a, r a → q a := sorry lemma rq₂ [intro] [priority 10] : ∀ a, s a → q a := sorry attribute q [reducible] definition lemma1 (a : nat) : r a → s a → p a := by blast print lemma1 attribute rq₂ [intro] [priority 30] definition lemma2 (a : nat) : r a → s a → p a := by blast print lemma2
5c1cc979eef91538e45dd3bc81f3eb6831140bae
646fc4b41ca4adb82b3f7fbae3ea3c58ff496b4c
/Example.lean
6fd16f2c1557f98e27a1e6e9b125d4f0a44098ca
[]
no_license
cpehle/lean4-plugin-example
82e63420463483381c91de0705b5626a336863fa
d32d3b310645cfecf4c33acafe996755f67cf30b
refs/heads/main
1,690,367,192,612
1,631,531,751,000
1,631,531,751,000
405,148,785
2
1
null
null
null
null
UTF-8
Lean
false
false
21
lean
import Example.Basic
3a0064d141e53fa8cd99d5bc801081046bd45ea3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/type_tags.lean
d03b666e93413d51f54eebe3bc4801168ce7bda7
[ "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
14,202
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 algebra.hom.group import logic.equiv.defs import data.finite.defs /-! # Type tags that turn additive structures into multiplicative, and vice versa We define two type tags: * `additive α`: turns any multiplicative structure on `α` into the corresponding additive structure on `additive α`; * `multiplicative α`: turns any additive structure on `α` into the corresponding multiplicative structure on `multiplicative α`. We also define instances `additive.*` and `multiplicative.*` that actually transfer the structures. ## See also This file is similar to `order.synonym`. -/ universes u v variables {α : Type u} {β : Type v} /-- If `α` carries some multiplicative structure, then `additive α` carries the corresponding additive structure. -/ def additive (α : Type*) := α /-- If `α` carries some additive structure, then `multiplicative α` carries the corresponding multiplicative structure. -/ def multiplicative (α : Type*) := α namespace additive /-- Reinterpret `x : α` as an element of `additive α`. -/ def of_mul : α ≃ additive α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ /-- Reinterpret `x : additive α` as an element of `α`. -/ def to_mul : additive α ≃ α := of_mul.symm @[simp] lemma of_mul_symm_eq : (@of_mul α).symm = to_mul := rfl @[simp] lemma to_mul_symm_eq : (@to_mul α).symm = of_mul := rfl end additive namespace multiplicative /-- Reinterpret `x : α` as an element of `multiplicative α`. -/ def of_add : α ≃ multiplicative α := ⟨λ x, x, λ x, x, λ x, rfl, λ x, rfl⟩ /-- Reinterpret `x : multiplicative α` as an element of `α`. -/ def to_add : multiplicative α ≃ α := of_add.symm @[simp] lemma of_add_symm_eq : (@of_add α).symm = to_add := rfl @[simp] lemma to_add_symm_eq : (@to_add α).symm = of_add := rfl end multiplicative @[simp] lemma to_add_of_add (x : α) : (multiplicative.of_add x).to_add = x := rfl @[simp] lemma of_add_to_add (x : multiplicative α) : multiplicative.of_add x.to_add = x := rfl @[simp] lemma to_mul_of_mul (x : α) : (additive.of_mul x).to_mul = x := rfl @[simp] lemma of_mul_to_mul (x : additive α) : additive.of_mul x.to_mul = x := rfl instance [inhabited α] : inhabited (additive α) := ⟨additive.of_mul default⟩ instance [inhabited α] : inhabited (multiplicative α) := ⟨multiplicative.of_add default⟩ instance [finite α] : finite (additive α) := finite.of_equiv α (by refl) instance [finite α] : finite (multiplicative α) := finite.of_equiv α (by refl) instance [infinite α] : infinite (additive α) := by tauto instance [infinite α] : infinite (multiplicative α) := by tauto instance [nontrivial α] : nontrivial (additive α) := additive.of_mul.injective.nontrivial instance [nontrivial α] : nontrivial (multiplicative α) := multiplicative.of_add.injective.nontrivial instance additive.has_add [has_mul α] : has_add (additive α) := { add := λ x y, additive.of_mul (x.to_mul * y.to_mul) } instance [has_add α] : has_mul (multiplicative α) := { mul := λ x y, multiplicative.of_add (x.to_add + y.to_add) } @[simp] lemma of_add_add [has_add α] (x y : α) : multiplicative.of_add (x + y) = multiplicative.of_add x * multiplicative.of_add y := rfl @[simp] lemma to_add_mul [has_add α] (x y : multiplicative α) : (x * y).to_add = x.to_add + y.to_add := rfl @[simp] lemma of_mul_mul [has_mul α] (x y : α) : additive.of_mul (x * y) = additive.of_mul x + additive.of_mul y := rfl @[simp] lemma to_mul_add [has_mul α] (x y : additive α) : (x + y).to_mul = x.to_mul * y.to_mul := rfl instance [semigroup α] : add_semigroup (additive α) := { add_assoc := @mul_assoc α _, ..additive.has_add } instance [add_semigroup α] : semigroup (multiplicative α) := { mul_assoc := @add_assoc α _, ..multiplicative.has_mul } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } instance [has_one α] : has_zero (additive α) := ⟨additive.of_mul 1⟩ @[simp] lemma of_mul_one [has_one α] : @additive.of_mul α 1 = 0 := rfl @[simp] lemma of_mul_eq_zero {A : Type*} [has_one A] {x : A} : additive.of_mul x = 0 ↔ x = 1 := iff.rfl @[simp] lemma to_mul_zero [has_one α] : (0 : additive α).to_mul = 1 := rfl instance [has_zero α] : has_one (multiplicative α) := ⟨multiplicative.of_add 0⟩ @[simp] lemma of_add_zero [has_zero α] : @multiplicative.of_add α 0 = 1 := rfl @[simp] lemma of_add_eq_one {A : Type*} [has_zero A] {x : A} : multiplicative.of_add x = 1 ↔ x = 0 := iff.rfl @[simp] lemma to_add_one [has_zero α] : (1 : multiplicative α).to_add = 0 := rfl instance [mul_one_class α] : add_zero_class (additive α) := { zero := 0, add := (+), zero_add := one_mul, add_zero := mul_one } instance [add_zero_class α] : mul_one_class (multiplicative α) := { one := 1, mul := (*), one_mul := zero_add, mul_one := add_zero } instance [h : monoid α] : add_monoid (additive α) := { zero := 0, add := (+), nsmul := @monoid.npow α h, nsmul_zero' := monoid.npow_zero', nsmul_succ' := monoid.npow_succ', ..additive.add_zero_class, ..additive.add_semigroup } instance [h : add_monoid α] : monoid (multiplicative α) := { one := 1, mul := (*), npow := @add_monoid.nsmul α h, npow_zero' := add_monoid.nsmul_zero', npow_succ' := add_monoid.nsmul_succ', ..multiplicative.mul_one_class, ..multiplicative.semigroup } instance [left_cancel_monoid α] : add_left_cancel_monoid (additive α) := { zero := 0, add := (+), .. additive.add_monoid, .. additive.add_left_cancel_semigroup } instance [add_left_cancel_monoid α] : left_cancel_monoid (multiplicative α) := { one := 1, mul := (*), .. multiplicative.monoid, .. multiplicative.left_cancel_semigroup } instance [right_cancel_monoid α] : add_right_cancel_monoid (additive α) := { zero := 0, add := (+), .. additive.add_monoid, .. additive.add_right_cancel_semigroup } instance [add_right_cancel_monoid α] : right_cancel_monoid (multiplicative α) := { one := 1, mul := (*), .. multiplicative.monoid, .. multiplicative.right_cancel_semigroup } instance [comm_monoid α] : add_comm_monoid (additive α) := { zero := 0, add := (+), .. additive.add_monoid, .. additive.add_comm_semigroup } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { one := 1, mul := (*), ..multiplicative.monoid, .. multiplicative.comm_semigroup } instance [has_inv α] : has_neg (additive α) := ⟨λ x, multiplicative.of_add x.to_mul⁻¹⟩ @[simp] lemma of_mul_inv [has_inv α] (x : α) : additive.of_mul x⁻¹ = -(additive.of_mul x) := rfl @[simp] lemma to_mul_neg [has_inv α] (x : additive α) : (-x).to_mul = x.to_mul⁻¹ := rfl instance [has_neg α] : has_inv (multiplicative α) := ⟨λ x, additive.of_mul (-x.to_add)⟩ @[simp] lemma of_add_neg [has_neg α] (x : α) : multiplicative.of_add (-x) = (multiplicative.of_add x)⁻¹ := rfl @[simp] lemma to_add_inv [has_neg α] (x : multiplicative α) : (x⁻¹).to_add = -x.to_add := rfl instance additive.has_sub [has_div α] : has_sub (additive α) := { sub := λ x y, additive.of_mul (x.to_mul / y.to_mul) } instance multiplicative.has_div [has_sub α] : has_div (multiplicative α) := { div := λ x y, multiplicative.of_add (x.to_add - y.to_add) } @[simp] lemma of_add_sub [has_sub α] (x y : α) : multiplicative.of_add (x - y) = multiplicative.of_add x / multiplicative.of_add y := rfl @[simp] lemma to_add_div [has_sub α] (x y : multiplicative α) : (x / y).to_add = x.to_add - y.to_add := rfl @[simp] lemma of_mul_div [has_div α] (x y : α) : additive.of_mul (x / y) = additive.of_mul x - additive.of_mul y := rfl @[simp] lemma to_mul_sub [has_div α] (x y : additive α) : (x - y).to_mul = x.to_mul / y.to_mul := rfl instance [has_involutive_inv α] : has_involutive_neg (additive α) := { neg_neg := @inv_inv _ _, ..additive.has_neg } instance [has_involutive_neg α] : has_involutive_inv (multiplicative α) := { inv_inv := @neg_neg _ _, ..multiplicative.has_inv } instance [div_inv_monoid α] : sub_neg_monoid (additive α) := { sub_eq_add_neg := @div_eq_mul_inv α _, zsmul := @div_inv_monoid.zpow α _, zsmul_zero' := div_inv_monoid.zpow_zero', zsmul_succ' := div_inv_monoid.zpow_succ', zsmul_neg' := div_inv_monoid.zpow_neg', .. additive.has_neg, .. additive.has_sub, .. additive.add_monoid } instance [sub_neg_monoid α] : div_inv_monoid (multiplicative α) := { div_eq_mul_inv := @sub_eq_add_neg α _, zpow := @sub_neg_monoid.zsmul α _, zpow_zero' := sub_neg_monoid.zsmul_zero', zpow_succ' := sub_neg_monoid.zsmul_succ', zpow_neg' := sub_neg_monoid.zsmul_neg', .. multiplicative.has_inv, .. multiplicative.has_div, .. multiplicative.monoid } instance [division_monoid α] : subtraction_monoid (additive α) := { neg_add_rev := @mul_inv_rev _ _, neg_eq_of_add := @inv_eq_of_mul_eq_one_right _ _, .. additive.sub_neg_monoid, .. additive.has_involutive_neg } instance [subtraction_monoid α] : division_monoid (multiplicative α) := { mul_inv_rev := @neg_add_rev _ _, inv_eq_of_mul := @neg_eq_of_add_eq_zero_right _ _, .. multiplicative.div_inv_monoid, .. multiplicative.has_involutive_inv } instance [division_comm_monoid α] : subtraction_comm_monoid (additive α) := { .. additive.subtraction_monoid, .. additive.add_comm_semigroup } instance [subtraction_comm_monoid α] : division_comm_monoid (multiplicative α) := { .. multiplicative.division_monoid, .. multiplicative.comm_semigroup } instance [group α] : add_group (additive α) := { add_left_neg := @mul_left_inv α _, .. additive.sub_neg_monoid } instance [add_group α] : group (multiplicative α) := { mul_left_inv := @add_left_neg α _, .. multiplicative.div_inv_monoid } instance [comm_group α] : add_comm_group (additive α) := { .. additive.add_group, .. additive.add_comm_monoid } instance [add_comm_group α] : comm_group (multiplicative α) := { .. multiplicative.group, .. multiplicative.comm_monoid } open multiplicative (of_add) open additive (of_mul) /-- Reinterpret `α →+ β` as `multiplicative α →* multiplicative β`. -/ @[simps] def add_monoid_hom.to_multiplicative [add_zero_class α] [add_zero_class β] : (α →+ β) ≃ (multiplicative α →* multiplicative β) := { to_fun := λ f, ⟨λ a, of_add (f a.to_add), f.2, f.3⟩, inv_fun := λ f, ⟨λ a, (f (of_add a)).to_add, f.2, f.3⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, } } /-- Reinterpret `α →* β` as `additive α →+ additive β`. -/ @[simps] def monoid_hom.to_additive [mul_one_class α] [mul_one_class β] : (α →* β) ≃ (additive α →+ additive β) := { to_fun := λ f, ⟨λ a, of_mul (f a.to_mul), f.2, f.3⟩, inv_fun := λ f, ⟨λ a, (f (of_mul a)).to_mul, f.2, f.3⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, } } /-- Reinterpret `additive α →+ β` as `α →* multiplicative β`. -/ @[simps] def add_monoid_hom.to_multiplicative' [mul_one_class α] [add_zero_class β] : (additive α →+ β) ≃ (α →* multiplicative β) := { to_fun := λ f, ⟨λ a, of_add (f (of_mul a)), f.2, f.3⟩, inv_fun := λ f, ⟨λ a, (f a.to_mul).to_add, f.2, f.3⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, } } /-- Reinterpret `α →* multiplicative β` as `additive α →+ β`. -/ @[simps] def monoid_hom.to_additive' [mul_one_class α] [add_zero_class β] : (α →* multiplicative β) ≃ (additive α →+ β) := add_monoid_hom.to_multiplicative'.symm /-- Reinterpret `α →+ additive β` as `multiplicative α →* β`. -/ @[simps] def add_monoid_hom.to_multiplicative'' [add_zero_class α] [mul_one_class β] : (α →+ additive β) ≃ (multiplicative α →* β) := { to_fun := λ f, ⟨λ a, (f a.to_add).to_mul, f.2, f.3⟩, inv_fun := λ f, ⟨λ a, of_mul (f (of_add a)), f.2, f.3⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, } } /-- Reinterpret `multiplicative α →* β` as `α →+ additive β`. -/ @[simps] def monoid_hom.to_additive'' [add_zero_class α] [mul_one_class β] : (multiplicative α →* β) ≃ (α →+ additive β) := add_monoid_hom.to_multiplicative''.symm /-- If `α` has some multiplicative structure and coerces to a function, then `additive α` should also coerce to the same function. This allows `additive` to be used on bundled function types with a multiplicative structure, which is often used for composition, without affecting the behavior of the function itself. -/ instance additive.has_coe_to_fun {α : Type*} {β : α → Sort*} [has_coe_to_fun α β] : has_coe_to_fun (additive α) (λ a, β a.to_mul) := ⟨λ a, coe_fn a.to_mul⟩ /-- If `α` has some additive structure and coerces to a function, then `multiplicative α` should also coerce to the same function. This allows `multiplicative` to be used on bundled function types with an additive structure, which is often used for composition, without affecting the behavior of the function itself. -/ instance multiplicative.has_coe_to_fun {α : Type*} {β : α → Sort*} [has_coe_to_fun α β] : has_coe_to_fun (multiplicative α) (λ a, β a.to_add) := ⟨λ a, coe_fn a.to_add⟩
205ab2082955c2f074c88ff6aca22029d7e49345
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Mon/limits_auto.lean
ba50161d465332527105a4bf53dbeae4b6403a1b
[]
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
8,859
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.pi import Mathlib.algebra.category.Mon.basic import Mathlib.group_theory.submonoid.default import Mathlib.category_theory.limits.types import Mathlib.category_theory.limits.creates import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # The category of (commutative) (additive) monoids has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ namespace Mon protected instance monoid_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ Mon) (j : J) : monoid (category_theory.functor.obj (F ⋙ category_theory.forget Mon) j) := id (Mon.monoid (category_theory.functor.obj F j)) /-- The flat sections of a functor into `Mon` form a submonoid of all sections. -/ def Mathlib.AddMon.sections_add_submonoid {J : Type u} [category_theory.small_category J] (F : J ⥤ AddMon) : add_submonoid ((j : J) → ↥(category_theory.functor.obj F j)) := add_submonoid.mk (category_theory.functor.sections (F ⋙ category_theory.forget AddMon)) sorry sorry protected instance Mathlib.AddMon.limit_add_monoid {J : Type u} [category_theory.small_category J] (F : J ⥤ AddMon) : add_monoid (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget AddMon))) := add_submonoid.to_add_monoid (AddMon.sections_add_submonoid F) /-- `limit.π (F ⋙ forget Mon) j` as a `monoid_hom`. -/ def Mathlib.AddMon.limit_π_add_monoid_hom {J : Type u} [category_theory.small_category J] (F : J ⥤ AddMon) (j : J) : category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget AddMon)) →+ category_theory.functor.obj (F ⋙ category_theory.forget AddMon) j := add_monoid_hom.mk (category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget AddMon))) j) sorry sorry namespace has_limits -- The next two definitions are used in the construction of `has_limits Mon`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `Mon`. (Internal use only; use the limits API.) -/ def Mathlib.AddMon.has_limits.limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ AddMon) : category_theory.limits.cone F := category_theory.limits.cone.mk (AddMon.of (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget AddMon)))) (category_theory.nat_trans.mk (AddMon.limit_π_add_monoid_hom F)) /-- Witness that the limit cone in `Mon` is a limit cone. (Internal use only; use the limits API.) -/ def Mathlib.AddMon.has_limits.limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ AddMon) : category_theory.limits.is_limit (AddMon.has_limits.limit_cone F) := category_theory.limits.is_limit.of_faithful (category_theory.forget AddMon) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget AddMon)) (fun (s : category_theory.limits.cone F) => add_monoid_hom.mk (fun (v : category_theory.limits.cone.X (category_theory.functor.map_cone (category_theory.forget AddMon) s)) => { val := fun (j : J) => category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.functor.map_cone (category_theory.forget AddMon) s)) j v, property := sorry }) sorry sorry) sorry end has_limits /-- The category of monoids has all limits. -/ protected instance Mathlib.AddMon.has_limits : category_theory.limits.has_limits AddMon := category_theory.limits.has_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ AddMon) => category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk sorry sorry) /-- The forgetful functor from monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance Mathlib.AddMon.forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget AddMon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ AddMon) => category_theory.limits.preserves_limit_of_preserves_limit_cone (AddMon.has_limits.limit_cone_is_limit F) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget AddMon)) end Mon namespace CommMon protected instance comm_monoid_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ CommMon) (j : J) : comm_monoid (category_theory.functor.obj (F ⋙ category_theory.forget CommMon) j) := id (CommMon.comm_monoid (category_theory.functor.obj F j)) protected instance limit_comm_monoid {J : Type u} [category_theory.small_category J] (F : J ⥤ CommMon) : comm_monoid (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget CommMon))) := submonoid.to_comm_monoid (Mon.sections_submonoid (F ⋙ category_theory.forget₂ CommMon Mon)) /-- We show that the forgetful functor `CommMon ⥤ Mon` creates limits. All we need to do is notice that the limit point has a `comm_monoid` instance available, and then reuse the existing limit. -/ protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommMon) : category_theory.creates_limit F (category_theory.forget₂ CommMon Mon) := sorry /-- A choice of limit cone for a functor into `CommMon`. (Generally, you'll just want to use `limit F`.) -/ def Mathlib.AddCommMon.limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ AddCommMon) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ AddCommMon AddMon)) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def Mathlib.AddCommMon.limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ AddCommMon) : category_theory.limits.is_limit (AddCommMon.limit_cone F) := category_theory.lifted_limit_is_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ AddCommMon AddMon)) /-- The category of commutative monoids has all limits. -/ protected instance has_limits : category_theory.limits.has_limits CommMon := category_theory.limits.has_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ CommMon) => category_theory.has_limit_of_created F (category_theory.forget₂ CommMon Mon) /-- The forgetful functor from commutative monoids to monoids preserves all limits. (That is, the underlying monoid could have been computed instead as limits in the category of monoids.) -/ protected instance Mathlib.AddCommMon.forget₂_AddMon_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ AddCommMon AddMon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ AddCommMon) => category_theory.preserves_limit_of_creates_limit_and_has_limit F (category_theory.forget₂ AddCommMon AddMon) /-- The forgetful functor from commutative monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget CommMon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommMon) => category_theory.limits.comp_preserves_limit (category_theory.forget₂ CommMon Mon) (category_theory.forget Mon) end Mathlib
f5b0f91c263ed6be9508e83f6b5ebbd1dd7aaa91
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/matchErrorLocation.lean
671b9c10475d3470c594e07da451213b9623c10d
[ "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
107
lean
def head {α} (xs : List α) (h : xs = [] → False) : α := match he:xs with | [] => h he | x::_ => x
b1e20804d1b37e3372d2c3d8348009ee4d763a35
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/subtype.lean
314a76deb87d0b2926e4dde136568f8dfa116b0a
[ "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
1,279
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.subtype Author: Leonardo de Moura, Jeremy Avigad -/ open decidable set_option structure.proj_mk_thm true structure subtype {A : Type} (P : A → Prop) := tag :: (elt_of : A) (has_property : P elt_of) notation `{` binders `|` r:(scoped:1 P, subtype P) `}` := r namespace subtype variables {A : Type} {P : A → Prop} theorem tag_irrelevant {a : A} (H1 H2 : P a) : tag a H1 = tag a H2 := rfl theorem tag_eq {a1 a2 : A} {H1 : P a1} {H2 : P a2} (H3 : a1 = a2) : tag a1 H1 = tag a2 H2 := eq.subst H3 (take H2, tag_irrelevant H1 H2) H2 protected theorem equal {a1 a2 : {x | P x}} : ∀(H : elt_of a1 = elt_of a2), a1 = a2 := destruct a1 (take x1 H1, destruct a2 (take x2 H2 H, tag_eq H)) protected definition is_inhabited [instance] {a : A} (H : P a) : inhabited {x | P x} := inhabited.mk (tag a H) protected definition has_decidable_eq [instance] [H : decidable_eq A] : decidable_eq {x | P x} := take a1 a2 : {x | P x}, have H1 : (a1 = a2) ↔ (elt_of a1 = elt_of a2), from iff.intro (assume H, eq.subst H rfl) (assume H, equal H), decidable_of_decidable_of_iff _ (iff.symm H1) end subtype
f5eec24b389dc4f1ff2fb5c42ffa3120620563e5
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/real/cau_seq.lean
cbe27102f9721e01ab311d2df5acba84c2c09c18
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
6,638
lean
import ..myrat.le import ..myring.order import ..mynat.max import ..sequence namespace hidden open myring open ordered_myring open myfield open ordered_myfield def is_cau_seq (f : sequence myrat) : Prop := ∀ ε : myrat, 0 < ε → ∃ N : mynat, ∀ n m : mynat, N ≤ n → N ≤ m → abs (f m - f n) < ε -- Create the type of Cauchy sequences def cau_seq := {f : sequence myrat // is_cau_seq f} namespace cau_seq -- Two cauchy sequences are equivalent if their difference -- tends to zero def equivalent (f g : cau_seq) : Prop := ∀ ε : myrat, 0 < ε → ∃ N : mynat, ∀ n : mynat, N ≤ n → abs (f.val n - g.val n) < ε private theorem equivalent_refl: reflexive equivalent := begin intros f ε, assume hepos, cases f.property ε hepos with N hN, existsi N, intro n, assume hNn, from hN n n hNn hNn, end private theorem equivalent_symm: symmetric equivalent := begin intros f g, assume hfeqg, intro ε, assume hepos, cases hfeqg ε hepos with N hN, existsi N, intro n, assume hNn, have := hN n hNn, rwa [←abs_neg, sub_def, neg_distr, neg_neg, add_comm, ←sub_def], end private theorem equivalent_trans: transitive equivalent := begin intros f g h, assume hfeqg hgeqh, intro ε, assume hepos, cases hfeqg (ε / 2) (half_pos hepos) with N1 hN1, cases hgeqh (ε / 2) (half_pos hepos) with N2 hN2, existsi mynat.max N1 N2, intro n, assume hN1N2n, have hN1e := hN1 n (mynat.max_le_cancel_left hN1N2n), have hN2e := hN2 n (mynat.max_le_cancel_right hN1N2n), have := triangle_ineq (f.val n - g.val n) (g.val n - h.val n), conv at this { congr, rw [sub_def, sub_def, add_assoc], congr, congr, skip, rw ←add_assoc, congr, rw [add_comm, ←sub_def, sub_self], }, rw [zero_add, ←sub_def] at this, have hcomb := lt_comb hN1e hN2e, rw half_plus_half at hcomb, apply le_lt_chain (abs (f.val n - g.val n) + abs (g.val n - h.val n)); assumption, assume water, apply nontrivial_zero_ne_two myrat.nontrivial, symmetry, assumption, end instance real_setoid: setoid cau_seq := ⟨equivalent, equivalent_refl, equivalent_symm, equivalent_trans⟩ theorem setoid_equiv (f g : cau_seq) : f ≈ g ↔ equivalent f g := iff.rfl theorem seq_eq_impl_eq (f g : cau_seq) : (∀ n, f.val n = g.val n) → f = g := begin cases f, cases g, dsimp only [], intros h, congr, -- Good old congr apply funext, assumption, end theorem seq_eq_impl_cau_seq_equiv (f g : cau_seq) : (∀ n, f.val n = g.val n) → f ≈ g := begin assume h, rw setoid_equiv, unfold equivalent, intros ε hε, existsi (0 : mynat), intros n hn, rwa [h n, sub_self], end theorem constant_cauchy (x : myrat) : is_cau_seq (λ n, x) := begin dsimp only [is_cau_seq], rw sub_self, intros ε hε, existsi (0 : mynat), intros m n hm hn, rwa abs_zero, end instance: has_zero cau_seq := ⟨⟨λ n, 0, constant_cauchy 0⟩⟩ instance: has_one cau_seq := ⟨⟨λ n, 1, constant_cauchy 1⟩⟩ local attribute [instance] classical.prop_decidable theorem abs_bounded_above (f : cau_seq) : ∃ (u : myrat), 0 < u ∧ ∀ n, abs (f.val n) < u:= begin cases f.property 1 (ordered_myring.nontrivial_zero_lt_one myrat.nontrivial) with N h, existsi max (1 + (max_upto N $ λ n, abs (f.val n))) (abs (f.val N) + 1), split, { apply lt_le_chain (abs (f.val N) + 1), rw ←add_zero (0 : myrat), apply le_lt_comb, exact abs_nonneg _, exact (ordered_myring.nontrivial_zero_lt_one myrat.nontrivial), apply ordered_myring.le_max_right, }, { intros n, have := h n N, by_cases hNn : N ≤ n, { have := this hNn (@mynat.le_refl N), apply lt_le_chain (abs (f.val N) + 1), { rw lt_add_cancel_left _ _ (-abs (f.val N)), rw add_comm, rw ←add_assoc, rw neg_add, rw zero_add, apply le_lt_chain (abs (f.val N - f.val n)), { transitivity abs (abs (f.val n) + -abs (f.val N)), apply self_le_abs, rw ←sub_def, rw abs_sub_switch, apply triangle_ineq_sub, }, { assumption, }, }, { apply ordered_myring.le_max_right, }, }, { change n < N at hNn, have hNn₂ := mynat.lt_impl_le hNn, apply lt_le_chain (1 + max_upto N (λ (n : mynat), abs (f.val n))), { rw ←zero_add (abs (f.val n)), apply lt_le_comb, { exact (ordered_myring.nontrivial_zero_lt_one myrat.nontrivial), }, { -- `change` comes into its own change ((λ (n : mynat), abs (f.val n)) n) ≤ _, apply max_upto_ge_before, assumption, }, }, { apply ordered_myring.le_max_left, }, }, }, end -- Why was this so hard ffs theorem nzero_impl_abs_eventually_bounded_below (f : cau_seq) (hnf0 : ¬f ≈ 0) : ∃ (δ : myrat) (N : mynat), 0 < δ ∧ ∀ n : mynat, N ≤ n → δ < abs (f.val n) := begin change ¬(f.equivalent 0) at hnf0, unfold cau_seq.equivalent at hnf0, rw not_forall at hnf0, cases hnf0 with ε hnf0, rw not_imp at hnf0, cases hnf0 with hε hnf0, rw not_exists at hnf0, have hfcau := f.property (ε / 2) (half_pos hε), cases hfcau with N hfcau, existsi (ε / 2), existsi N, split, exact half_pos hε, intros n hn, have hfN := hnf0 N, rw not_forall at hfN, cases hfN with m hm, rw not_imp at hm, cases hm with hNm hm, change ¬abs (f.val m - 0) < ε at hm, rw [sub_def, neg_zero, myring.add_zero] at hm, have := hfcau _ _ hn hNm, change ¬¬ε ≤ abs (f.val m) at hm, rw not_not at hm, clear hnf0 hn hNm hfcau, -- This is why P ≠ NP rw ←abs_abs, rw ←myring.add_zero (abs (f.val n)), rw ←myring.neg_add (abs (f.val m)), rw ←myring.add_assoc, rw ←neg_neg (abs (f.val n)), rw add_comm _ (-abs _), rw ←abs_neg, rw neg_distr, rw neg_distr, rw neg_neg, rw neg_neg, rw ←sub_def, rw ←sub_def, apply lt_le_chain (abs (abs (abs (f.val m) - abs (f.val n)) - abs (abs (f.val m)))), { rw abs_abs, rw abs_sub_switch, apply lt_le_chain (abs (f.val m) - abs (abs (f.val m) - abs (f.val n))), { rw sub_def, rw ←minus_half myrat.two_nzero, rw sub_def, apply le_lt_comb, assumption, { rw ←lt_neg_switch_iff, apply le_lt_chain (abs (f.val m - f.val n)), exact triangle_ineq_sub _ _, assumption, }, }, exact self_le_abs _, }, exact triangle_ineq_sub _ _, end end cau_seq end hidden
a12be41b29e9b5d9943c7aab8dcba03936f8eebf
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/try_for_heap.lean
85db58b7d580cc28bb7d534980a146c28b53c00e
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
2,067
lean
constant heap : Type constant ptr : Type constant val : Type constant pt : ptr → val → heap constant hunion : heap → heap → heap constant is_def : heap → Prop infix `∙`:60 := hunion infix `↣`:70 := pt /- constant hunion_is_assoc : is_associative heap hunion constant hunion_is_comm : is_commutative heap hunion attribute [instance] hunion_is_comm hunion_is_assoc axiom noalias : ∀ (h : heap) (y₁ y₂ : ptr) (w₁ w₂ : val), is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂ -/ open tactic meta def my_tac : tactic unit := using_smt `[ { [smt] intros, smt_tactic.add_lemmas_from_facts, eblast } ] -- set_option profiler true example (h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val) (hcomm : ∀ x y, x ∙ y = y ∙ x) (hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z)) (hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂) : is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ := by my_tac -- should work example (h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val) (hcomm : ∀ x y, x ∙ y = y ∙ x) (hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z)) (hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂) : is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ := by try_for 100 $ my_tac -- should timeout example (h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val) (hcomm : ∀ x y, x ∙ y = y ∙ x) (hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z)) (hnoalias : ∀ h y₁ y₂ w₁ w₂, is_def (h ∙ y₁ ↣ w₁ ∙ y₂ ↣ w₂) → y₁ ≠ y₂) : is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ := by try_for 10000 $ my_tac -- should work
4a159b7c447ec57e272ddef908543cc54b7e2704
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/group_theory/monoid_localization.lean
348acf2a15e55bac933d7f1f1d70d4740662a0ed
[ "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
54,848
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import group_theory.congruence import algebra.group.units import algebra.punit_instances /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M →* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M × S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. Given such a localization map `f : M →* N`, we can define the surjection `localization_map.mk'` sending `(x, y) : M × S` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : M →* P` such that `g(S) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `N` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We also define the quotient of `M × S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M × S` satisfying '`∀ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (x₂, y₂)` by `s` whenever `(x₁, y₁) ∼ (x₂, y₂)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, `localization`, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_monoid_of_mk'` and associated lemmas. These show the quotient map `mk : M → S → localization S` equals the surjection `localization_map.mk'` induced by the map `monoid_of : localization_map S (localization S)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_monoid_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ set_option old_structure_cmd true namespace add_submonoid variables {M : Type*} [add_comm_monoid M] (S : add_submonoid M) (N : Type*) [add_comm_monoid N] /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M →+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map extends add_monoid_hom M N := (map_add_units' : ∀ y : S, is_add_unit (to_fun y)) (surj' : ∀ z : N, ∃ x : M × S, z + to_fun x.2 = to_fun x.1) (eq_iff_exists' : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x + c = y + c) /-- The add_monoid hom underlying a `localization_map` of `add_comm_monoid`s. -/ add_decl_doc localization_map.to_add_monoid_hom end add_submonoid variables {M : Type*} [comm_monoid M] (S : submonoid M) (N : Type*) [comm_monoid N] {P : Type*} [comm_monoid P] namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M →* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map extends monoid_hom M N := (map_units' : ∀ y : S, is_unit (to_fun y)) (surj' : ∀ z : N, ∃ x : M × S, z * to_fun x.2 = to_fun x.1) (eq_iff_exists' : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x * c = y * c) attribute [to_additive add_submonoid.localization_map] submonoid.localization_map attribute [to_additive add_submonoid.localization_map.to_add_monoid_hom] submonoid.localization_map.to_monoid_hom /-- The monoid hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_monoid_hom end submonoid namespace localization run_cmd to_additive.map_namespace `localization `add_localization /-- The congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`. -/ @[to_additive "The congruence relation on `M × S`, `M` an `add_comm_monoid` and `S` an `add_submonoid` of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(0, 0) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`."] def r (S : submonoid M) : con (M × S) := Inf {c | ∀ y : S, c 1 (y, y)} /-- An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. -/ @[to_additive "An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`."] def r' : con (M × S) := begin refine { r := λ a b : M × S, ∃ c : S, a.1 * b.2 * c = b.1 * a.2 * c, iseqv := ⟨λ a, ⟨1, rfl⟩, λ a b ⟨c, hc⟩, ⟨c, hc.symm⟩, _⟩, .. }, { rintros a b c ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use b.2 * t₁ * t₂, simp only [submonoid.coe_mul], calc a.1 * c.2 * (b.2 * t₁ * t₂) = a.1 * b.2 * t₁ * c.2 * t₂ : by ac_refl ... = b.1 * c.2 * t₂ * a.2 * t₁ : by { rw ht₁, ac_refl } ... = c.1 * a.2 * (b.2 * t₁ * t₂) : by { rw ht₂, ac_refl } }, { rintros a b c d ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use t₁ * t₂, calc (a.1 * c.1) * (b.2 * d.2) * (t₁ * t₂) = (a.1 * b.2 * t₁) * (c.1 * d.2 * t₂) : by ac_refl ... = (b.1 * d.1) * (a.2 * c.2) * (t₁ * t₂) : by { rw [ht₁, ht₂], ac_refl } } end /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ @[to_additive "The additive congruence relation used to localize an `add_comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `add_localization.r`) or explicitly (see `add_localization.r'`)."] theorem r_eq_r' : r S = r' S := le_antisymm (Inf_le $ λ _, ⟨1, by simp⟩) $ le_Inf $ λ b H ⟨p, q⟩ y ⟨t, ht⟩, begin rw [← mul_one (p, q), ← mul_one y], refine b.trans (b.mul (b.refl _) (H (y.2 * t))) _, convert b.symm (b.mul (b.refl y) (H (q * t))) using 1, rw [prod.mk_mul_mk, submonoid.coe_mul, ← mul_assoc, ht, mul_left_comm, mul_assoc], refl end variables {S} @[to_additive] lemma r_iff_exists {x y : M × S} : r S x y ↔ ∃ c : S, x.1 * y.2 * c = y.1 * x.2 * c := by rw r_eq_r' S; refl end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ @[to_additive add_localization "The localization of an `add_comm_monoid` at one of its submonoids (as a quotient type)."] def localization := (localization.r S).quotient namespace localization @[to_additive] instance inhabited : inhabited (localization S) := con.quotient.inhabited @[to_additive] instance : comm_monoid (localization S) := (r S).comm_monoid variables {S} /-- Given a `comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`. -/ @[to_additive "Given an `add_comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`."] def mk (x : M) (y : S) : localization S := (r S).mk' (x, y) @[elab_as_eliminator, to_additive] theorem ind {p : localization S → Prop} (H : ∀ (y : M × S), p (mk y.1 y.2)) (x) : p x := by rcases x; convert H x; exact prod.mk.eta.symm @[elab_as_eliminator, to_additive] theorem induction_on {p : localization S → Prop} (x) (H : ∀ (y : M × S), p (mk y.1 y.2)) : p x := ind H x @[elab_as_eliminator, to_additive] theorem induction_on₂ {p : localization S → localization S → Prop} (x y) (H : ∀ (x y : M × S), p (mk x.1 x.2) (mk y.1 y.2)) : p x y := induction_on x $ λ x, induction_on y $ H x @[elab_as_eliminator, to_additive] theorem induction_on₃ {p : localization S → localization S → localization S → Prop} (x y z) (H : ∀ (x y z : M × S), p (mk x.1 x.2) (mk y.1 y.2) (mk z.1 z.2)) : p x y z := induction_on₂ x y $ λ x y, induction_on z $ H x y @[to_additive] lemma one_rel (y : S) : r S 1 (y, y) := λ b hb, hb y @[to_additive] theorem r_of_eq {x y : M × S} (h : y.1 * x.2 = x.1 * y.2) : r S x y := r_iff_exists.2 ⟨1, by rw h⟩ end localization variables {S N} namespace monoid_hom /-- Makes a localization map from a `comm_monoid` hom satisfying the characteristic predicate. -/ @[to_additive "Makes a localization map from an `add_comm_monoid` hom satisfying the characteristic predicate."] def to_localization_map (f : M →* N) (H1 : ∀ y : S, is_unit (f y)) (H2 : ∀ z, ∃ x : M × S, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : S, x * c = y * c) : submonoid.localization_map S N := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end monoid_hom namespace submonoid namespace localization_map /-- Short for `to_monoid_hom`; used to apply a localization map as a function. -/ @[to_additive "Short for `to_add_monoid_hom`; used to apply a localization map as a function."] abbreviation to_map (f : localization_map S N) := f.to_monoid_hom @[to_additive, ext] lemma ext {f g : localization_map S N} (h : ∀ x, f.to_map x = g.to_map x) : f = g := by cases f; cases g; simp only; exact funext h attribute [ext] add_submonoid.localization_map.ext @[to_additive] lemma ext_iff {f g : localization_map S N} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ @[to_additive] lemma to_map_injective : function.injective (@localization_map.to_map _ _ S N _) := λ _ _ h, ext $ monoid_hom.ext_iff.1 h @[to_additive] lemma map_units (f : localization_map S N) (y : S) : is_unit (f.to_map y) := f.4 y @[to_additive] lemma surj (f : localization_map S N) (z : N) : ∃ x : M × S, z * f.to_map x.2 = f.to_map x.1 := f.5 z @[to_additive] lemma eq_iff_exists (f : localization_map S N) {x y} : f.to_map x = f.to_map y ↔ ∃ c : S, x * c = y * c := f.6 x y /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ @[to_additive "Given a localization map `f : M →+ N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x - f y = z`."] noncomputable def sec (f : localization_map S N) (z : N) : M × S := classical.some $ f.surj z @[to_additive] lemma sec_spec {f : localization_map S N} (z : N) : z * f.to_map (f.sec z).2 = f.to_map (f.sec z).1 := classical.some_spec $ f.surj z @[to_additive] lemma sec_spec' {f : localization_map S N} (z : N) : f.to_map (f.sec z).1 = f.to_map (f.sec z).2 * z := by rw [mul_comm, sec_spec] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `w * (f y)⁻¹ = z ↔ w = f y * z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `w - f y = z ↔ w = f y + z`."] lemma mul_inv_left {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : w * ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ = z ↔ w = f y * z := by rw mul_comm; convert units.inv_mul_eq_iff_eq_mul _; exact (is_unit.coe_lift_right (f.mrestrict S) h _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w * (f y)⁻¹ ↔ z * f y = w`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w - f y ↔ z + f y = w`."] lemma mul_inv_right {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : z = w * ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ ↔ z * f y = w := by rw [eq_comm, mul_inv_left h, mul_comm, eq_comm] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ * (f y₁)⁻¹ = f x₂ * (f y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁)`. -/ @[simp, to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ - f y₁ = f x₂ - f y₂ ↔ f (x₁ + y₂) = f (x₂ + y₁)`."] lemma mul_inv {f : M →* N} (h : ∀ y : S, is_unit (f y)) {x₁ x₂} {y₁ y₂ : S} : f x₁ * ↑(is_unit.lift_right (f.mrestrict S) h y₁)⁻¹ = f x₂ * ↑(is_unit.lift_right (f.mrestrict S) h y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁) := by rw [mul_inv_right h, mul_assoc, mul_comm _ (f y₂), ←mul_assoc, mul_inv_left h, mul_comm x₂, f.map_mul, f.map_mul] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y, z ∈ S`, we have `(f y)⁻¹ = (f z)⁻¹ → f y = f z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y, z ∈ S`, we have `- (f y) = - (f z) → f y = f z`."] lemma inv_inj {f : M →* N} (hf : ∀ y : S, is_unit (f y)) {y z} (h : (is_unit.lift_right (f.mrestrict S) hf y)⁻¹ = (is_unit.lift_right (f.mrestrict S) hf z)⁻¹) : f y = f z := by rw [←mul_one (f y), eq_comm, ←mul_inv_left hf y (f z) 1, h]; convert units.inv_mul _; exact (is_unit.coe_lift_right (f.mrestrict S) hf _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y ∈ S`, `(f y)⁻¹` is unique. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y ∈ S`, `- (f y)` is unique."] lemma inv_unique {f : M →* N} (h : ∀ y : S, is_unit (f y)) {y : S} {z} (H : f y * z = 1) : ↑(is_unit.lift_right (f.mrestrict S) h y)⁻¹ = z := by rw [←one_mul ↑(_)⁻¹, mul_inv_left, ←H] variables (f : localization_map S N) @[to_additive] lemma map_right_cancel {x y} {c : S} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := begin rw [f.to_map.map_mul, f.to_map.map_mul] at h, cases f.map_units c with u hu, rw ←hu at h, exact (units.mul_right_inj u).1 h, end @[to_additive] lemma map_left_cancel {x y} {c : S} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.map_right_cancel $ by rw [mul_comm _ x, mul_comm _ y, h] /-- Given a localization map `f : M →* N`, the surjection sending `(x, y) : M × S` to `f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N`, the surjection sending `(x, y) : M × S` to `f x - f y`."] noncomputable def mk' (f : localization_map S N) (x : M) (y : S) : N := f.to_map x * ↑(is_unit.lift_right (f.to_map.mrestrict S) f.map_units y)⁻¹ @[to_additive] lemma mk'_mul (x₁ x₂ : M) (y₁ y₂ : S) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := (mul_inv_left f.map_units _ _ _).2 $ show _ = _ * (_ * _ * (_ * _)), by rw [←mul_assoc, ←mul_assoc, mul_inv_right f.map_units, mul_assoc, mul_assoc, mul_comm _ (f.to_map x₂), ←mul_assoc, ←mul_assoc, mul_inv_right f.map_units, submonoid.coe_mul, f.to_map.map_mul, f.to_map.map_mul]; ac_refl @[to_additive] lemma mk'_one (x) : f.mk' x (1 : S) = f.to_map x := by rw [mk', monoid_hom.map_one]; exact mul_one _ /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z * f y = f x`, then `f x * (f y)⁻¹ = z`. -/ @[simp, to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z + f y = f x`, then `f x - f y = z`."] lemma mk'_sec (z : N) : f.mk' (f.sec z).1 (f.sec z).2 = z := show _ * _ = _, by rw [←sec_spec, mul_inv_left, mul_comm] @[to_additive] lemma mk'_surjective (z : N) : ∃ x (y : S), f.mk' x y = z := ⟨(f.sec z).1, (f.sec z).2, f.mk'_sec z⟩ @[to_additive] lemma mk'_spec (x) (y : S) : f.mk' x y * f.to_map y = f.to_map x := show _ * _ * _ = _, by rw [mul_assoc, mul_comm _ (f.to_map y), ←mul_assoc, mul_inv_left, mul_comm] @[to_additive] lemma mk'_spec' (x) (y : S) : f.to_map y * f.mk' x y = f.to_map x := by rw [mul_comm, mk'_spec] @[to_additive] theorem eq_mk'_iff_mul_eq {x} {y : S} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := ⟨λ H, by rw [H, mk'_spec], λ H, by erw [mul_inv_right, H]; refl⟩ @[to_additive] theorem mk'_eq_iff_eq_mul {x} {y : S} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := by rw [eq_comm, eq_mk'_iff_mul_eq, eq_comm] @[to_additive] lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := ⟨λ H, by rw [f.to_map.map_mul, f.mk'_eq_iff_eq_mul.1 H, mul_assoc, mul_comm (f.to_map _), ←mul_assoc, mk'_spec, f.to_map.map_mul], λ H, by rw [mk'_eq_iff_eq_mul, mk', mul_assoc, mul_comm _ (f.to_map y₁), ←mul_assoc, ←f.to_map.map_mul, ←H, f.to_map.map_mul, mul_inv_right f.map_units]⟩ @[to_additive] protected lemma eq {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : S, a₁ * b₂ * c = b₁ * a₂ * c := f.mk'_eq_iff_eq.trans $ f.eq_iff_exists @[to_additive] protected lemma eq' {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ localization.r S (a₁, a₂) (b₁, b₂) := by rw [f.eq, localization.r_iff_exists] @[to_additive] lemma eq_iff_eq (g : localization_map S P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.eq_iff_exists.trans g.eq_iff_exists.symm @[to_additive] lemma mk'_eq_iff_mk'_eq (g : localization_map S P) {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.eq'.trans g.eq'.symm /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `f x₁ * (f y₁)⁻¹ * f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ * y₂ * c = x₂ * y₁ * c`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `(f x₁ - f y₁) + f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ + y₂ + c = x₂ + y₁ + c`."] lemma exists_of_sec_mk' (x) (y : S) : ∃ c : S, x * (f.sec $ f.mk' x y).2 * c = (f.sec $ f.mk' x y).1 * y * c := f.eq_iff_exists.1 $ f.mk'_eq_iff_eq.1 $ (mk'_sec _ _).symm @[to_additive] lemma mk'_eq_of_eq {a₁ b₁ : M} {a₂ b₂ : S} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.mk'_eq_iff_eq.2 $ H ▸ rfl @[simp, to_additive] lemma mk'_self' (y : S) : f.mk' (y : M) y = 1 := show _ * _ = _, by rw [mul_inv_left, mul_one] @[simp, to_additive] lemma mk'_self (x) (H : x ∈ S) : f.mk' x ⟨x, H⟩ = 1 := by convert mk'_self' _ _; refl @[to_additive] lemma mul_mk'_eq_mk'_of_mul (x₁ x₂) (y : S) : f.to_map x₁ * f.mk' x₂ y = f.mk' (x₁ * x₂) y := by rw [←mk'_one, ←mk'_mul, one_mul] @[to_additive] lemma mk'_mul_eq_mk'_of_mul (x₁ x₂) (y : S) : f.mk' x₂ y * f.to_map x₁ = f.mk' (x₁ * x₂) y := by rw [mul_comm, mul_mk'_eq_mk'_of_mul] @[to_additive] lemma mul_mk'_one_eq_mk' (x) (y : S) : f.to_map x * f.mk' 1 y = f.mk' x y := by rw [mul_mk'_eq_mk'_of_mul, mul_one] @[simp, to_additive] lemma mk'_mul_cancel_right (x : M) (y : S) : f.mk' (x * y) y = f.to_map x := by rw [←mul_mk'_one_eq_mk', f.to_map.map_mul, mul_assoc, mul_mk'_one_eq_mk', mk'_self', mul_one] @[to_additive] lemma mk'_mul_cancel_left (x) (y : S) : f.mk' ((y : M) * x) y = f.to_map x := by rw [mul_comm, mk'_mul_cancel_right] @[to_additive] lemma is_unit_comp (j : N →* P) (y : S) : is_unit (j.comp f.to_map y) := ⟨units.map j $ is_unit.lift_right (f.to_map.mrestrict S) f.map_units y, show j _ = j _, from congr_arg j $ (is_unit.coe_lift_right (f.to_map.mrestrict S) f.map_units _)⟩ variables {g : M →* P} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g(S) ⊆ units P`, `f x = f y → g x = g y` for all `x y : M`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g(S) ⊆ add_units P`, `f x = f y → g x = g y` for all `x y : M`."] lemma eq_of_eq (hg : ∀ y : S, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := begin obtain ⟨c, hc⟩ := f.eq_iff_exists.1 h, rw [←mul_one (g x), ←is_unit.mul_lift_right_inv (g.mrestrict S) hg c], show _ * (g c * _) = _, rw [←mul_assoc, ←g.map_mul, hc, mul_inv_left hg, g.map_mul, mul_comm], end /-- Given `comm_monoid`s `M, P`, localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, and `g : M →* P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`. -/ @[to_additive "Given `add_comm_monoid`s `M, P`, localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, and `g : M →+ P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`."] lemma comp_eq_of_eq {T : submonoid P} {Q : Type*} [comm_monoid Q] (hg : ∀ y : S, g y ∈ T) (k : localization_map T Q) {x y} (h : f.to_map x = f.to_map y) : k.to_map (g x) = k.to_map (g y) := f.eq_of_eq (λ y : S, show is_unit (k.to_map.comp g y), from k.map_units ⟨g y, hg y⟩) h variables (hg : ∀ y : S, is_unit (g y)) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x - g y`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def lift : N →* P := { to_fun := λ z, g (f.sec z).1 * ↑(is_unit.lift_right (g.mrestrict S) hg (f.sec z).2)⁻¹, map_one' := by rw [mul_inv_left, mul_one]; exact f.eq_of_eq hg (by rw [←sec_spec, one_mul]), map_mul' := λ x y, begin rw [mul_inv_left hg, ←mul_assoc, ←mul_assoc, mul_inv_right hg, mul_comm _ (g (f.sec y).1), ←mul_assoc, ←mul_assoc, mul_inv_right hg], repeat { rw ←g.map_mul }, exact f.eq_of_eq hg (by repeat { rw f.to_map.map_mul <|> rw sec_spec' }; ac_refl) end } variables {S g} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : M, y ∈ S`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x - f y` to `g x - g y` for all `x : M, y ∈ S`."] lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.mrestrict S) hg y)⁻¹ := (mul_inv hg).2 $ f.eq_of_eq hg $ by rw [f.to_map.map_mul, f.to_map.map_mul, sec_spec', mul_assoc, f.mk'_spec, mul_comm] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec (z v) : f.lift hg z = v ↔ g (f.sec z).1 = g (f.sec z).2 * v := mul_inv_left hg _ _ v /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v w : P`, we have `f.lift hg z * w = v ↔ g x * w = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v w : P`, we have `f.lift hg z + w = v ↔ g x + w = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec_mul (z w v) : f.lift hg z * w = v ↔ g (f.sec z).1 * w = g (f.sec z).2 * v := begin rw mul_comm, show _ * (_ * _) = _ ↔ _, rw [←mul_assoc, mul_inv_left hg, mul_comm], end @[to_additive] lemma lift_mk'_spec (x v) (y : S) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := by rw f.lift_mk' hg; exact mul_inv_left hg _ _ _ /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `f.lift hg z * g y = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `f.lift hg z + g y = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_right (z) : f.lift hg z * g (f.sec z).2 = g (f.sec z).1 := show _ * _ * _ = _, by erw [mul_assoc, is_unit.lift_right_inv_mul, mul_one] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `g y * f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `g y + f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_left (z) : g (f.sec z).2 * f.lift hg z = g (f.sec z).1 := by rw [mul_comm, lift_mul_right] @[simp, to_additive] lemma lift_eq (x : M) : f.lift hg (f.to_map x) = g x := by rw [lift_spec, ←g.map_mul]; exact f.eq_of_eq hg (by rw [sec_spec', f.to_map.map_mul]) @[to_additive] lemma lift_eq_iff {x y : M × S} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := by rw [lift_mk', lift_mk', mul_inv hg] @[simp, to_additive] lemma lift_comp : (f.lift hg).comp f.to_map = g := by ext; exact f.lift_eq hg _ @[simp, to_additive] lemma lift_of_comp (j : N →* P) : f.lift (f.is_unit_comp j) = j := begin ext, rw lift_spec, show j _ = j _ * _, erw [←j.map_mul, sec_spec'], end @[to_additive] lemma epic_of_localization_map {j k : N →* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := begin rw [←f.lift_of_comp j, ←f.lift_of_comp k], congr' 1 with x, exact h x, end @[to_additive] lemma lift_unique {j : N →* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := begin ext, rw [lift_spec, ←hj, ←hj, ←j.map_mul], apply congr_arg, rw ←sec_spec', end @[simp, to_additive] lemma lift_id (x) : f.lift f.map_units x = x := monoid_hom.ext_iff.1 (f.lift_of_comp $ monoid_hom.id N) x /-- Given two localization maps `f : M →* N, k : M →* P` for a submonoid `S ⊆ M`, the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P` induced by `k`. -/ @[simp, to_additive] lemma lift_left_inverse {k : localization_map S P} (z : N) : k.lift f.map_units (f.lift k.map_units z) = z := begin rw lift_spec, cases f.surj z with x hx, conv_rhs {congr, skip, rw f.eq_mk'_iff_mul_eq.2 hx}, rw [mk', ←mul_assoc, mul_inv_right f.map_units, ←f.to_map.map_mul, ←f.to_map.map_mul], apply k.eq_of_eq f.map_units, rw [k.to_map.map_mul, k.to_map.map_mul, ←sec_spec, mul_assoc, lift_spec_mul], repeat { rw ←k.to_map.map_mul }, apply f.eq_of_eq k.map_units, repeat { rw f.to_map.map_mul }, rw [sec_spec', ←hx], ac_refl, end @[to_additive] lemma lift_surjective_iff : function.surjective (f.lift hg) ↔ ∀ v : P, ∃ x : M × S, v * g x.2 = g x.1 := begin split, { intros H v, obtain ⟨z, hz⟩ := H v, obtain ⟨x, hx⟩ := f.surj z, use x, rw [←hz, f.eq_mk'_iff_mul_eq.2 hx, lift_mk', mul_assoc, mul_comm _ (g ↑x.2)], erw [is_unit.mul_lift_right_inv (g.mrestrict S) hg, mul_one] }, { intros H v, obtain ⟨x, hx⟩ := H v, use f.mk' x.1 x.2, rw [lift_mk', mul_inv_left hg, mul_comm, ←hx] } end @[to_additive] lemma lift_injective_iff : function.injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := begin split, { intros H x y, split, { exact f.eq_of_eq hg }, { intro h, rw [←f.lift_eq hg, ←f.lift_eq hg] at h, exact H h }}, { intros H z w h, obtain ⟨x, hx⟩ := f.surj z, obtain ⟨y, hy⟩ := f.surj w, rw [←f.mk'_sec z, ←f.mk'_sec w], exact (mul_inv f.map_units).2 ((H _ _).2 $ (mul_inv hg).1 h) } end variables {T : submonoid P} (hy : ∀ y : S, g y ∈ T) {Q : Type*} [comm_monoid Q] (k : localization_map T Q) /-- Given a `comm_monoid` homomorphism `g : M →* P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →* N` and `k : P →* Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a `add_comm_monoid` homomorphism `g : M →+ P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced add_monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →+ N` and `k : P →+ Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) - k (g y)`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def map : N →* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} @[to_additive] lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp, to_additive] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ @[to_additive] lemma map_mk' (x) (y : S) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := begin rw [map, lift_mk', mul_inv_left], { show k.to_map (g x) = k.to_map (g y) * _, rw mul_mk'_eq_mk'_of_mul, exact (k.mk'_mul_cancel_left (g x) ⟨(g y), hy y⟩).symm }, end /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) * u` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) + u` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_spec (z u) : f.map hy k z = u ↔ k.to_map (g (f.sec z).1) = k.to_map (g (f.sec z).2) * u := f.lift_spec (λ y, k.map_units ⟨g y, hy y⟩) _ _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `f.map hy k z + k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_right (z) : f.map hy k z * (k.to_map (g (f.sec z).2)) = k.to_map (g (f.sec z).1) := f.lift_mul_right (λ y, k.map_units ⟨g y, hy y⟩) _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `k (g y) + f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_left (z) : k.to_map (g (f.sec z).2) * f.map hy k z = k.to_map (g (f.sec z).1) := by rw [mul_comm, f.map_mul_right] @[simp, to_additive] lemma map_id (z : N) : f.map (λ y, show monoid_hom.id M y ∈ S, from y.2) f z = z := f.lift_id z /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_comp_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := begin ext z, show j.to_map _ * _ = j.to_map (l _) * _, { rw [mul_inv_left, ←mul_assoc, mul_inv_right], show j.to_map _ * j.to_map (l (g _)) = j.to_map (l _) * _, rw [←j.to_map.map_mul, ←j.to_map.map_mul, ←l.map_mul, ←l.map_mul], exact k.comp_eq_of_eq hl j (by rw [k.to_map.map_mul, k.to_map.map_mul, sec_spec', mul_assoc, map_mul_right]) }, end /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl section away_map variables (x : M) /-- Given `x : M`, the type of `comm_monoid` homomorphisms `f : M →* N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`. -/ @[reducible, to_additive "Given `x : M`, the type of `add_comm_monoid` homomorphisms `f : M →+ N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`."] def away_map (N' : Type*) [comm_monoid N'] := localization_map (powers x) N' variables (F : away_map x N) /-- Given `x : M` and a localization map `F : M →* N` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : N := F.mk' 1 ⟨x, mem_powers _⟩ /-- Given `x : M`, a localization map `F : M →* N` away from `x`, and a map of `comm_monoid`s `g : M →* P` such that `g x` is invertible, the homomorphism induced from `N` to `P` sending `z : N` to `g y * (g x)⁻ⁿ`, where `y : M, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : N →* P := F.lift $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : M) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : M` and localization maps `F : M →* N, G : M →* P` away from `x` and `x * y` respectively, the homomorphism induced from `N` to `P`. -/ noncomputable def away_to_away_right (y : M) (G : away_map (x * y) P) : N →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map end submonoid namespace add_submonoid namespace localization_map section away_map variables {A : Type*} [add_comm_monoid A] (x : A) {B : Type*} [add_comm_monoid B] (F : away_map x B) {C : Type*} [add_comm_monoid C] {g : A →+ C} /-- Given `x : A` and a localization map `F : A →+ B` away from `x`, `neg_self` is `- (F x)`. -/ noncomputable def away_map.neg_self : B := F.mk' 0 ⟨x, mem_multiples _⟩ /-- Given `x : A`, a localization map `F : A →+ B` away from `x`, and a map of `add_comm_monoid`s `g : A →+ C` such that `g x` is invertible, the homomorphism induced from `B` to `C` sending `z : B` to `g y - n • g x`, where `y : A, n : ℕ` are such that `z = F y - n • F x`. -/ noncomputable def away_map.lift (hg : is_add_unit (g x)) : B →+ C := F.lift $ λ y, show is_add_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_nsmul], exact is_add_unit.map (add_monoid_hom.of $ (λ x, n •ℕ x)) hg, end @[simp] lemma away_map.lift_eq (hg : is_add_unit (g x)) (a : A) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_add_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : A` and localization maps `F : A →+ B, G : A →+ C` away from `x` and `x + y` respectively, the homomorphism induced from `B` to `C`. -/ noncomputable def away_to_away_right (y : A) (G : away_map (x + y) C) : B →+ C := F.lift x $ show is_add_unit (G.to_map x), from is_add_unit_of_add_eq_zero (G.to_map x) (G.mk' y ⟨x + y, mem_multiples _⟩) $ by rw [add_mk'_eq_mk'_of_add, mk'_self] end away_map end localization_map end add_submonoid namespace submonoid namespace localization_map variables (f : S.localization_map N) {g : M →* P} (hg : ∀ (y : S), is_unit (g y)) {T : submonoid P} {Q : Type*} [comm_monoid Q] /-- If `f : M →* N` and `k : M →* P` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `P`. -/ @[to_additive "If `f : M →+ N` and `k : M →+ R` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `R`."] noncomputable def mul_equiv_of_localizations (k : localization_map S P) : N ≃* P := ⟨f.lift k.map_units, k.lift f.map_units, f.lift_left_inverse, k.lift_left_inverse, monoid_hom.map_mul _⟩ @[to_additive, simp] lemma mul_equiv_of_localizations_apply {k : localization_map S P} {x} : f.mul_equiv_of_localizations k x = f.lift k.map_units x := rfl @[to_additive, simp] lemma mul_equiv_of_localizations_symm_apply {k : localization_map S P} {x} : (f.mul_equiv_of_localizations k).symm x = k.lift f.map_units x := rfl @[to_additive] lemma mul_equiv_of_localizations_symm_eq_mul_equiv_of_localizations {k : localization_map S P} : (k.mul_equiv_of_localizations f).symm = f.mul_equiv_of_localizations k := rfl /-- If `f : M →* N` is a localization map for a submonoid `S` and `k : N ≃* P` is an isomorphism of `comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`. -/ @[to_additive "If `f : M →+ N` is a localization map for a submonoid `S` and `k : N ≃+ P` is an isomorphism of `add_comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`."] def of_mul_equiv_of_localizations (k : N ≃* P) : localization_map S P := (k.to_monoid_hom.comp f.to_map).to_localization_map (λ y, is_unit_comp f k.to_monoid_hom y) (λ v, let ⟨z, hz⟩ := k.to_equiv.surjective v in let ⟨x, hx⟩ := f.surj z in ⟨x, show v * k _ = k _, by rw [←hx, k.map_mul, ←hz]; refl⟩) (λ x y, (k.to_equiv.apply_eq_iff_eq _ _).trans $ f.eq_iff_exists) @[to_additive, simp] lemma of_mul_equiv_of_localizations_apply {k : N ≃* P} (x) : (f.of_mul_equiv_of_localizations k).to_map x = k (f.to_map x) := rfl @[to_additive] lemma of_mul_equiv_of_localizations_eq {k : N ≃* P} : (f.of_mul_equiv_of_localizations k).to_map = k.to_monoid_hom.comp f.to_map := rfl @[to_additive] lemma symm_comp_of_mul_equiv_of_localizations_apply {k : N ≃* P} (x) : k.symm ((f.of_mul_equiv_of_localizations k).to_map x) = f.to_map x := k.symm_apply_apply (f.to_map x) @[to_additive] lemma symm_comp_of_mul_equiv_of_localizations_apply' {k : P ≃* N} (x) : k ((f.of_mul_equiv_of_localizations k.symm).to_map x) = f.to_map x := k.apply_symm_apply (f.to_map x) @[to_additive] lemma of_mul_equiv_of_localizations_eq_iff_eq {k : N ≃* P} {x y} : (f.of_mul_equiv_of_localizations k).to_map x = y ↔ f.to_map x = k.symm y := k.to_equiv.eq_symm_apply.symm @[to_additive] lemma mul_equiv_of_localizations_right_inv (k : localization_map S P) : f.of_mul_equiv_of_localizations (f.mul_equiv_of_localizations k) = k := to_map_injective $ f.lift_comp k.map_units @[to_additive, simp] lemma mul_equiv_of_localizations_right_inv_apply {k : localization_map S P} {x} : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_localizations k)).to_map x = k.to_map x := ext_iff.1 (f.mul_equiv_of_localizations_right_inv k) x @[to_additive] lemma mul_equiv_of_localizations_left_inv (k : N ≃* P) : f.mul_equiv_of_localizations (f.of_mul_equiv_of_localizations k) = k := mul_equiv.ext $ monoid_hom.ext_iff.1 $ f.lift_of_comp k.to_monoid_hom @[to_additive, simp] lemma mul_equiv_of_localizations_left_inv_apply {k : N ≃* P} (x) : f.mul_equiv_of_localizations (f.of_mul_equiv_of_localizations k) x = k x := by rw mul_equiv_of_localizations_left_inv @[simp, to_additive] lemma of_mul_equiv_of_localizations_id : f.of_mul_equiv_of_localizations (mul_equiv.refl N) = f := by ext; refl @[to_additive] lemma of_mul_equiv_of_localizations_comp {k : N ≃* P} {j : P ≃* Q} : (f.of_mul_equiv_of_localizations (k.trans j)).to_map = j.to_monoid_hom.comp (f.of_mul_equiv_of_localizations k).to_map := by ext; refl /-- Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`. -/ @[to_additive "Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`."] def of_mul_equiv_of_dom {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : localization_map T N := let H' : S.comap k.to_monoid_hom = T := H ▸ (submonoid.ext' $ T.1.preimage_image_eq k.to_equiv.injective) in (f.to_map.comp k.to_monoid_hom).to_localization_map (λ y, let ⟨z, hz⟩ := f.map_units ⟨k y, H ▸ set.mem_image_of_mem k y.2⟩ in ⟨z, hz⟩) (λ z, let ⟨x, hx⟩ := f.surj z in let ⟨v, hv⟩ := k.to_equiv.surjective x.1 in let ⟨w, hw⟩ := k.to_equiv.surjective x.2 in ⟨(v, ⟨w, H' ▸ show k w ∈ S, from hw.symm ▸ x.2.2⟩), show z * f.to_map (k.to_equiv w) = f.to_map (k.to_equiv v), by erw [hv, hw, hx]; refl⟩) (λ x y, show f.to_map _ = f.to_map _ ↔ _, by erw f.eq_iff_exists; exact ⟨λ ⟨c, hc⟩, let ⟨d, hd⟩ := k.to_equiv.surjective c in ⟨⟨d, H' ▸ show k d ∈ S, from hd.symm ▸ c.2⟩, by erw [←hd, ←k.map_mul, ←k.map_mul] at hc; exact k.to_equiv.injective hc⟩, λ ⟨c, hc⟩, ⟨⟨k c, H ▸ set.mem_image_of_mem k c.2⟩, by erw ←k.map_mul; rw [hc, k.map_mul]; refl⟩⟩) @[to_additive, simp] lemma of_mul_equiv_of_dom_apply {k : P ≃* M} (H : T.map k.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map x = f.to_map (k x) := rfl @[to_additive] lemma of_mul_equiv_of_dom_eq {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : (f.of_mul_equiv_of_dom H).to_map = f.to_map.comp k.to_monoid_hom := rfl @[to_additive] lemma of_mul_equiv_of_dom_comp_symm {k : P ≃* M} (H : T.map k.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map (k.symm x) = f.to_map x := congr_arg f.to_map $ k.apply_symm_apply x @[to_additive] lemma of_mul_equiv_of_dom_comp {k : M ≃* P} (H : T.map k.symm.to_monoid_hom = S) (x) : (f.of_mul_equiv_of_dom H).to_map (k x) = f.to_map x := congr_arg f.to_map $ k.symm_apply_apply x /-- A special case of `f ∘ id = f`, `f` a localization map. -/ @[simp, to_additive "A special case of `f ∘ id = f`, `f` a localization map."] lemma of_mul_equiv_of_dom_id : f.of_mul_equiv_of_dom (show S.map (mul_equiv.refl M).to_monoid_hom = S, from submonoid.ext $ λ x, ⟨λ ⟨y, hy, h⟩, h ▸ hy, λ h, ⟨x, h, rfl⟩⟩) = f := by ext; refl /-- Given localization maps `f : M →* N, k : P →* U` for submonoids `S, T` respectively, an isomorphism `j : M ≃* P` such that `j(S) = T` induces an isomorphism of localizations `N ≃* U`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ U` for submonoids `S, T` respectively, an isomorphism `j : M ≃+ P` such that `j(S) = T` induces an isomorphism of localizations `N ≃+ U`."] noncomputable def mul_equiv_of_mul_equiv (k : localization_map T Q) {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : N ≃* Q := f.mul_equiv_of_localizations $ k.of_mul_equiv_of_dom H @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq_map_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H x = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl @[to_additive] lemma mul_equiv_of_mul_equiv_eq_map {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.mul_equiv_of_mul_equiv k H).to_monoid_hom = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H (f.to_map x) = k.to_map (j x) := f.map_eq (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ @[simp, to_additive] lemma mul_equiv_of_mul_equiv_mk' {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x y) : f.mul_equiv_of_mul_equiv k H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.map_mk' (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ _ @[to_additive, simp] lemma of_mul_equiv_of_mul_equiv_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_mul_equiv k H)).to_map x = k.to_map (j x) := ext_iff.1 (f.mul_equiv_of_localizations_right_inv (k.of_mul_equiv_of_dom H)) x @[to_additive] lemma of_mul_equiv_of_mul_equiv {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.of_mul_equiv_of_localizations (f.mul_equiv_of_mul_equiv k H)).to_map = k.to_map.comp j.to_monoid_hom := monoid_hom.ext $ f.of_mul_equiv_of_mul_equiv_apply H end localization_map end submonoid namespace localization variables (S) /-- Natural hom sending `x : M`, `M` a `comm_monoid`, to the equivalence class of `(x, 1)` in the localization of `M` at a submonoid. -/ @[to_additive "Natural homomorphism sending `x : M`, `M` an `add_comm_monoid`, to the equivalence class of `(x, 0)` in the localization of `M` at a submonoid."] def monoid_of : submonoid.localization_map S (localization S) := { map_units' := λ y, is_unit_iff_exists_inv.2 ⟨mk 1 y, (r S).eq.2 $ show r S (_, 1 * y) 1, by simpa using (r S).symm (one_rel y)⟩, surj' := λ z, induction_on z $ λ x, ⟨x, (r S).eq.2 $ show r S (x.1 * x.2, x.2 * 1) (x.1, 1), by rw [mul_comm x.2, ←mul_one (x.1, (1 : S))]; exact (r S).mul ((r S).refl (x.1, 1)) ((r S).symm $ one_rel x.2)⟩, eq_iff_exists' := λ x y, (r S).eq.trans $ r_iff_exists.trans $ show (∃ (c : S), x * 1 * c = y * 1 * c) ↔ _, by rw [mul_one, mul_one], ..(r S).mk'.comp $ monoid_hom.inl M S } variables {S} @[to_additive] lemma mk_one_eq_monoid_of_mk (x) : mk x 1 = (monoid_of S).to_map x := rfl @[to_additive] lemma mk_eq_monoid_of_mk'_apply (x y) : mk x y = (monoid_of S).mk' x y := show _ = _ * _, from (submonoid.localization_map.mul_inv_right (monoid_of S).map_units _ _ _).2 $ begin rw [←mk_one_eq_monoid_of_mk, ←mk_one_eq_monoid_of_mk, show mk x y * mk y 1 = mk (x * y) (1 * y), by rw mul_comm 1 y; refl, show mk x 1 = mk (x * 1) ((1 : S) * 1), by rw [mul_one, mul_one]], exact (con.eq _).2 (con.symm _ $ (localization.r S).mul (con.refl _ (x, 1)) $ one_rel _), end @[simp, to_additive] lemma mk_eq_monoid_of_mk' : mk = (monoid_of S).mk' := funext $ λ _, funext $ λ _, mk_eq_monoid_of_mk'_apply _ _ variables (f : submonoid.localization_map S N) /-- Given a localization map `f : M →* N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`."] noncomputable def mul_equiv_of_quotient (f : submonoid.localization_map S N) : localization S ≃* N := (monoid_of S).mul_equiv_of_localizations f variables {f} @[simp, to_additive] lemma mul_equiv_of_quotient_apply (x) : mul_equiv_of_quotient f x = (monoid_of S).lift f.map_units x := rfl @[simp, to_additive] lemma mul_equiv_of_quotient_mk' (x y) : mul_equiv_of_quotient f ((monoid_of S).mk' x y) = f.mk' x y := (monoid_of S).lift_mk' _ _ _ @[to_additive] lemma mul_equiv_of_quotient_mk (x y) : mul_equiv_of_quotient f (mk x y) = f.mk' x y := by rw mk_eq_monoid_of_mk'_apply; exact mul_equiv_of_quotient_mk' _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_monoid_of (x) : mul_equiv_of_quotient f ((monoid_of S).to_map x) = f.to_map x := (monoid_of S).lift_eq _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_symm_mk' (x y) : (mul_equiv_of_quotient f).symm (f.mk' x y) = (monoid_of S).mk' x y := f.lift_mk' _ _ _ @[to_additive] lemma mul_equiv_of_quotient_symm_mk (x y) : (mul_equiv_of_quotient f).symm (f.mk' x y) = mk x y := by rw mk_eq_monoid_of_mk'_apply; exact mul_equiv_of_quotient_symm_mk' _ _ @[simp, to_additive] lemma mul_equiv_of_quotient_symm_monoid_of (x) : (mul_equiv_of_quotient f).symm (f.to_map x) = (monoid_of S).to_map x := f.lift_eq _ _ section away variables (x : M) /-- Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient. -/ @[reducible, to_additive "Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient."] def away := localization (submonoid.powers x) /-- Given `x : M`, `inv_self` is `x⁻¹` in the localization (as a quotient type) of `M` at the submonoid generated by `x`. -/ @[to_additive "Given `x : M`, `neg_self` is `-x` in the localization (as a quotient type) of `M` at the submonoid generated by `x`."] def away.inv_self : away x := mk 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : M`, the natural hom sending `y : M`, `M` a `comm_monoid`, to the equivalence class of `(y, 1)` in the localization of `M` at the submonoid generated by `x`. -/ @[reducible, to_additive "Given `x : M`, the natural hom sending `y : M`, `M` an `add_comm_monoid`, to the equivalence class of `(y, 0)` in the localization of `M` at the submonoid generated by `x`."] def away.monoid_of : submonoid.localization_map.away_map x (away x) := monoid_of (submonoid.powers x) @[simp, to_additive] lemma away.mk_eq_monoid_of_mk' : mk = (away.monoid_of x).mk' := mk_eq_monoid_of_mk' /-- Given `x : M` and a localization map `f : M →* N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`. -/ @[to_additive "Given `x : M` and a localization map `f : M →+ N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`."] noncomputable def away.mul_equiv_of_quotient (f : submonoid.localization_map.away_map x N) : away x ≃* N := mul_equiv_of_quotient f end away end localization
e647c86f3a9df0a518dd524517529283994e5e75
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/letRecMissingAnnotation.lean
f9e466efe2bb332e35924bb805394dcd36f878e8
[ "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
234
lean
def sum (as : Array Nat) : Nat := let rec go (i : Nat) (s : Nat) : Nat := if h : i < as.size then go (i+2) (s + as.get ⟨i, h⟩) -- Error else s go 0 0 termination_by' measure (fun ⟨i, _⟩ => as.size - i)
d216eca4e753bac0f8c913da850202e9e5c01013
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/conditionally_complete_lattice/group.lean
b9c5bcef8ad2c5ac90958a1fad04a37eeff578db
[ "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,991
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import order.conditionally_complete_lattice.basic import algebra.order.group.type_tags /-! # Conditionally complete lattices and groups. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ section group variables {α : Type*} {ι : Sort*} {ι' : Sort*} [nonempty ι] [nonempty ι'] [conditionally_complete_lattice α] [group α] @[to_additive] lemma le_mul_cinfi [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, a ≤ g * h j) : a ≤ g * infi h := inv_mul_le_iff_le_mul.mp $ le_cinfi $ λ hi, inv_mul_le_iff_le_mul.mpr $ H _ @[to_additive] lemma mul_csupr_le [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, g * h j ≤ a) : g * supr h ≤ a := @le_mul_cinfi αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, a ≤ g i * h) : a ≤ infi g * h := mul_inv_le_iff_le_mul.mp $ le_cinfi $ λ gi, mul_inv_le_iff_le_mul.mpr $ H _ @[to_additive] lemma csupr_mul_le [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, g i * h ≤ a) : supr g * h ≤ a := @le_cinfi_mul αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul_cinfi [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, a ≤ g i * h j) : a ≤ infi g * infi h := le_cinfi_mul $ λ i, le_mul_cinfi $ H _ @[to_additive] lemma csupr_mul_csupr_le [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, g i * h j ≤ a) : supr g * supr h ≤ a := csupr_mul_le $ λ i, mul_csupr_le $ H _ end group
18e1233246a074832d899e21c7b45c7b89180ad0
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.30.lean
1e476254d4749bddd51fff1fac8cf254325153e1
[]
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
236
lean
import standard import data.nat open nat check nat.sub_self example (m n : nat) : m - n = 0 ∨ m ≠ n := begin cases (decidable.em (m = n)) with [Heq, Hne], { apply eq.subst Heq, exact or.inl (sub_self m)}, { apply or.inr Hne } end
fd32a32fabb5c6a7af1b5de2bbb27d016f8de9f7
50b3917f95cf9fe84639812ea0461b38f8f0dbe1
/Examples/mario_glueing.lean
77188f501c955c83bab9c7f72dee572f44ab5e21
[]
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
10,614
lean
import mario_sheaf -- Mario's gist universes u v open lattice variables {α : Type u} [semilattice_inf α] variable (U : α) --#print notation →⊓ --#check @semilattice_inf_hom /- class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) -/ --#where namespace semilattice_inf.opens --#print has_inf.inf def inf {α : Type u} [semilattice_inf α] (U : α) ( a b : {V // V <= U}) : {V // V <= U} := ⟨a.val ⊓ b.val, le_trans inf_le_left a.property⟩ instance has_inf {α : Type u} [semilattice_inf α] (U : α) : has_inf {V // V ≤ U} := ⟨inf U⟩ example {α : Type u} [semilattice_inf α] (U : α) : has_inf {V // V ≤ U} := by apply_instance example {α : Type u} [semilattice_inf α] (U : α) : partial_order {V // V ≤ U} := by apply_instance instance {α : Type u} [semilattice_inf α] (U : α) : semilattice_inf {V // V ≤ U} := { inf_le_left := λ a b, inf_le_left, inf := λ a b, ⟨a.1 ⊓ b.1, le_trans inf_le_left a.2⟩, inf_le_right := λ a b, inf_le_right, le_inf := λ a b c, le_inf, ..subtype.partial_order _ } def presheaf_on_opens (U : α) := presheaf {V // V ≤ U} --#print notation →⊓ --#where -- Is this a thing? /-- semilattice_inf.opens.res_subset -/ def res_subset (F : presheaf_on_opens U) (V : α) (HVU : V ≤ U) : presheaf_on_opens V := presheaf.comap ({ to_fun := λ W, (⟨W.val, le_trans W.property HVU⟩ : {V // V ≤ U}),--⟨W.val,begin sorry end⟩, mono := λ V W H, H, map_inf' := λ W X, rfl}) F structure morphism (F : presheaf_on_opens U) (G : presheaf_on_opens U) := (map : Π (V : {V // V ≤ U}), F.F V → G.F V) (commutes : ∀ (V W : {V // V ≤ U}) (HWV : W ≤ V) (x), map W (F.res V W HWV x) = G.res V W HWV (map V x)) namespace morphism definition commutes' (F : presheaf_on_opens U) (G : presheaf_on_opens U) (f : morphism U F G) : ∀ (V W : {V // V ≤ U}) (HWV : W ≤ V) (x : F.F V), f.map W ((F.res V W HWV) x) = G.res V W HWV ((f.map V) x) := begin intros V W HVW, funext x, apply f.commutes end def commutes'' (F : presheaf_on_opens U) (G : presheaf_on_opens U) (f : morphism U F G) : ∀ (V W : {V // V ≤ U}) (HWV : W ≤ V), f.map W ∘ (F.res V W HWV) = G.res V W HWV ∘ (f.map V) := begin intros V W HVW, funext x, apply f.commutes end protected def id (F : presheaf_on_opens U) : morphism U F F := { map := λ V, id, commutes := λ V W HWV, by intros; refl} def comp {F : presheaf_on_opens U} {G : presheaf_on_opens U} {H : presheaf_on_opens U} (η : morphism U G H) (ξ : morphism U F G) : morphism U F H := { map := λ V x, η.map V (ξ.map V x), commutes := λ V W HWV, begin intro x, rw morphism.commutes' U F G ξ, rw morphism.commutes' U G H η, end} @[extensionality] lemma ext {F : presheaf_on_opens U} {G : presheaf_on_opens U} {η ξ : morphism U F G} (H : ∀ V x, η.map V x = ξ.map V x) : η = ξ := by cases η; cases ξ; congr; ext; apply H @[simp] lemma id_comp {F : presheaf_on_opens U} {G : presheaf_on_opens U} (η : morphism U F G) : comp U (morphism.id U G) η = η := begin ext x, refl, end @[simp] lemma comp_id {F : presheaf_on_opens U} {G : presheaf_on_opens U} (η : morphism U F G) : comp U η (morphism.id U F) = η := begin ext x, refl, end @[simp] lemma comp_assoc {F : presheaf_on_opens U} {G : presheaf_on_opens U} {H : presheaf_on_opens U} {I : presheaf_on_opens U} (η : morphism U H I) (ξ : morphism U G H) (χ : morphism U F G) : comp U (comp U η ξ) χ = comp U η (comp U ξ χ) := rfl def res_subset {F : presheaf_on_opens U} {G : presheaf_on_opens U} (η : morphism U F G) (V : α) (HVU : V ≤ U) : morphism V (res_subset U F V HVU) (res_subset U G V HVU) := { map := λ W, begin exact morphism.map η ⟨W.val, _⟩ end, commutes := λ S T, commutes η ⟨S.val, le_trans S.property HVU⟩ ⟨T.val, le_trans T.property HVU⟩ } @[simp] lemma comp_res_subset {F : presheaf_on_opens U} {G : presheaf_on_opens U} {H : presheaf_on_opens U} (η : morphism U G H) (ξ : morphism U F G) (V : α) (HVU : V ≤ U) : comp _ (res_subset _ η V HVU) (res_subset _ ξ V HVU) = res_subset _ (comp _ η ξ) V HVU := rfl @[simp] lemma id_res_subset {F : presheaf_on_opens U} (V : α) (HVU : V ≤ U) : morphism.res_subset _ (morphism.id U F) V HVU = morphism.id V (semilattice_inf.opens.res_subset U F V HVU) := rfl end morphism /-- semilattice_inf.opens.equiv, equiv for sheaves on an "open subset" of α -/ structure equiv (F : presheaf_on_opens U) (G : presheaf_on_opens U) := (to_fun : morphism U F G) (inv_fun : morphism U G F) (left_inv : morphism.comp U inv_fun to_fun = morphism.id U F) (right_inv : morphism.comp U to_fun inv_fun = morphism.id U G) namespace equiv def refl (F : presheaf_on_opens U) : equiv U F F := ⟨morphism.id U F, morphism.id U F, rfl, rfl⟩ def symm {F : presheaf_on_opens U} {G : presheaf_on_opens U} (e : equiv U F G) : equiv U G F := ⟨e.2, e.1, e.4, e.3⟩ def trans {F : presheaf_on_opens U} {G : presheaf_on_opens U} {H : presheaf_on_opens U} (e₁ : equiv U F G) (e₂ : equiv U G H) : equiv U F H := ⟨morphism.comp U e₂.1 e₁.1, morphism.comp U e₁.2 e₂.2, by rw [morphism.comp_assoc, ← morphism.comp_assoc U e₂.2, e₂.3, morphism.id_comp, e₁.3], by rw [morphism.comp_assoc, ← morphism.comp_assoc U e₁.1, e₁.4, morphism.id_comp, e₂.4]⟩ -- up to here #check @res_subset -- might be useful --#check (@semilattice_inf.opens.equiv α _ U F G).to_fun --.to_fun.commutes def res_subset {F : presheaf_on_opens U} {G : presheaf_on_opens U} (e : equiv U F G) (V : α) (HVU : V ≤ U) : equiv V (res_subset U F V HVU) (res_subset U G V HVU) := { to_fun := morphism.res_subset U e.1 V HVU, --{ map := λ W x, begin exact e.to_fun.map ⟨W.val, _⟩ x end, -- commutes := λ W1 W2 H21 x, -- by -- convert -- e.to_fun.commutes -- ⟨W1.val, le_trans W1.property HVU⟩ -- ⟨W2.val, le_trans W2.property HVU⟩ -- H21 x, -- } inv_fun := morphism.res_subset _ e.2 V HVU, -- { map := λ W x, begin exact e.inv_fun.map ⟨W.val, _⟩ x end, -- commutes := λ W1 W2 H21 x, -- by -- convert -- e.inv_fun.commutes -- ⟨W1.val, le_trans W1.property HVU⟩ -- ⟨W2.val, le_trans W2.property HVU⟩ -- H21 x, -- } left_inv := begin rw morphism.comp_res_subset U, rw e.3, rw morphism.id_res_subset end, right_inv := by rw [morphism.comp_res_subset, e.4, morphism.id_res_subset]} end equiv #exit def glue {I : Type*} (S : I → α) (F : Π (i : I), presheaf_on_opens (S i)) (φ : Π (i j : I), equiv ((S i) ⊓ (S j)) (res_subset (S i) (F i) ((S i) ⊓ (S j)) inf_le_left) (res_subset (S j) (F j) ((S i) ⊓ (S j)) inf_le_right)) (Hφ1 : ∀ i, φ i i = equiv.refl (S i ⊓ S i) (res_subset (S i) (F i) ((S i) ⊓ (S i)) inf_le_left)) (Hφ2 : ∀ i j k, equiv.trans ((S i) ⊓ (S j) ⊓ (S k)) (equiv.res_subset ((S i) ⊓ (S j)) (φ i j) ((S i) ⊓ (S j) ⊓ (S k)) (inf_le_left)) (equiv.res_subset ((S j) ⊓ (S k)) (φ j k) ((S i) ⊓ (S j) ⊓ (S k)) (show (S i) ⊓ (S j) ⊓ (S k) ≤ (S j) ⊓ (S k), from begin exact le_inf (le_trans (inf_le_left) (inf_le_right)) (inf_le_right) end)) -- (le_inf (le_trans (inf_le_left) --(inf_le_right)) (inf_le_right)) = equiv.res_subset ((S i) ⊓ (S k)) (φ i k) ((S i) ⊓ (S j) ⊓ (S k)) (le_inf (le_trans (inf_le_left) (inf_le_left)) (le_trans inf_le_left inf_le_right))) : presheaf_on_opens (lattice.complete_lattice.supr S) := { F := λ W, { f : Π i, (F i).eval ((S i) ∩ W) (set.inter_subset_left _ _) // ∀ i j, (φ i j).1.map ((S i) ∩ (S j) ∩ W) (set.inter_subset_left _ _) ((F i).res ((S i) ∩ W) _ _ (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.inter_subset_right _ _)) (f i)) = (F j).res ((S j) ∩ W) _ _ (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_right _ _)) (f j) }, res := λ U V HUV f, ⟨λ i, (F i).res (S i ∩ U) _ (S i ∩ V) _ (set.inter_subset_inter_right _ HUV) (f.val i), begin intros i j, rw res_comp, rw res_comp, have answer := congr_arg (res (F j) (S i ∩ (S j) ∩ U) _ (S i ∩ (S j) ∩ V) (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_inter_right _ HUV) ) (f.property i j), rw res_comp at answer, rw ←answer, clear answer, convert (φ i j).to_fun.commutes (S i ∩ (S j) ∩ U) (set.inter_subset_left _ _) (S i ∩ (S j) ∩ V) (set.inter_subset_left _ _) (set.inter_subset_inter_right _ HUV) ( (@sheaf_on_opens.res _ _ (S i ∩ U) (F i) (S i ∩ U) (by refl) (S i ∩ S j ∩ U) (set.inter_subset_inter_left _ (set.inter_subset_left _ _)) (set.inter_subset_inter_left _ (set.inter_subset_left _ _)) (f.val i) ) ) using 2, convert (F i).F.Hcomp' (S i ∩ U) (S i ∩ S j ∩ U) (S i ∩ S j ∩ V) _ _ (f.val i), end⟩, Hid := begin sorry end, Hcomp := sorry } def universal_property_Kevin_wants (I : Type u) (S : I → α) (F : Π (i : I), presheaf_on_opens (S i)) (φ : Π (i j : I), equiv ((S i) ⊓ (S j)) (res_subset (S i) (F i) ((S i) ⊓ (S j)) inf_le_left) (res_subset (S j) (F j) ((S i) ⊓ (S j)) inf_le_right)) (Hφ1 : ∀ i, φ i i = equiv.refl (S i ⊓ S i) (res_subset (S i) (F i) ((S i) ⊓ (S i)) inf_le_left)) (Hφ2 : ∀ i j k, ((φ i j).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.inter_subset_left _ _)).trans ((φ j k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_right _ _)) (set.inter_subset_right _ _))) = (φ i k).res_subset ((S i) ∩ (S j) ∩ (S k)) (set.subset_inter (le_trans (set.inter_subset_left _ _) (set.inter_subset_left _ _)) (set.inter_subset_right _ _))) : ∀ i : I, equiv (res_subset (glue S F φ Hφ1 Hφ2) (S i) $ opens.subset_Union S i) (F i) := sorry end semilattice_inf.opens
e0b1743f1733c50494f78be6861933909d92b581
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/deprecated/subgroup.lean
e1cd324e1a5f923f7a08a1563adb14d78399b09b
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
28,098
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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro, Michael Howes -/ import group_theory.subgroup import deprecated.submonoid open set function variables {G : Type*} {H : Type*} {A : Type*} {a a₁ a₂ b c: G} section group variables [group G] [add_group A] /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set A) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ @[to_additive] class is_subgroup (s : set G) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) lemma additive.is_add_subgroup (s : set G) [is_subgroup s] : @is_add_subgroup (additive G) _ s := @is_add_subgroup.mk (additive G) _ _ (additive.is_add_submonoid _) (@is_subgroup.inv_mem _ _ _ _) theorem additive.is_add_subgroup_iff {s : set G} : @is_add_subgroup (additive G) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk G _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI additive.is_add_subgroup _⟩ lemma multiplicative.is_subgroup (s : set A) [is_add_subgroup s] : @is_subgroup (multiplicative A) _ s := @is_subgroup.mk (multiplicative A) _ _ (multiplicative.is_submonoid _) (@is_add_subgroup.neg_mem _ _ _ _) theorem multiplicative.is_subgroup_iff {s : set A} : @is_subgroup (multiplicative A) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk A _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI multiplicative.is_subgroup _⟩ @[to_additive] instance subtype.group {s : set G} [is_subgroup s] : group s := { inv := λ x, ⟨(x:G)⁻¹, is_subgroup.inv_mem x.2⟩, mul_left_inv := λ x, subtype.eq $ mul_left_inv x.1, .. subtype.monoid } @[to_additive] instance subtype.comm_group {G : Type*} [comm_group G] {s : set G} [is_subgroup s] : comm_group s := { .. subtype.group, .. subtype.comm_monoid } @[simp, norm_cast, to_additive] lemma is_subgroup.coe_inv {s : set G} [is_subgroup s] (a : s) : ((a⁻¹ : s) : G) = a⁻¹ := rfl attribute [norm_cast] is_add_subgroup.coe_neg @[simp, norm_cast] lemma is_subgroup.coe_gpow {s : set G} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : G) = a ^ n := by induction n; simp [is_submonoid.coe_pow a] @[simp, norm_cast] lemma is_add_subgroup.gsmul_coe {s : set A} [is_add_subgroup s] (a : s) (n : ℤ) : ((gsmul n a : s) : A) = gsmul n a := by induction n; simp [is_add_submonoid.smul_coe a] attribute [to_additive gsmul_coe] is_subgroup.coe_gpow @[to_additive of_add_neg] theorem is_subgroup.of_div (s : set G) (one_mem : (1:G) ∈ s) (div_mem : ∀{a b:G}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s) : is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set A) (zero_mem : (0:A) ∈ s) (sub_mem : ∀{a b:A}, a ∈ s → b ∈ s → a - b ∈ s) : is_add_subgroup s := is_add_subgroup.of_add_neg s zero_mem (λ x y hx hy, sub_mem hx hy) @[to_additive] instance is_subgroup.inter (s₁ s₂ : set G) [is_subgroup s₁] [is_subgroup s₂] : is_subgroup (s₁ ∩ s₂) := { inv_mem := λ x hx, ⟨is_subgroup.inv_mem hx.1, is_subgroup.inv_mem hx.2⟩ } @[to_additive] instance is_subgroup.Inter {ι : Sort*} (s : ι → set G) [h : ∀ y : ι, is_subgroup (s y)] : is_subgroup (set.Inter s) := { inv_mem := λ x h, set.mem_Inter.2 $ λ y, is_subgroup.inv_mem (set.mem_Inter.1 h y) } @[to_additive] lemma is_subgroup_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set G) [∀ i, is_subgroup (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subgroup (⋃i, s i) := { inv_mem := λ a ha, let ⟨i, hi⟩ := set.mem_Union.1 ha in set.mem_Union.2 ⟨i, is_subgroup.inv_mem hi⟩, to_is_submonoid := is_submonoid_Union_of_directed s directed } def gpowers (x : G) : set G := set.range ((^) x : ℤ → G) def gmultiples (x : A) : set A := set.range (λ i, gsmul i x) attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : G) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : A) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : A} {s : set A} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative A) _ _ _ (multiplicative.is_subgroup _) lemma gpowers_subset {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : gpowers a ⊆ s := λ x hx, match x, hx with _, ⟨i, rfl⟩ := is_subgroup.gpow_mem h end lemma gmultiples_subset {a : A} {s : set A} [is_add_subgroup s] (h : a ∈ s) : gmultiples a ⊆ s := @gpowers_subset (multiplicative A) _ _ _ (multiplicative.is_subgroup _) h attribute [to_additive gmultiples_subset] gpowers_subset lemma mem_gpowers {a : G} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : A} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group G] (s : set G) [is_subgroup s] @[to_additive] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup theorem is_add_subgroup.sub_mem {A} [add_group A] (s : set A) [is_add_subgroup s] (a b : A) (ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s := is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb) class normal_add_subgroup [add_group A] (s : set A) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : A, g + n - g ∈ s) @[to_additive] class normal_subgroup [group G] (s : set G) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : G, g * n * g⁻¹ ∈ s) @[to_additive] lemma normal_subgroup_of_comm_group [comm_group G] (s : set G) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } lemma additive.normal_add_subgroup [group G] (s : set G) [normal_subgroup s] : @normal_add_subgroup (additive G) _ s := @normal_add_subgroup.mk (additive G) _ _ (@additive.is_add_subgroup G _ _ _) (@normal_subgroup.normal _ _ _ _) theorem additive.normal_add_subgroup_iff [group G] {s : set G} : @normal_add_subgroup (additive G) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk G _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by exactI additive.normal_add_subgroup _⟩ lemma multiplicative.normal_subgroup [add_group A] (s : set A) [normal_add_subgroup s] : @normal_subgroup (multiplicative A) _ s := @normal_subgroup.mk (multiplicative A) _ _ (@multiplicative.is_subgroup A _ _ _) (@normal_add_subgroup.normal _ _ _ _) theorem multiplicative.normal_subgroup_iff [add_group A] {s : set A} : @normal_subgroup (multiplicative A) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk A _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by exactI multiplicative.normal_subgroup _⟩ namespace is_subgroup variable [group G] -- Normal subgroup properties @[to_additive] lemma mem_norm_comm {s : set G} [normal_subgroup s] {a b : G} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h @[to_additive] lemma mem_norm_comm_iff {s : set G} [normal_subgroup s] {a b : G} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ @[to_additive] def trivial (G : Type*) [group G] : set G := {1} @[simp, to_additive] lemma mem_trivial {g : G} : g ∈ trivial G ↔ g = 1 := mem_singleton_iff @[to_additive] instance trivial_normal : normal_subgroup (trivial G) := by refine {..}; simp [trivial] {contextual := tt} @[to_additive] lemma eq_trivial_iff {s : set G} [is_subgroup s] : s = trivial G ↔ (∀ x ∈ s, x = (1 : G)) := by simp only [set.ext_iff, is_subgroup.mem_trivial]; exact ⟨λ h x, (h x).1, λ h x, ⟨h x, λ hx, hx.symm ▸ is_submonoid.one_mem⟩⟩ @[to_additive] instance univ_subgroup : normal_subgroup (@univ G) := by refine {..}; simp @[to_additive add_center] def center (G : Type*) [group G] : set G := {z | ∀ g, g * z = z * g} @[to_additive mem_add_center] lemma mem_center {a : G} : a ∈ center G ↔ ∀g, g * a = a * g := iff.rfl @[to_additive add_center_normal] instance center_normal : normal_subgroup (center G) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } @[to_additive add_normalizer] def normalizer (s : set G) : set G := {g : G | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s} @[to_additive] instance normalizer_is_subgroup (s : set G) : is_subgroup (normalizer s) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) (hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } @[to_additive subset_add_normalizer] lemma subset_normalizer (s : set G) [is_subgroup s] : s ⊆ normalizer s := λ g hg n, by rw [is_subgroup.mul_mem_cancel_right _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_left _ hg] /-- Every subgroup is a normal subgroup of its normalizer -/ @[to_additive add_normal_in_add_normalizer] instance normal_in_normalizer (s : set G) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) := { one_mem := show (1 : G) ∈ s, from is_submonoid.one_mem, mul_mem := λ a b ha hb, show (a * b : G) ∈ s, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ s, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup open is_mul_hom (map_mul) @[to_additive] def ker [group H] (f : G → H) : set G := preimage f (trivial H) @[to_additive] lemma mem_ker [group H] (f : G → H) {x : G} : x ∈ ker f ↔ f x = 1 := mem_trivial variables [group G] [group H] @[to_additive] lemma one_ker_inv (f : G → H) [is_group_hom f] {a b : G} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive] lemma one_ker_inv' (f : G → H) [is_group_hom f] {a b : G} (h : f (a⁻¹ * b) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, apply inv_injective, rw eq_inv_of_mul_eq_one h end @[to_additive] lemma inv_ker_one (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma inv_ker_one' (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a⁻¹ * b) = 1 := have (f a)⁻¹ * f b = 1, by rw [h, mul_left_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma one_iff_ker_inv (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive] lemma one_iff_ker_inv' (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a⁻¹ * b) = 1 := ⟨inv_ker_one' f, one_ker_inv' f⟩ @[to_additive] lemma inv_iff_ker (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ @[to_additive] lemma inv_iff_ker' (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a⁻¹ * b ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv' _ _ _ @[to_additive] instance image_subgroup (f : G → H) [is_group_hom f] (s : set G) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, map_mul f]⟩, one_mem := ⟨1, one_mem, map_one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw map_inv f; simp *⟩ } @[to_additive] instance range_subgroup (f : G → H) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal @[to_additive] instance preimage (f : G → H) [is_group_hom f] (s : set H) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [map_mul f, map_one f, map_inv f, @inv_mem H _ s] {contextual:=tt} @[to_additive] instance preimage_normal (f : G → H) [is_group_hom f] (s : set H) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [map_mul f, map_inv f] {contextual:=tt}⟩ @[to_additive] instance normal_subgroup_ker (f : G → H) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial H) @[to_additive] lemma injective_of_trivial_ker (f : G → H) [is_group_hom f] (h : ker f = trivial G) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end @[to_additive] lemma trivial_ker_of_injective (f : G → H) [is_group_hom f] (h : function.injective f) : ker f = trivial G := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [map_one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.map_one f] {contextual := tt}) @[to_additive] lemma injective_iff_trivial_ker (f : G → H) [is_group_hom f] : function.injective f ↔ ker f = trivial G := ⟨trivial_ker_of_injective f, injective_of_trivial_ker f⟩ @[to_additive] lemma trivial_ker_iff_eq_one (f : G → H) [is_group_hom f] : ker f = trivial G ↔ ∀ x, f x = 1 → x = 1 := by rw set.ext_iff; simp [ker]; exact ⟨λ h x hx, (h x).1 hx, λ h x, ⟨h x, λ hx, by rw [hx, map_one f]⟩⟩ end is_group_hom @[to_additive] instance subtype_val.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (subtype.val : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive] instance coe.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (coe : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive] instance subtype_mk.is_group_hom [group G] [group H] {s : set G} [is_subgroup s] (f : H → G) [is_group_hom f] (h : ∀ x, f x ∈ s) : is_group_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_monoid_hom f h } @[to_additive] instance set_inclusion.is_group_hom [group G] {s t : set G} [is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) := subtype_mk.is_group_hom _ _ /-- `subtype.val : set.range f → H` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`subtype.val : set.range f → H` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_subtype_val [monoid G] [monoid H] (f : G →* H) : (set.range f) →* H := monoid_hom.of subtype.val /-- `set.range_factorization f : G → set.range f` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`set.range_factorization f : G → set.range f` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_factorization [monoid G] [monoid H] (f : G →* H) : G →* (set.range f) := { to_fun := set.range_factorization f, map_one' := by { dsimp [set.range_factorization], simp, refl, }, map_mul' := by { intros, dsimp [set.range_factorization], simp, refl, } } namespace add_group variables [add_group A] inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | neg {a : A} : in_closure a → in_closure (-a) | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_group namespace group open is_submonoid is_subgroup variables [group G] {s : set G} @[to_additive] inductive in_closure (s : set G) : G → Prop | basic {a : G} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : G} : in_closure a → in_closure a⁻¹ | mul {a b : G} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ @[to_additive] def closure (s : set G) : set G := {a | in_closure s a } @[to_additive] lemma mem_closure {a : G} : a ∈ s → a ∈ closure s := in_closure.basic @[to_additive] instance closure.is_subgroup (s : set G) : is_subgroup (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } @[to_additive] theorem subset_closure {s : set G} : s ⊆ closure s := λ a, mem_closure @[to_additive] theorem closure_subset {s t : set G} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] @[to_additive] lemma closure_subset_iff (s t : set G) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t := ⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩ @[to_additive] theorem closure_mono {s t : set G} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure @[simp, to_additive] lemma closure_subgroup (s : set G) [is_subgroup s] : closure s = s := set.subset.antisymm (closure_subset $ set.subset.refl s) subset_closure @[to_additive] theorem exists_list_of_mem_closure {s : set G} {a : G} (h : a ∈ closure s) : (∃l:list G, (∀x∈l, x ∈ s ∨ x⁻¹ ∈ s) ∧ l.prod = a) := in_closure.rec_on h (λ x hxs, ⟨[x], list.forall_mem_singleton.2 $ or.inl hxs, one_mul _⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x _ ⟨L, HL1, HL2⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, hy1, hy2⟩ := list.exists_of_mem_map hx in hy2 ▸ or.imp id (by rw [inv_inv]; exact id) (HL1 _ $ list.mem_reverse.1 hy1).symm, HL2 ▸ list.rec_on L one_inv.symm (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih, list.map_singleton, list.prod_cons, list.prod_nil, mul_one, list.prod_cons, mul_inv_rev])⟩) (λ x y hx hy ⟨L1, HL1, HL2⟩ ⟨L2, HL3, HL4⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL3⟩, by rw [list.prod_append, HL2, HL4]⟩) @[to_additive] lemma image_closure [group H] (f : G → H) [is_group_hom f] (s : set G) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_group_hom.map_inv f], apply is_subgroup.inv_mem, assumption }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) @[to_additive] theorem mclosure_subset {s : set G} : monoid.closure s ⊆ closure s := monoid.closure_subset $ subset_closure @[to_additive] theorem mclosure_inv_subset {s : set G} : monoid.closure (has_inv.inv ⁻¹' s) ⊆ closure s := monoid.closure_subset $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx) @[to_additive] theorem closure_eq_mclosure {s : set G} : closure s = monoid.closure (s ∪ has_inv.inv ⁻¹' s) := set.subset.antisymm (@closure_subset _ _ _ (monoid.closure (s ∪ has_inv.inv ⁻¹' s)) { inv_mem := λ x hx, monoid.in_closure.rec_on hx (λ x hx, or.cases_on hx (λ hx, monoid.subset_closure $ or.inr $ show x⁻¹⁻¹ ∈ s, from (inv_inv x).symm ▸ hx) (λ hx, monoid.subset_closure $ or.inl hx)) ((@one_inv G _).symm ▸ is_submonoid.one_mem) (λ x y hx hy ihx ihy, (mul_inv_rev x y).symm ▸ is_submonoid.mul_mem ihy ihx) } (set.subset.trans (set.subset_union_left _ _) monoid.subset_closure)) (monoid.closure_subset $ set.union_subset subset_closure $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx)) @[to_additive] theorem mem_closure_union_iff {G : Type*} [comm_group G] {s t : set G} {x : G} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := begin simp only [closure_eq_mclosure, monoid.mem_closure_union_iff, exists_prop, preimage_union], split, { rintro ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨_, hys, _, hzs, rfl⟩, _, ⟨_, hyt, _, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm zs] }, { rintro ⟨_, ⟨ys, hys, zs, hzs, rfl⟩, _, ⟨yt, hyt, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm yt] } end @[to_additive gmultiples_eq_closure] theorem gpowers_eq_closure {a : G} : gpowers a = closure {a} := subset.antisymm (gpowers_subset $ mem_closure $ by simp) (closure_subset $ by simp [mem_gpowers]) end group namespace is_subgroup variable [group G] @[to_additive] lemma trivial_eq_closure : trivial G = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) end is_subgroup /-The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ namespace group variables {s : set G} [group G] lemma conjugates_subset {t : set G} [normal_subgroup t] {a : G} (h : a ∈ t) : conjugates a ⊆ t := λ x ⟨c,w⟩, begin have H := normal_subgroup.normal a h c, rwa ←w, end theorem conjugates_of_set_subset' {s t : set G} [normal_subgroup t] (h : s ⊆ t) : conjugates_of_set s ⊆ t := set.bUnion_subset (λ x H, conjugates_subset (h H)) /-- The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ def normal_closure (s : set G) : set G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of a set is a subgroup. -/ instance normal_closure.is_subgroup (s : set G) : is_subgroup (normal_closure s) := closure.is_subgroup (conjugates_of_set s) /-- The normal closure of s is a normal subgroup. -/ instance normal_closure.is_normal : normal_subgroup (normal_closure s) := ⟨ λ n h g, begin induction h with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx))}, {simpa using (normal_closure.is_subgroup s).one_mem}, {rw ←conj_inv, exact (is_subgroup.inv_mem ihx)}, {rw ←conj_mul, exact (is_submonoid.mul_mem ihx ihy)}, end ⟩ /-- The normal closure of s is the smallest normal subgroup containing s. -/ theorem normal_closure_subset {s t : set G} [normal_subgroup t] (h : s ⊆ t) : normal_closure s ⊆ t := λ a w, begin induction w with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset' h $ hx)}, {exact is_submonoid.one_mem}, {exact is_subgroup.inv_mem ihx}, {exact is_submonoid.mul_mem ihx ihy} end lemma normal_closure_subset_iff {s t : set G} [normal_subgroup t] : s ⊆ t ↔ normal_closure s ⊆ t := ⟨normal_closure_subset, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} : s ⊆ t → normal_closure s ⊆ normal_closure t := λ h, normal_closure_subset (set.subset.trans h (subset_normal_closure)) end group section simple_group class simple_group (G : Type*) [group G] : Prop := (simple : ∀ (N : set G) [normal_subgroup N], N = is_subgroup.trivial G ∨ N = set.univ) class simple_add_group (A : Type*) [add_group A] : Prop := (simple : ∀ (N : set A) [normal_add_subgroup N], N = is_add_subgroup.trivial A ∨ N = set.univ) attribute [to_additive] simple_group theorem additive.simple_add_group_iff [group G] : simple_add_group (additive G) ↔ simple_group G := ⟨λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.1 h)⟩⟩ instance additive.simple_add_group [group G] [simple_group G] : simple_add_group (additive G) := additive.simple_add_group_iff.2 (by apply_instance) theorem multiplicative.simple_group_iff [add_group A] : simple_group (multiplicative A) ↔ simple_add_group A := ⟨λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.1 h)⟩⟩ instance multiplicative.simple_group [add_group A] [simple_add_group A] : simple_group (multiplicative A) := multiplicative.simple_group_iff.2 (by apply_instance) @[to_additive] lemma simple_group_of_surjective [group G] [group H] [simple_group G] (f : G → H) [is_group_hom f] (hf : function.surjective f) : simple_group H := ⟨λ H iH, have normal_subgroup (f ⁻¹' H), by resetI; apply_instance, begin resetI, cases simple_group.simple (f ⁻¹' H) with h h, { refine or.inl (is_subgroup.eq_trivial_iff.2 (λ x hx, _)), cases hf x with y hy, rw ← hy at hx, rw [← hy, is_subgroup.eq_trivial_iff.1 h y hx, is_group_hom.map_one f] }, { refine or.inr (set.eq_univ_of_forall (λ x, _)), cases hf x with y hy, rw set.eq_univ_iff_forall at h, rw ← hy, exact h y } end⟩ end simple_group /-- Create a bundled subgroup from a set `s` and `[is_subroup s]`. -/ @[to_additive "Create a bundled additive subgroup from a set `s` and `[is_add_subgroup s]`."] def subgroup.of [group G] (s : set G) [h : is_subgroup s] : subgroup G := { carrier := s, one_mem' := h.1.1, mul_mem' := h.1.2, inv_mem' := h.2 } @[to_additive] instance subgroup.is_subgroup [group G] (K : subgroup G) : is_subgroup (K : set G) := { one_mem := K.one_mem', mul_mem := K.mul_mem', inv_mem := K.inv_mem' } @[to_additive] instance subgroup.of_normal [group G] (s : set G) [h : is_subgroup s] [n : normal_subgroup s] : subgroup.normal (subgroup.of s) := { conj_mem := n.normal, }
931734c33925f28fea8b4b646279fd9ff2d41543
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/ka_bot.lean
0b6ce0aa83221d3c6f077ad2f1409e59f13f652d
[]
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
277
lean
import core.connectives import hilbert.wr.ka namespace clfrags namespace hilbert namespace wr namespace ka_bot axiom kab₁ : Π {a b c : Prop}, ka b a bot → ka b a c end ka_bot end wr end hilbert end clfrags
129cc4767f35dcc94fbc527821445d7fc818262a
246309748072bf9f8da313401699689ebbecd94d
/src/ring_theory/localization.lean
0e4ffa72f881625a42a73b2b28f033ddf95e1840
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
59,280
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston -/ import data.equiv.ring import group_theory.monoid_localization import ring_theory.algebraic /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. Given such a localization map `f : R →+* S`, we can define the surjection `localization_map.mk'` sending `(x, y) : R × M` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. Similarly, given commutative rings `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : R →+* P` such that `g(M) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `S` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We show the localization as a quotient type, defined in `group_theory.monoid_localization` as `submonoid.localization`, is a `comm_ring` and that the natural ring hom `of : R →+* localization M` is a localization map. We show that a localization at the complement of a prime ideal is a local ring. We prove some lemmas about the `R`-algebra structure of `S`. When `R` is an integral domain, we define `fraction_map R K` as an abbreviation for `localization (non_zero_divisors R) K`, the natural map to `R`'s field of fractions. We show that a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field. We use this to show the field of fractions as a quotient type, `fraction_ring`, is a field. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A ring localization map is defined to be a localization map of the underlying `comm_monoid` (a `submonoid.localization_map`) which is also a ring hom. To prove most lemmas about a `localization_map` `f` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `f.to_localization_map`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `of : localization_map M (localization M)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) (S : Type*) [comm_ring S] {P : Type*} [comm_ring P] open function set_option old_structure_cmd true /-- The type of ring homomorphisms satisfying the characteristic predicate: if `f : R →+* S` satisfies this predicate, then `S` is isomorphic to the localization of `R` at `M`. We later define an instance coercing a localization map `f` to its codomain `S` so that instances on `S` induced by `f` can 'know' the map needed to induce the instance. -/ @[nolint has_inhabited_instance] structure localization_map extends ring_hom R S, submonoid.localization_map M S /-- The ring hom underlying a `localization_map`. -/ add_decl_doc localization_map.to_ring_hom /-- The `comm_monoid` `localization_map` underlying a `comm_ring` `localization_map`. See `group_theory.monoid_localization` for its definition. -/ add_decl_doc localization_map.to_localization_map variables {M S} namespace ring_hom /-- Makes a localization map from a `comm_ring` hom satisfying the characteristic predicate. -/ def to_localization_map (f : R →+* S) (H1 : ∀ y : M, is_unit (f y)) (H2 : ∀ z, ∃ x : R × M, z * f x.2 = f x.1) (H3 : ∀ x y, f x = f y ↔ ∃ c : M, x * c = y * c) : localization_map M S := { map_units' := H1, surj' := H2, eq_iff_exists' := H3, .. f } end ring_hom /-- Makes a `comm_ring` localization map from an additive `comm_monoid` localization map of `comm_ring`s. -/ def submonoid.localization_map.to_ring_localization (f : submonoid.localization_map M S) (h : ∀ x y, f.to_map (x + y) = f.to_map x + f.to_map y) : localization_map M S := { ..ring_hom.mk' f.to_monoid_hom h, ..f } namespace localization_map variables (f : localization_map M S) /-- We define a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that instances on `S` induced by `f` can 'know` the map needed to induce the instance. -/ @[nolint unused_arguments has_inhabited_instance] def codomain (f : localization_map M S) := S instance : comm_ring f.codomain := by assumption instance {K : Type*} [field K] (f : localization_map M K) : field f.codomain := by assumption /-- Short for `to_ring_hom`; used for applying a localization map as a function. -/ abbreviation to_map := f.to_ring_hom lemma map_units (y : M) : is_unit (f.to_map y) := f.6 y lemma surj (z) : ∃ x : R × M, z * f.to_map x.2 = f.to_map x.1 := f.7 z lemma eq_iff_exists {x y} : f.to_map x = f.to_map y ↔ ∃ c : M, x * c = y * c := f.8 x y @[ext] lemma ext {f g : localization_map M S} (h : ∀ x, f.to_map x = g.to_map x) : f = g := begin cases f, cases g, simp only at *, exact funext h end lemma ext_iff {f g : localization_map M S} : f = g ↔ ∀ x, f.to_map x = g.to_map x := ⟨λ h x, h ▸ rfl, ext⟩ lemma to_map_injective : injective (@localization_map.to_map _ _ M S _) := λ _ _ h, ext $ ring_hom.ext_iff.1 h /-- Given `a : S`, `S` a localization of `R`, `is_integer a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ set.range f.to_map variables {f} lemma is_integer_add {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a + b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' + b', rw [f.to_map.map_add, ha, hb] end lemma is_integer_mul {a b} (ha : f.is_integer a) (hb : f.is_integer b) : f.is_integer (a * b) := begin rcases ha with ⟨a', ha⟩, rcases hb with ⟨b', hb⟩, use a' * b', rw [f.to_map.map_mul, ha, hb] end lemma is_integer_smul {a : R} {b} (hb : f.is_integer b) : f.is_integer (f.to_map a * b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, f.to_map.map_mul] end variables (f) /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer f (a * f.to_map b) := let ⟨⟨num, denom⟩, h⟩ := f.surj a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer f (f.to_map b * a) := by { simp_rw mul_comm _ a, apply exists_integer_multiple' } /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec {f : localization_map M S} (z : S) : z * f.to_map (f.to_localization_map.sec z).2 = f.to_map (f.to_localization_map.sec z).1 := classical.some_spec $ f.surj z /-- Given `z : S`, `f.to_localization_map.sec z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' {f : localization_map M S} (z : S) : f.to_map (f.to_localization_map.sec z).1 = f.to_map (f.to_localization_map.sec z).2 * z := by rw [mul_comm, sec_spec] open_locale big_operators /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer f (f.to_map b * a) := begin haveI := classical.prop_decidable, use ∏ a in s, (f.to_localization_map.sec a).2, intros a ha, use (∏ x in s.erase a, (f.to_localization_map.sec x).2) * (f.to_localization_map.sec a).1, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←f.to_map.map_mul], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase a), finset.insert_erase ha], refl, end lemma map_right_cancel {x y} {c : M} (h : f.to_map (c * x) = f.to_map (c * y)) : f.to_map x = f.to_map y := f.to_localization_map.map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : f.to_map (x * c) = f.to_map (y * c)) : f.to_map x = f.to_map y := f.to_localization_map.map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * f.to_map y = f.to_map x) (hx : x = 0) : z = 0 := by rw [hx, f.to_map.map_zero] at h; exact (f.map_units y).mul_left_eq_zero.1 h /-- Given a localization map `f : R →+* S`, the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (f : localization_map M S) (x : R) (y : M) : S := f.to_localization_map.mk' x y @[simp] lemma mk'_sec (z : S) : f.mk' (f.to_localization_map.sec z).1 (f.to_localization_map.sec z).2 = z := f.to_localization_map.mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := f.to_localization_map.mk'_mul _ _ _ _ lemma mk'_one (x) : f.mk' x (1 : M) = f.to_map x := f.to_localization_map.mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : f.mk' x y * f.to_map y = f.to_map x := f.to_localization_map.mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : f.to_map y * f.mk' x y = f.to_map x := f.to_localization_map.mk'_spec' _ _ theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = f.mk' x y ↔ z * f.to_map y = f.to_map x := f.to_localization_map.eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : f.mk' x y = z ↔ f.to_map x = z * f.to_map y := f.to_localization_map.mk'_eq_iff_eq_mul lemma mk'_surjective (z : S) : ∃ x (y : M), f.mk' x y = z := let ⟨r, hr⟩ := f.surj z in ⟨r.1, r.2, (f.eq_mk'_iff_mul_eq.2 hr).symm⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.to_map (x₁ * y₂) = f.to_map (x₂ * y₁) := f.to_localization_map.mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : f.mk' x y ∈ I ↔ f.to_map x ∈ I := begin split; intro h, { rw [← mk'_spec f x y, mul_comm], exact I.smul_mem (f.to_map y) h }, { rw ← mk'_spec f x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units f y), have := I.smul_mem b h, rwa [smul_eq_mul, mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := f.to_localization_map.eq lemma eq_iff_eq (g : localization_map M P) {x y} : f.to_map x = f.to_map y ↔ g.to_map x = g.to_map y := f.to_localization_map.eq_iff_eq g.to_localization_map lemma mk'_eq_iff_mk'_eq (g : localization_map M P) {x₁ x₂} {y₁ y₂ : M} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.to_localization_map.mk'_eq_iff_mk'_eq g.to_localization_map lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.to_localization_map.mk'_eq_of_eq H @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : f.mk' x ⟨x, hx⟩ = 1 := f.to_localization_map.mk'_self _ hx @[simp] lemma mk'_self' {x : M} : f.mk' x x = 1 := f.to_localization_map.mk'_self' _ lemma mk'_self'' {x : M} : f.mk' x.1 x = 1 := f.mk'_self' lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : f.to_map x * f.mk' y z = f.mk' (x * y) z := f.to_localization_map.mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : f.mk' x y = f.to_map x * f.mk' 1 y := (f.to_localization_map.mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : f.mk' (y * x) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : f.mk' (x * y) y = f.to_map x := f.to_localization_map.mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : f.mk' x y * f.mk' y x = 1 := by rw [←f.mk'_mul, mul_comm]; exact f.mk'_self _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : f.mk' x y * f.mk' y ⟨x, h⟩ = 1 := f.mk'_mul_mk'_eq_one ⟨x, h⟩ _ lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp f.to_map y) := f.to_localization_map.is_unit_comp j.to_monoid_hom _ /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : f.to_map x = f.to_map y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : f.mk' (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = f.mk' x₁ y₁ + f.mk' x₂ y₂ := f.mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, ←eq_sub_iff_add_eq, mk'_eq_iff_eq_mul, mul_comm _ (f.to_map _), mul_sub, eq_sub_iff_add_eq, ←eq_sub_iff_add_eq', ←mul_assoc, ←f.to_map.map_mul, mul_mk'_eq_mk'_of_mul, mk'_eq_iff_eq_mul], simp only [f.to_map.map_add, submonoid.coe_mul, f.to_map.map_mul], ring_exp, end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := ring_hom.mk' (@submonoid.localization_map.lift _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg) $ begin intros x y, rw [f.to_localization_map.lift_spec, mul_comm, add_mul, ←sub_eq_iff_eq_add, eq_comm, f.to_localization_map.lift_spec_mul, mul_comm _ (_ - _), sub_mul, eq_sub_iff_add_eq', ←eq_sub_iff_add_eq, mul_assoc, f.to_localization_map.lift_spec_mul], show g _ * (g _ * g _) = g _ * (g _ * g _ - g _ * g _), repeat {rw ←g.map_mul}, rw [←g.map_sub, ←g.map_mul], apply f.eq_of_eq hg, erw [f.to_map.map_mul, sec_spec', mul_sub, f.to_map.map_sub], simp only [f.to_map.map_mul, sec_spec'], ring_exp, end variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_ring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.mrestrict M) hg y)⁻¹ := f.to_localization_map.lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := f.to_localization_map.lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : f.lift hg (f.to_map x) = g x := f.to_localization_map.lift_eq _ _ lemma lift_eq_iff {x y : R × M} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := f.to_localization_map.lift_eq_iff _ @[simp] lemma lift_comp : (f.lift hg).comp f.to_map = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : f.lift (f.is_unit_comp j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ f.to_localization_map.lift_of_comp j.to_monoid_hom lemma epic_of_localization_map {j k : S →+* P} (h : ∀ a, j.comp f.to_map a = k.comp f.to_map a) : j = k := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.epic_of_localization_map _ _ _ _ _ _ _ f.to_localization_map j.to_monoid_hom k.to_monoid_hom h lemma lift_unique {j : S →+* P} (hj : ∀ x, j (f.to_map x) = g x) : f.lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : f.lift f.map_units x = x := f.to_localization_map.lift_id _ /-- Given two localization maps `f : R →+* S, k : R →+* P` for a submonoid `M ⊆ R`, the hom from `P` to `S` induced by `f` is left inverse to the hom from `S` to `P` induced by `k`. -/ @[simp] lemma lift_left_inverse {k : localization_map M S} (z : S) : k.lift f.map_units (f.lift k.map_units z) = z := f.to_localization_map.lift_left_inverse _ lemma lift_surjective_iff : surjective (f.lift hg) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := f.to_localization_map.lift_surjective_iff hg lemma lift_injective_iff : injective (f.lift hg) ↔ ∀ x y, f.to_map x = f.to_map y ↔ g x = g y := f.to_localization_map.lift_injective_iff hg variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) /-- Given a `comm_ring` homomorphism `g : R →+* P` where for submonoids `M ⊆ R, T ⊆ P` we have `g(M) ⊆ T`, the induced ring homomorphism from the localization of `R` at `M` to the localization of `P` at `T`: if `f : R →+* S` and `k : P →+* Q` are localization maps for `M` and `T` respectively, we send `z : S` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map : S →+* Q := @lift _ _ _ _ _ _ _ f (k.to_map.comp g) $ λ y, k.map_units ⟨g y, hy y⟩ variables {k} lemma map_eq (x) : f.map hy k (f.to_map x) = k.to_map (g x) := f.lift_eq (λ y, k.map_units ⟨g y, hy y⟩) x @[simp] lemma map_comp : (f.map hy k).comp f.to_map = k.to_map.comp g := f.lift_comp $ λ y, k.map_units ⟨g y, hy y⟩ lemma map_mk' (x) (y : M) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ @[simp] lemma map_id (z : S) : f.map (λ y, show ring_hom.id R y ∈ M, from y.2) f z = z := f.lift_id _ /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.map_comp_map _ _ _ _ _ _ _ f.to_localization_map g.to_monoid_hom _ hy _ _ k.to_localization_map _ _ _ _ _ j.to_localization_map l.to_monoid_hom hl /-- If `comm_ring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_ring A] {U : submonoid A} {W} [comm_ring W] (j : localization_map U W) {l : P →+* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl /-- Given localization maps `f : R →+* S, k : P →+* Q` for submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ noncomputable def ring_equiv_of_ring_equiv (k : localization_map T Q) (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := (f.to_localization_map.mul_equiv_of_mul_equiv k.to_localization_map H).to_ring_equiv $ (@lift _ _ _ _ _ _ _ f (k.to_map.comp h.to_ring_hom) (λ y, k.map_units ⟨(h y), H ▸ set.mem_image_of_mem h y.2⟩)).map_add @[simp] lemma ring_equiv_of_ring_equiv_eq_map_apply {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H x = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (f.ring_equiv_of_ring_equiv k j H).to_monoid_hom = f.map (λ y : M, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : f.ring_equiv_of_ring_equiv k j H (f.to_map x) = k.to_map (j x) := f.to_localization_map.mul_equiv_of_mul_equiv_eq H _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x y) : f.ring_equiv_of_ring_equiv k j H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.to_localization_map.mul_equiv_of_mul_equiv_mk' H _ _ section away_map variables (x : R) /-- Given `x : R`, the type of homomorphisms `f : R →* S` such that `S` is isomorphic to the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away_map (S' : Type*) [comm_ring S'] := localization_map (submonoid.powers x) S' variables (F : away_map x S) /-- Given `x : R` and a localization map `F : R →+* S` away from `x`, `inv_self` is `(F x)⁻¹`. -/ noncomputable def away_map.inv_self : S := F.mk' 1 ⟨x, submonoid.mem_powers _⟩ /-- Given `x : R`, a localization map `F : R →+* S` away from `x`, and a map of `comm_ring`s `g : R →+* P` such that `g x` is invertible, the homomorphism induced from `S` to `P` sending `z : S` to `g y * (g x)⁻ⁿ`, where `y : R, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ noncomputable def away_map.lift (hg : is_unit (g x)) : S →+* P := localization_map.lift F $ λ y, show is_unit (g y.1), begin obtain ⟨n, hn⟩ := y.2, rw [←hn, g.map_pow], exact is_unit.map (monoid_hom.of $ ((^ n) : P → P)) hg, end @[simp] lemma away_map.lift_eq (hg : is_unit (g x)) (a : R) : F.lift x hg (F.to_map a) = g a := lift_eq _ _ _ @[simp] lemma away_map.lift_comp (hg : is_unit (g x)) : (F.lift x hg).comp F.to_map = g := lift_comp _ _ /-- Given `x y : R` and localization maps `F : R →+* S, G : R →+* P` away from `x` and `x * y` respectively, the homomorphism induced from `S` to `P`. -/ noncomputable def away_to_away_right (y : R) (G : away_map (x * y) P) : S →* P := F.lift x $ show is_unit (G.to_map x), from is_unit_of_mul_eq_one (G.to_map x) (G.mk' y ⟨x * y, submonoid.mem_powers _⟩) $ by rw [mul_mk'_eq_mk'_of_mul, mk'_self] end away_map end localization_map namespace localization variables {M} instance : has_add (localization M) := ⟨λ z w, con.lift_on₂ z w (λ x y : R × M, mk ((x.2 : R) * y.1 + y.2 * x.1) (x.2 * y.2)) $ λ r1 r2 r3 r4 h1 h2, (con.eq _).2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((r1.2 : R) * r2.1 + r2.2 * r1.1) * (r3.2 * r4.2) * (t₆ * t₅) = (r2.1 * r4.2 * t₆) * (r1.2 * r3.2 * t₅) + (r1.1 * r3.2 * t₅) * (r2.2 * r4.2 * t₆) : by ring ... = (r3.2 * r4.1 + r4.2 * r3.1) * (r1.2 * r2.2) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end⟩ instance : has_neg (localization M) := ⟨λ z, con.lift_on z (λ x : R × M, mk (-x.1) x.2) $ λ r1 r2 h, (con.eq _).2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, ht], ring, end⟩ instance : has_zero (localization M) := ⟨mk 0 1⟩ private meta def tac := `[{ intros, refine quotient.sound' (r_of_eq _), simp only [prod.snd_mul, prod.fst_mul, submonoid.coe_mul], ring }] instance : comm_ring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), add_assoc := λ m n k, quotient.induction_on₃' m n k (by tac), zero_add := λ y, quotient.induction_on' y (by tac), add_zero := λ y, quotient.induction_on' y (by tac), neg := has_neg.neg, add_left_neg := λ y, quotient.induction_on' y (by tac), add_comm := λ y z, quotient.induction_on₂' z y (by tac), left_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), right_distrib := λ m n k, quotient.induction_on₃' m n k (by tac), ..localization.comm_monoid M } variables (M) /-- Natural hom sending `x : R`, `R` a `comm_ring`, to the equivalence class of `(x, 1)` in the localization of `R` at a submonoid. -/ def of : localization_map M (localization M) := (localization.monoid_of M).to_ring_localization $ λ x y, (con.eq _).2 $ r_of_eq $ by simp [add_comm] variables {M} lemma monoid_of_eq_of (x) : (monoid_of M).to_map x = (of M).to_map x := rfl lemma mk_one_eq_of (x) : mk x 1 = (of M).to_map x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = (of M).mk' x y := mk_eq_monoid_of_mk'_apply _ _ @[simp] lemma mk_eq_mk' : mk = (of M).mk' := mk_eq_monoid_of_mk' variables (f : localization_map M S) /-- Given a localization map `f : R →+* S` for a submonoid `M`, we get an isomorphism between the localization of `R` at `M` as a quotient type and `S`. -/ noncomputable def ring_equiv_of_quotient : localization M ≃+* S := (mul_equiv_of_quotient f.to_localization_map).to_ring_equiv $ ((of M).lift f.map_units).map_add variables {f} @[simp] lemma ring_equiv_of_quotient_apply (x) : ring_equiv_of_quotient f x = (of M).lift f.map_units x := rfl @[simp] lemma ring_equiv_of_quotient_mk' (x y) : ring_equiv_of_quotient f ((of M).mk' x y) = f.mk' x y := mul_equiv_of_quotient_mk' _ _ lemma ring_equiv_of_quotient_mk (x y) : ring_equiv_of_quotient f (mk x y) = f.mk' x y := mul_equiv_of_quotient_mk _ _ @[simp] lemma ring_equiv_of_quotient_of (x) : ring_equiv_of_quotient f ((of M).to_map x) = f.to_map x := mul_equiv_of_quotient_monoid_of _ @[simp] lemma ring_equiv_of_quotient_symm_mk' (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = (of M).mk' x y := mul_equiv_of_quotient_symm_mk' _ _ lemma ring_equiv_of_quotient_symm_mk (x y) : (ring_equiv_of_quotient f).symm (f.mk' x y) = mk x y := mul_equiv_of_quotient_symm_mk _ _ @[simp] lemma ring_equiv_of_quotient_symm_of (x) : (ring_equiv_of_quotient f).symm (f.to_map x) = (of M).to_map x := mul_equiv_of_quotient_symm_monoid_of _ section away variables (x : R) /-- Given `x : R`, the natural hom sending `y : R`, `R` a `comm_ring`, to the equivalence class of `(y, 1)` in the localization of `R` at the submonoid generated by `x`. -/ @[reducible] def away.of : localization_map.away_map x (away x) := of (submonoid.powers x) @[simp] lemma away.mk_eq_mk' : mk = (away.of x).mk' := mk_eq_mk' /-- Given `x : R` and a localization map `f : R →+* S` away from `x`, we get an isomorphism between the localization of `R` at the submonoid generated by `x` as a quotient type and `S`. -/ noncomputable def away.ring_equiv_of_quotient (f : localization_map.away_map x S) : away x ≃+* S := ring_equiv_of_quotient f end away end localization variables {M} section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.2 hxy) hnx hny } end ideal namespace localization_map variables (S) /-- A localization map from `R` to `S` where the submonoid is the complement of a prime ideal of `R`. -/ @[reducible] def at_prime := localization_map I.prime_compl S end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal, as a quotient type. -/ @[reducible] def at_prime := localization I.prime_compl end localization namespace localization_map variables {I} /-- When `f` is a localization map from `R` at the complement of a prime ideal `I`, we use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `local_ring` instance on `S` can 'know' the map needed to induce the instance. -/ instance at_prime.local_ring (f : at_prime S I) : local_ring f.codomain := local_of_nonunits_ideal (λ hze, begin rw [←f.to_map.map_one, ←f.to_map.map_zero] at hze, obtain ⟨t, ht⟩ := f.eq_iff_exists.1 hze, exact ((show (t : R) ∉ I, from t.2) (have htz : (t : R) = 0, by simpa using ht.symm, htz.symm ▸ I.zero_mem)) end) (begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r s}, f.mk' r s ∈ nonunits S → r ∈ I, from λ r s, not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨f.mk' s ⟨r, nr⟩, f.mk'_mul_mk'_eq_one' _ _ nr⟩), rcases f.mk'_surjective x with ⟨rx, sx, hrx⟩, rcases f.mk'_surjective y with ⟨ry, sy, hry⟩, rcases f.mk'_surjective z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←f.mk'_add, ←f.mk'_mul, ←f.mk'_self I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, cases f.eq.1 hxyz with t ht, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, rw [←sub_eq_zero, ←sub_mul] at ht, have hr := (hp.mem_or_mem_of_mul_eq_zero ht).resolve_right t.2, have := I.neg_mem_iff.1 ((ideal.add_mem_iff_right _ _).1 hr), { exact not_or (mt hp.mem_or_mem (not_or sx.2 sy.2)) sz.2 (hp.mem_or_mem this)}, { exact I.mul_mem_right (I.add_mem (I.mul_mem_right (this hx)) (I.mul_mem_right (this hy)))} end) end localization_map namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := localization_map.at_prime.local_ring (of I.prime_compl) end localization end at_prime namespace localization_map variables (f : localization_map M S) section ideals /-- Explicit characterization of the ideal given by `ideal.map f.to_map I`. In practice, this ideal differs only in that the carrier set is defined explicitly. This definition is only meant to be used in proving `mem_map_to_map_iff`, and any proof that needs to refer to the explicit carrier set should use that theorem. -/ private def to_map_ideal (I : ideal R) : ideal S := { carrier := { z : S | ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1}, zero_mem' := ⟨⟨0, 1⟩, by simp⟩, add_mem' := begin rintros a b ⟨a', ha⟩ ⟨b', hb⟩, use ⟨a'.2 * b'.1 + b'.2 * a'.1, I.add_mem (I.smul_mem _ b'.1.2) (I.smul_mem _ a'.1.2)⟩, use a'.2 * b'.2, simp only [ring_hom.map_add, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], rw [add_mul, ← mul_assoc a, ha, mul_comm (f.to_map a'.2) (f.to_map b'.2), ← mul_assoc b, hb], ring end, smul_mem' := begin rintros c x ⟨x', hx⟩, obtain ⟨c', hc⟩ := localization_map.surj f c, use ⟨c'.1 * x'.1, I.smul_mem c'.1 x'.1.2⟩, use c'.2 * x'.2, simp only [←hx, ←hc, smul_eq_mul, submodule.coe_mk, submonoid.coe_mul, ring_hom.map_mul], ring end } theorem mem_map_to_map_iff {I : ideal R} {z} : z ∈ ideal.map f.to_map I ↔ ∃ x : I × M, z * (f.to_map x.2) = f.to_map x.1 := begin split, { show _ → z ∈ to_map_ideal f I, refine λ h, ideal.mem_Inf.1 h (λ z hz, _), obtain ⟨y, hy⟩ := hz, use ⟨⟨⟨y, hy.left⟩, 1⟩, by simp [hy.right]⟩ }, { rintros ⟨⟨a, s⟩, h⟩, rw [← ideal.unit_mul_mem_iff_mem _ (map_units f s), mul_comm], exact h.symm ▸ ideal.mem_map_of_mem a.2 } end theorem map_comap (J : ideal S) : ideal.map f.to_map (ideal.comap f.to_map J) = J := le_antisymm (ideal.map_le_iff_le_comap.2 (le_refl _)) $ λ x hJ, begin obtain ⟨r, s, hx⟩ := f.mk'_surjective x, rw ←hx at ⊢ hJ, exact ideal.mul_mem_right _ (ideal.mem_map_of_mem (show f.to_map r ∈ J, from f.mk'_spec r s ▸ @ideal.mul_mem_right _ _ J (f.mk' r s) (f.to_map s) hJ)), end theorem comap_map_of_is_prime_disjoint (I : ideal R) (hI : I.is_prime) (hM : disjoint (M : set R) I) : ideal.comap f.to_map (ideal.map f.to_map I) = I := begin refine le_antisymm (λ a ha, _) ideal.le_comap_map, rw [ideal.mem_comap, mem_map_to_map_iff] at ha, obtain ⟨⟨b, s⟩, h⟩ := ha, have : f.to_map (a * ↑s - b) = 0 := by simpa [sub_eq_zero] using h, rw [← f.to_map.map_zero, eq_iff_exists] at this, obtain ⟨c, hc⟩ := this, have : a * s ∈ I, { rw zero_mul at hc, let this : (a * ↑s - ↑b) * ↑c ∈ I := hc.symm ▸ I.zero_mem, cases hI.right this with h1 h2, { simpa using I.add_mem h1 b.2 }, { exfalso, refine hM ⟨c.2, h2⟩ } }, cases hI.right this with h1 h2, { exact h1 }, { exfalso, refine hM ⟨s.2, h2⟩ } end /-- If `S` is the localization of `R` at a submonoid, the ordering of ideals of `S` is embedded in the ordering of ideals of `R`. -/ def order_embedding : ideal S ↪o ideal R := { to_fun := λ J, ideal.comap f.to_map J, inj' := function.left_inverse.injective f.map_comap, map_rel_iff' := λ J₁ J₂, ⟨ideal.comap_mono, λ hJ, f.map_comap J₁ ▸ f.map_comap J₂ ▸ ideal.map_mono hJ⟩ } /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its comap, see `le_rel_iso_of_prime` for the more general relation isomorphism -/ lemma is_prime_iff_is_prime_disjoint (J : ideal S) : J.is_prime ↔ (ideal.comap f.to_map J).is_prime ∧ disjoint (M : set R) ↑(ideal.comap f.to_map J) := begin split, { refine λ h, ⟨⟨_, _⟩, λ m hm, h.1 (ideal.eq_top_of_is_unit_mem _ hm.2 (map_units f ⟨m, hm.left⟩))⟩, { refine λ hJ, h.left _, rw [eq_top_iff, (order_embedding f).map_rel_iff], exact le_of_eq hJ.symm }, { intros x y hxy, rw [ideal.mem_comap, ring_hom.map_mul] at hxy, exact h.right hxy } }, { refine λ h, ⟨λ hJ, h.left.left (eq_top_iff.2 _), _⟩, { rwa [eq_top_iff, (order_embedding f).map_rel_iff] at hJ }, { intros x y hxy, obtain ⟨a, s, ha⟩ := mk'_surjective f x, obtain ⟨b, t, hb⟩ := mk'_surjective f y, have : f.mk' (a * b) (s * t) ∈ J := by rwa [mk'_mul, ha, hb], rw [mk'_mem_iff, ← ideal.mem_comap] at this, replace this := h.left.right this, rw [ideal.mem_comap, ideal.mem_comap] at this, rwa [← ha, ← hb, mk'_mem_iff, mk'_mem_iff] } } end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M`. This lemma gives the particular case for an ideal and its map, see `le_rel_iso_of_prime` for the more general relation isomorphism, and the reverse implication -/ lemma is_prime_of_is_prime_disjoint (I : ideal R) (hp : I.is_prime) (hd : disjoint (M : set R) ↑I) : (ideal.map f.to_map I).is_prime := begin rw [is_prime_iff_is_prime_disjoint f, comap_map_of_is_prime_disjoint f I hp hd], exact ⟨hp, hd⟩ end /-- If `R` is a ring, then prime ideals in the localization at `M` correspond to prime ideals in the original ring `R` that are disjoint from `M` -/ def order_iso_of_prime (f : localization_map M S) : {p : ideal S // p.is_prime} ≃o {p : ideal R // p.is_prime ∧ disjoint (M : set R) ↑p} := { to_fun := λ p, ⟨ideal.comap f.to_map p.1, (is_prime_iff_is_prime_disjoint f p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map f.to_map p.1, is_prime_of_is_prime_disjoint f p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap f J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint f I.1 I.2.1 I.2.2), map_rel_iff' := λ I I', ⟨λ h x hx, h hx, λ h, (show I.val ≤ I'.val, from (map_comap f I.val) ▸ (map_comap f I'.val) ▸ (ideal.map_mono h))⟩ } end ideals /-! ### `algebra` section Defines the `R`-algebra instance on a copy of `S` carrying the data of the localization map `f` needed to induce the `R`-algebra structure. -/ /-- We use a copy of the localization map `f`'s codomain `S` carrying the data of `f` so that the `R`-algebra instance on `S` can 'know' the map needed to induce the `R`-algebra structure. -/ instance : algebra R f.codomain := f.to_map.to_algebra end localization_map namespace localization instance : algebra R (localization M) := localization_map.algebra (of M) end localization namespace localization_map variables (f : localization_map M S) @[simp] lemma of_id (a : R) : (algebra.of_id R f.codomain) a = f.to_map a := rfl @[simp] lemma algebra_map_eq : algebra_map R f.codomain = f.to_map := rfl variables (f) /-- Localization map `f` from `R` to `S` as an `R`-linear map. -/ def lin_coe : R →ₗ[R] f.codomain := { to_fun := f.to_map, map_add' := f.to_map.map_add, map_smul' := f.to_map.map_mul } /-- Map from ideals of `R` to submodules of `S` induced by `f`. -/ -- This was previously a `has_coe` instance, but if `f.codomain = R` then this will loop. -- It could be a `has_coe_t` instance, but we keep it explicit here to avoid slowing down -- the rest of the library. def coe_submodule (I : ideal R) : submodule R f.codomain := submodule.map f.lin_coe I variables {f} lemma mem_coe_submodule (I : ideal R) {x : S} : x ∈ f.coe_submodule I ↔ ∃ y : R, y ∈ I ∧ f.to_map y = x := iff.rfl @[simp] lemma lin_coe_apply {x} : f.lin_coe x = f.to_map x := rfl variables {g : R →+* P} variables {T : submonoid P} (hy : ∀ y : M, g y ∈ T) {Q : Type*} [comm_ring Q] (k : localization_map T Q) lemma map_smul (x : f.codomain) (z : R) : f.map hy k (z • x : f.codomain) = @has_scalar.smul P k.codomain _ (g z) (f.map hy k x) := show f.map hy k (f.to_map z * x) = k.to_map (g z) * f.map hy k x, by rw [ring_hom.map_mul, map_eq] section integer_normalization open finsupp polynomial open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : polynomial f.codomain) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_mem_support (p : polynomial f.codomain) (i : ℕ) (h : coeff_integer_normalization p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization : polynomial f.codomain → polynomial R := λ p, on_finset p.support (coeff_integer_normalization p) (coeff_integer_normalization_mem_support p) @[simp] lemma integer_normalization_coeff (p : polynomial f.codomain) (i : ℕ) : (integer_normalization p).coeff i = coeff_integer_normalization p i := rfl lemma integer_normalization_spec (p : polynomial f.codomain) : ∃ (b : M), ∀ i, f.to_map ((integer_normalization p).coeff i) = f.to_map b * p.coeff i := begin use classical.some (f.exist_integer_multiples_of_finset (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (f.exist_integer_multiples_of_finset (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (_root_.mul_zero (f.to_map _)).symm, { exact f.to_ring_hom.map_zero }, { exact finsupp.not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : polynomial f.codomain) : ∃ (b : M), (integer_normalization p).map f.to_map = f.to_map b • p := let ⟨b, hb⟩ := integer_normalization_spec p in ⟨b, polynomial.ext (λ i, by { rw coeff_map, exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : f.codomain →+* R') (p : polynomial f.codomain) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp f.to_map) x (integer_normalization p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map p in trans (eval₂_map f.to_map g x).symm (by rw [hb, eval₂_smul, hx, smul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra f.codomain R'] [is_scalar_tower R f.codomain R'] (p : polynomial f.codomain) {x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R f.codomain R', algebra_map_eq, integer_normalization_eval₂_eq_zero _ _ hx] end integer_normalization end localization_map variables (R) {A : Type*} [integral_domain A] variables (K : Type*) section non_zero_divisors /-- The submonoid of non-zero-divisors of a `comm_ring` `R`. -/ def non_zero_divisors : submonoid R := { carrier := {x | ∀ z, z * x = 0 → z = 0}, one_mem' := λ z hz, by rwa mul_one at hz, mul_mem' := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } variables {R} lemma mul_mem_non_zero_divisors {a b : R} : a * b ∈ non_zero_divisors R ↔ a ∈ non_zero_divisors R ∧ b ∈ non_zero_divisors R := begin split, { intro h, split; intros x h'; apply h, { rw [←mul_assoc, h', zero_mul] }, { rw [mul_comm a b, ←mul_assoc, h', zero_mul] } }, { rintros ⟨ha, hb⟩ x hx, apply ha, apply hb, rw [mul_assoc, hx] }, end lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : A} (hnx : x ≠ 0) (hxy : y * x = 0) : y = 0 := or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_iff_ne_zero {x : A} : x ∈ non_zero_divisors A ↔ x ≠ 0 := ⟨λ hm hz, zero_ne_one (hm 1 $ by rw [hz, one_mul]).symm, λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx⟩ lemma map_ne_zero_of_mem_non_zero_divisors {B : Type*} [ring B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ≠ 0 := λ h0, mem_non_zero_divisors_iff_ne_zero.1 x.2 $ g.injective_iff.1 hg x h0 lemma map_mem_non_zero_divisors {B : Type*} [integral_domain B] {g : A →+* B} (hg : injective g) {x : non_zero_divisors A} : g x ∈ non_zero_divisors B := λ z hz, eq_zero_of_ne_zero_of_mul_eq_zero (map_ne_zero_of_mem_non_zero_divisors hg) hz variables {K} lemma le_non_zero_divisors_of_domain [integral_domain K] {M : submonoid K} (hM : ↑0 ∉ M) : M ≤ non_zero_divisors K := λ x hx y hy, or.rec_on (eq_zero_or_eq_zero_of_mul_eq_zero hy) (λ h, h) (λ h, absurd (h ▸ hx : (0 : K) ∈ M) hM) namespace localization_map lemma to_map_eq_zero_iff (f : localization_map M S) {x : R} (hM : M ≤ non_zero_divisors R) : f.to_map x = 0 ↔ x = 0 := begin rw ← f.to_map.map_zero, split; intro h, { cases f.eq_iff_exists.mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end lemma injective (f : localization_map M S) (hM : M ≤ non_zero_divisors R) : injective f.to_map := begin rw ring_hom.injective_iff f.to_map, intros a ha, rw [← f.to_map.map_zero, f.eq_iff_exists] at ha, cases ha with c hc, rw zero_mul at hc, exact hM c.2 a hc, end protected lemma to_map_ne_zero_of_mem_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) (x : non_zero_divisors A) : f.to_map x ≠ 0 := map_ne_zero_of_mem_non_zero_divisors (f.injective hM) /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. -/ def integral_domain_of_le_non_zero_divisors {M : submonoid A} (f : localization_map M S) (hM : M ≤ non_zero_divisors A) : integral_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases f.surj z with x hx, cases f.surj w with y hy, have : z * w * f.to_map y.2 * f.to_map x.2 = f.to_map x.1 * f.to_map y.1, by rw [mul_assoc z, hy, ←hx]; ac_refl, rw [h, zero_mul, zero_mul, ← f.to_map.map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff f hM).mp this.symm) with H H, { exact or.inl (f.eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (f.eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨f.to_map 0, f.to_map 1, λ h, zero_ne_one (f.injective hM h)⟩, ..(infer_instance : comm_ring S) } /-- The localization at of an integral domain to a set of non-zero elements is an integral domain -/ def integral_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : integral_domain (localization M) := (localization.of M).integral_domain_of_le_non_zero_divisors hM /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance integral_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : integral_domain (localization.at_prime P) := integral_domain_localization (le_non_zero_divisors_of_domain (by simpa only [] using P.zero_mem)) end localization_map end non_zero_divisors /-- Localization map from an integral domain `R` to its field of fractions. -/ @[reducible] def fraction_map [comm_ring K] := localization_map (non_zero_divisors R) K namespace fraction_map open localization_map variables {R K} lemma to_map_eq_zero_iff [comm_ring K] (φ : fraction_map R K) {x : R} : φ.to_map x = 0 ↔ x = 0 := φ.to_map_eq_zero_iff (le_of_eq rfl) protected theorem injective [comm_ring K] (φ : fraction_map R K) : function.injective φ.to_map := φ.injective (le_of_eq rfl) protected lemma to_map_ne_zero_of_mem_non_zero_divisors [comm_ring K] (φ : fraction_map A K) (x : non_zero_divisors A) : φ.to_map x ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (le_of_eq rfl) x /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is an integral domain. -/ def to_integral_domain [comm_ring K] (φ : fraction_map A K) : integral_domain K := φ.integral_domain_of_le_non_zero_divisors (le_of_eq rfl) local attribute [instance] classical.dec_eq /-- The inverse of an element in the field of fractions of an integral domain. -/ protected noncomputable def inv [comm_ring K] (φ : fraction_map A K) (z : K) : K := if h : z = 0 then 0 else φ.mk' (φ.to_localization_map.sec z).2 ⟨(φ.to_localization_map.sec z).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, h $ φ.eq_zero_of_fst_eq_zero (sec_spec z) h0⟩ protected lemma mul_inv_cancel [comm_ring K] (φ : fraction_map A K) (x : K) (hx : x ≠ 0) : x * φ.inv x = 1 := show x * dite _ _ _ = 1, by rw [dif_neg hx, ←is_unit.mul_left_inj (φ.map_units ⟨(φ.to_localization_map.sec x).1, mem_non_zero_divisors_iff_ne_zero.2 $ λ h0, hx $ φ.eq_zero_of_fst_eq_zero (sec_spec x) h0⟩), one_mul, mul_assoc, mk'_spec, ←eq_mk'_iff_mul_eq]; exact (φ.mk'_sec x).symm /-- A `comm_ring` `K` which is the localization of an integral domain `R` at `R - {0}` is a field. -/ noncomputable def to_field [comm_ring K] (φ : fraction_map A K) : field K := { inv := φ.inv, mul_inv_cancel := φ.mul_inv_cancel, inv_zero := dif_pos rfl, ..φ.to_integral_domain } variables {B : Type*} [integral_domain B] [field K] {L : Type*} [field L] (f : fraction_map A K) {g : A →+* L} lemma mk'_eq_div {r s} : f.mk' r s = f.to_map r / f.to_map s := f.mk'_eq_iff_eq_mul.2 $ (div_mul_cancel _ (f.to_map_ne_zero_of_mem_non_zero_divisors _)).symm lemma is_unit_map_of_injective (hg : function.injective g) (y : non_zero_divisors A) : is_unit (g y) := is_unit.mk0 (g y) $ map_ne_zero_of_mem_non_zero_divisors hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, we get a field hom sending `z : K` to `g x * (g y)⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift (hg : injective g) : K →+* L := f.lift $ is_unit_map_of_injective hg /-- Given an integral domain `A`, a localization map to its fields of fractions `f : A →+* K`, and an injective ring hom `g : A →+* L` where `L` is a field, field hom induced from `K` to `L` maps `f x / f y` to `g x / g y` for all `x : A, y ∈ non_zero_divisors A`. -/ @[simp] lemma lift_mk' (hg : injective g) (x y) : f.lift hg (f.mk' x y) = g x / g y := begin erw f.lift_mk' (is_unit_map_of_injective hg), erw submonoid.localization_map.mul_inv_left (λ y : non_zero_divisors A, show is_unit (g.to_monoid_hom y), from is_unit_map_of_injective hg y), exact (mul_div_cancel' _ (map_ne_zero_of_mem_non_zero_divisors hg)).symm, end /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L` and an injective ring hom `j : A →+* B`, we get a field hom sending `z : K` to `g (j x) * (g (j y))⁻¹`, where `(x, y) : A × (non_zero_divisors A)` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : fraction_map B L) {j : A →+* B} (hj : injective j) : K →+* L := f.map (λ y, mem_non_zero_divisors_iff_ne_zero.2 $ map_ne_zero_of_mem_non_zero_divisors hj) g /-- Given integral domains `A, B` and localization maps to their fields of fractions `f : A →+* K, g : B →+* L`, an isomorphism `j : A ≃+* B` induces an isomorphism of fields of fractions `K ≃+* L`. -/ noncomputable def field_equiv_of_ring_equiv (g : fraction_map B L) (h : A ≃+* B) : K ≃+* L := f.ring_equiv_of_ring_equiv g h begin ext b, show b ∈ h.to_equiv '' _ ↔ _, erw [h.to_equiv.image_eq_preimage, set.preimage, set.mem_set_of_eq, mem_non_zero_divisors_iff_ne_zero, mem_non_zero_divisors_iff_ne_zero], exact h.symm.map_ne_zero_iff end /-- The cast from `int` to `rat` as a `fraction_map`. -/ def int.fraction_map : fraction_map ℤ ℚ := { to_fun := coe, map_units' := begin rintro ⟨x, hx⟩, rw [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hx, simpa only [is_unit_iff_ne_zero, int.cast_eq_zero, ne.def, subtype.coe_mk] using hx, end, surj' := begin rintro ⟨n, d, hd, h⟩, refine ⟨⟨n, ⟨d, _⟩⟩, rat.mul_denom_eq_num⟩, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero, int.coe_nat_ne_zero_iff_pos] end, eq_iff_exists' := begin intros x y, rw [int.cast_inj], refine ⟨by { rintro rfl, use 1 }, _⟩, rintro ⟨⟨c, hc⟩, h⟩, apply int.eq_of_mul_eq_mul_right _ h, rwa [submonoid.mem_carrier, mem_non_zero_divisors_iff_ne_zero] at hc, end, ..int.cast_ring_hom ℚ } lemma integer_normalization_eq_zero_iff {p : polynomial f.codomain} : integer_normalization p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec p, split; intros h i, { apply f.to_map_eq_zero_iff.mp, rw [hb i, h i], exact _root_.mul_zero _ }, { have hi := h i, rw [polynomial.coeff_zero, ← f.to_map_eq_zero_iff, hb i] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact f.to_map_eq_zero_iff.mp h } end /-- A field is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] : algebra.is_algebraic A L ↔ algebra.is_algebraic f.codomain L := begin split; intros h x; obtain ⟨p, hp, px⟩ := h x, { refine ⟨p.map f.to_map, λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : f.to_map (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact f.to_map_eq_zero_iff.mp this }, { rwa [is_scalar_tower.aeval_apply _ f.codomain, algebra_map_eq] at px } }, { exact ⟨integer_normalization p, mt f.integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero p px⟩ }, end section num_denom variables [unique_factorization_domain A] (φ : fraction_map A K) lemma exists_reduced_fraction (x : φ.codomain) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ φ.mk' a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := φ.exists_integer_multiple x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_domain.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, apply mul_left_cancel' (φ.to_map_ne_zero_of_mem_non_zero_divisors ⟨c' * b', b_nonzero⟩), simp only [subtype.coe_mk, φ.to_map.map_mul] at *, erw [←hab, mul_assoc, φ.mk'_spec' a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : φ.codomain) : A := classical.some (φ.exists_reduced_fraction x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : φ.codomain) : non_zero_divisors A := classical.some (classical.some_spec (φ.exists_reduced_fraction x)) lemma num_denom_reduced (x : φ.codomain) : ∀ {d}, d ∣ φ.num x → d ∣ φ.denom x → is_unit d := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).1 @[simp] lemma mk'_num_denom (x : φ.codomain) : φ.mk' (φ.num x) (φ.denom x) = x := (classical.some_spec (classical.some_spec (φ.exists_reduced_fraction x))).2 lemma num_mul_denom_eq_num_iff_eq {x y : φ.codomain} : x * φ.to_map (φ.denom y) = φ.to_map (φ.num y) ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : φ.codomain} : y * φ.to_map (φ.denom x) = φ.to_map (φ.num x) ↔ x = y := ⟨ λ h, by simpa only [eq_comm, mk'_num_denom] using φ.eq_mk'_iff_mul_eq.mpr h, λ h, φ.eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom]) ⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : φ.codomain} : φ.num y * φ.denom x = φ.num x * φ.denom y ↔ x = y := ⟨ λ h, by simpa only [mk'_num_denom] using φ.mk'_eq_of_eq h, λ h, by rw h ⟩ lemma eq_zero_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : x = 0 := φ.num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : φ.codomain} (h : is_unit (φ.denom x : A)) : φ.is_integer x := begin cases h with d hd, have d_ne_zero : φ.to_map (φ.denom x) ≠ 0 := φ.to_map_ne_zero_of_mem_non_zero_divisors (φ.denom x), use ↑d⁻¹ * φ.num x, refine trans _ (φ.mk'_num_denom x), rw [φ.to_map.map_mul, φ.to_map.map_units_inv, hd], apply mul_left_cancel' d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, φ.mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : φ.codomain} (h : φ.num x = 0) : is_unit (φ.denom x : A) := φ.num_denom_reduced x (h.symm ▸ dvd_zero _) (dvd_refl _) end num_denom end fraction_map namespace integral_closure variables {L : Type*} [field K] [field L] {f : fraction_map A K} open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : fraction_map (integral_closure A L) L := (algebra_map (integral_closure A L) L).to_localization_map (λ ⟨⟨y, integral⟩, nonzero⟩, have y ≠ 0 := λ h, mem_non_zero_divisors_iff_ne_zero.mp nonzero (subtype.ext_iff_val.mpr h), show is_unit y, from ⟨⟨y, y⁻¹, mul_inv_cancel this, inv_mul_cancel this⟩, rfl⟩) (λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨x, ⟨y, mem_non_zero_divisors_iff_ne_zero.mpr hy⟩⟩, hxy⟩) (λ x y, ⟨ λ (h : x.1 = y.1), ⟨1, by simpa using subtype.ext_iff_val.mpr h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel' (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc) ⟩) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ def fraction_map_of_finite_extension [algebra A L] [algebra f.codomain L] [is_scalar_tower A f.codomain L] [finite_dimensional f.codomain L] : fraction_map (integral_closure A L) L := fraction_map_of_algebraic (f.comap_is_algebraic_iff.mpr is_algebraic_of_finite) (λ x hx, f.to_map_eq_zero_iff.mp ((algebra_map f.codomain L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end integral_closure variables (A) /-- The fraction field of an integral domain as a quotient type. -/ @[reducible] def fraction_ring := localization (non_zero_divisors A) /-- Natural hom sending `x : A`, `A` an integral domain, to the equivalence class of `(x, 1)` in the field of fractions of `A`. -/ def of : fraction_map A (localization (non_zero_divisors A)) := localization.of (non_zero_divisors A) namespace fraction_ring variables {A} noncomputable instance : field (fraction_ring A) := (of A).to_field @[simp] lemma mk_eq_div {r s} : (localization.mk r s : fraction_ring A) = ((of A).to_map r / (of A).to_map s : fraction_ring A) := by erw [localization.mk_eq_mk', (of A).mk'_eq_div] /-- Given an integral domain `A` and a localization map to a field of fractions `f : A →+* K`, we get an isomorphism between the field of fractions of `A` as a quotient type and `K`. -/ noncomputable def field_equiv_of_quotient {K : Type*} [field K] (f : fraction_map A K) : fraction_ring A ≃+* K := localization.ring_equiv_of_quotient f end fraction_ring
dd4f02c1da5e208ab7a48f3b64cbda686f3b8e7b
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/function/lp_order.lean
fa528399bfcf18eeea301cf7b83bcb8721774522
[ "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
3,466
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import analysis.normed.order.lattice import measure_theory.function.lp_space /-! # Order related properties of Lp spaces ### Results - `Lp E p μ` is an `ordered_add_comm_group` when `E` is a `normed_lattice_add_comm_group`. ### TODO - move definitions of `Lp.pos_part` and `Lp.neg_part` to this file, and define them as `has_pos_part.pos` and `has_pos_part.neg` given by the lattice structure. -/ open topological_space measure_theory lattice_ordered_comm_group open_locale ennreal variables {α E : Type*} {m : measurable_space α} {μ : measure α} {p : ℝ≥0∞} namespace measure_theory namespace Lp section order variables [normed_lattice_add_comm_group E] lemma coe_fn_le (f g : Lp E p μ) : f ≤ᵐ[μ] g ↔ f ≤ g := by rw [← subtype.coe_le_coe, ← ae_eq_fun.coe_fn_le, ← coe_fn_coe_base, ← coe_fn_coe_base] lemma coe_fn_nonneg (f : Lp E p μ) : 0 ≤ᵐ[μ] f ↔ 0 ≤ f := begin rw ← coe_fn_le, have h0 := Lp.coe_fn_zero E p μ, split; intro h; filter_upwards [h, h0] with _ _ h2, { rwa h2, }, { rwa ← h2, }, end instance : covariant_class (Lp E p μ) (Lp E p μ) (+) (≤) := begin refine ⟨λ f g₁ g₂ hg₁₂, _⟩, rw ← coe_fn_le at hg₁₂ ⊢, filter_upwards [coe_fn_add f g₁, coe_fn_add f g₂, hg₁₂] with _ h1 h2 h3, rw [h1, h2, pi.add_apply, pi.add_apply], exact add_le_add le_rfl h3, end instance : ordered_add_comm_group (Lp E p μ) := { add_le_add_left := λ f g, add_le_add_left, ..subtype.partial_order _, ..add_subgroup.to_add_comm_group _} lemma _root_.measure_theory.mem_ℒp.sup {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f ⊔ g) p μ := mem_ℒp.mono' (hf.norm.add hg.norm) (hf.1.sup hg.1) (filter.eventually_of_forall (λ x, norm_sup_le_add (f x) (g x))) lemma _root_.measure_theory.mem_ℒp.inf {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f ⊓ g) p μ := mem_ℒp.mono' (hf.norm.add hg.norm) (hf.1.inf hg.1) (filter.eventually_of_forall (λ x, norm_inf_le_add (f x) (g x))) lemma _root_.measure_theory.mem_ℒp.abs {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (|f|) p μ := hf.sup hf.neg instance : lattice (Lp E p μ) := subtype.lattice (λ f g hf hg, by { rw mem_Lp_iff_mem_ℒp at *, exact (mem_ℒp_congr_ae (ae_eq_fun.coe_fn_sup _ _)).mpr (hf.sup hg), }) (λ f g hf hg, by { rw mem_Lp_iff_mem_ℒp at *, exact (mem_ℒp_congr_ae (ae_eq_fun.coe_fn_inf _ _)).mpr (hf.inf hg),}) lemma coe_fn_sup (f g : Lp E p μ) : ⇑(f ⊔ g) =ᵐ[μ] ⇑f ⊔ ⇑g := ae_eq_fun.coe_fn_sup _ _ lemma coe_fn_inf (f g : Lp E p μ) : ⇑(f ⊓ g) =ᵐ[μ] ⇑f ⊓ ⇑g := ae_eq_fun.coe_fn_inf _ _ lemma coe_fn_abs (f : Lp E p μ) : ⇑|f| =ᵐ[μ] λ x, |f x| := ae_eq_fun.coe_fn_abs _ noncomputable instance [fact (1 ≤ p)] : normed_lattice_add_comm_group (Lp E p μ) := { add_le_add_left := λ f g, add_le_add_left, solid := λ f g hfg, begin rw ← coe_fn_le at hfg, simp_rw [Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top f) (Lp.snorm_ne_top g)], refine snorm_mono_ae _, filter_upwards [hfg, Lp.coe_fn_abs f, Lp.coe_fn_abs g] with x hx hxf hxg, rw [hxf, hxg] at hx, exact has_solid_norm.solid hx, end, ..Lp.lattice, ..Lp.normed_add_comm_group, } end order end Lp end measure_theory
270d8a1db32bf70700065f6c865f9cff2691994b
a6b711a4e8db20755026231f7ed529a9014b2b6d
/ZZ_IGNORE/RAW/dm_rat/dm_rat.lean
f02718f518324efbf6662af6916e1d817b4425be
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
394
lean
--fix imports, code is good import .natural import .integer open natural open integer structure rational := mk_rational :: (num : integer) (denom : natural) (pos : ¬ denom = O) open rational def zero_over_one := mk_rational (of_nat O) (S O) (by contradiction) def one_half := mk_rational (of_nat (S O)) (S (S O)) (by contradiction) #check mk_rational (of_nat O) (S O) (by contradiction)
91f20fbf5c7dc065207c7a08607d0c18bcb63ede
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/init/num.hlean
a38e9dd9369e4dca75ef432af7be6cd6171b0654
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,346
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.bool open bool definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one namespace pos_num definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, bit0 n) (λn r, cond (is_one n) one (bit1 r)) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λn f b, pos_num.rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, pos_num.rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b notation a + b := add a b definition mul (a b : pos_num) : pos_num := pos_num.rec_on a b (λn r, bit0 r + b) (λn r, bit0 r) notation a * b := mul a b definition lt (a b : pos_num) : bool := pos_num.rec_on a (λ b, pos_num.cases_on b ff (λm, tt) (λm, tt)) (λn f b, pos_num.cases_on b ff (λm, f m) (λm, f m)) (λn f b, pos_num.cases_on b ff (λm, f (succ m)) (λm, f m)) b definition le (a b : pos_num) : bool := lt a (succ b) definition equal (a b : pos_num) : bool := le a b && le b a end pos_num definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero namespace num open pos_num definition pred (a : num) : num := num.rec_on a zero (λp, cond (is_one p) zero (pos (pred p))) definition size (a : num) : num := num.rec_on a (pos one) (λp, pos (size p)) definition add (a b : num) : num := num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb))) definition mul (a b : num) : num := num.rec_on a zero (λpa, num.rec_on b zero (λpb, pos (pos_num.mul pa pb))) notation a + b := add a b notation a * b := mul a b definition le (a b : num) : bool := num.rec_on a tt (λpa, num.rec_on b ff (λpb, pos_num.le pa pb)) private definition psub (a b : pos_num) : num := pos_num.rec_on a (λb, zero) (λn f b, cond (pos_num.le (bit1 n) b) zero (pos_num.cases_on b (pos (bit0 n)) (λm, 2 * f m) (λm, 2 * f m + 1))) (λn f b, cond (pos_num.le (bit0 n) b) zero (pos_num.cases_on b (pos (pos_num.pred (bit0 n))) (λm, pred (2 * f m)) (λm, 2 * f m))) b definition sub (a b : num) : num := num.rec_on a zero (λpa, num.rec_on b a (λpb, psub pa pb)) notation a ≤ b := le a b notation a - b := sub a b end num -- the coercion from num to nat is defined here, -- so that it can already be used in init.trunc and init.tactic namespace nat definition add (a b : nat) : nat := nat.rec_on b a (λ b₁ r, succ r) notation a + b := add a b definition of_num [coercion] (n : num) : nat := num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, r + r + (succ zero)) (λ n r, r + r) n) n end nat attribute nat.of_num [reducible] -- of_num is also reducible if namespace "nat" is not opened
5890828a7e33ecd55c00f4fc8438dac681a39eb7
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/monoidal/functor.lean
9211029b454f992b7f5dfcf1cb50a99444e68da8
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
14,497
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison, Bhavik Mehta -/ import category_theory.monoidal.category import category_theory.adjunction.basic /-! # (Lax) monoidal functors A lax monoidal functor `F` between monoidal categories `C` and `D` is a functor between the underlying categories equipped with morphisms * `ε : 𝟙_ D ⟶ F.obj (𝟙_ C)` (called the unit morphism) * `μ X Y : (F.obj X) ⊗ (F.obj Y) ⟶ F.obj (X ⊗ Y)` (called the tensorator, or strength). satisfying various axioms. A monoidal functor is a lax monoidal functor for which `ε` and `μ` are isomorphisms. We show that the composition of (lax) monoidal functors gives a (lax) monoidal functor. See also `category_theory.monoidal.functorial` for a typeclass decorating an object-level function with the additional data of a monoidal functor. This is useful when stating that a pre-existing functor is monoidal. See `category_theory.monoidal.natural_transformation` for monoidal natural transformations. We show in `category_theory.monoidal.Mon_` that lax monoidal functors take monoid objects to monoid objects. ## Future work * Oplax monoidal functors. ## References See https://stacks.math.columbia.edu/tag/0FFL. -/ open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory section open monoidal_category variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] (D : Type u₂) [category.{v₂} D] [monoidal_category.{v₂} D] /-- A lax monoidal functor is a functor `F : C ⥤ D` between monoidal categories, equipped with morphisms `ε : 𝟙 _D ⟶ F.obj (𝟙_ C)` and `μ X Y : F.obj X ⊗ F.obj Y ⟶ F.obj (X ⊗ Y)`, satisfying the appropriate coherences. -/ -- The direction of `left_unitality` and `right_unitality` as simp lemmas may look strange: -- remember the rule of thumb that component indices of natural transformations -- "weigh more" than structural maps. -- (However by this argument `associativity` is currently stated backwards!) structure lax_monoidal_functor extends C ⥤ D := -- unit morphism (ε : 𝟙_ D ⟶ obj (𝟙_ C)) -- tensorator (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (α_ X Y Z).hom = (α_ (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (λ_ (obj X)).hom = (ε ⊗ 𝟙 (obj X)) ≫ μ (𝟙_ C) X ≫ map (λ_ X).hom . obviously) (right_unitality' : ∀ X : C, (ρ_ (obj X)).hom = (𝟙 (obj X) ⊗ ε) ≫ μ X (𝟙_ C) ≫ map (ρ_ X).hom . obviously) restate_axiom lax_monoidal_functor.μ_natural' attribute [simp, reassoc] lax_monoidal_functor.μ_natural restate_axiom lax_monoidal_functor.left_unitality' attribute [simp] lax_monoidal_functor.left_unitality restate_axiom lax_monoidal_functor.right_unitality' attribute [simp] lax_monoidal_functor.right_unitality restate_axiom lax_monoidal_functor.associativity' attribute [simp, reassoc] lax_monoidal_functor.associativity -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity section variables {C D} @[simp, reassoc] lemma lax_monoidal_functor.left_unitality_inv (F : lax_monoidal_functor C D) (X : C) : (λ_ (F.obj X)).inv ≫ (F.ε ⊗ 𝟙 (F.obj X)) ≫ F.μ (𝟙_ C) X = F.map (λ_ X).inv := begin rw [iso.inv_comp_eq, F.left_unitality, category.assoc, category.assoc, ←F.to_functor.map_comp, iso.hom_inv_id, F.to_functor.map_id, comp_id], end @[simp, reassoc] lemma lax_monoidal_functor.right_unitality_inv (F : lax_monoidal_functor C D) (X : C) : (ρ_ (F.obj X)).inv ≫ (𝟙 (F.obj X) ⊗ F.ε) ≫ F.μ X (𝟙_ C) = F.map (ρ_ X).inv := begin rw [iso.inv_comp_eq, F.right_unitality, category.assoc, category.assoc, ←F.to_functor.map_comp, iso.hom_inv_id, F.to_functor.map_id, comp_id], end @[simp, reassoc] lemma lax_monoidal_functor.associativity_inv (F : lax_monoidal_functor C D) (X Y Z : C) : (𝟙 (F.obj X) ⊗ F.μ Y Z) ≫ F.μ X (Y ⊗ Z) ≫ F.map (α_ X Y Z).inv = (α_ (F.obj X) (F.obj Y) (F.obj Z)).inv ≫ (F.μ X Y ⊗ 𝟙 (F.obj Z)) ≫ F.μ (X ⊗ Y) Z := begin rw [iso.eq_inv_comp, ←F.associativity_assoc, ←F.to_functor.map_comp, iso.hom_inv_id, F.to_functor.map_id, comp_id], end end /-- A monoidal functor is a lax monoidal functor for which the tensorator and unitor as isomorphisms. See https://stacks.math.columbia.edu/tag/0FFL. -/ structure monoidal_functor extends lax_monoidal_functor.{v₁ v₂} C D := (ε_is_iso : is_iso ε . tactic.apply_instance) (μ_is_iso : Π X Y : C, is_iso (μ X Y) . tactic.apply_instance) attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso variables {C D} /-- The unit morphism of a (strong) monoidal functor as an isomorphism. -/ noncomputable def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : tensor_unit D ≅ F.obj (tensor_unit C) := as_iso F.ε /-- The tensorator of a (strong) monoidal functor as an isomorphism. -/ noncomputable def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := as_iso (F.μ X Y) end open monoidal_category namespace lax_monoidal_functor variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] /-- The identity lax monoidal functor. -/ @[simps] def id : lax_monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. 𝟭 C } instance : inhabited (lax_monoidal_functor C C) := ⟨id C⟩ end lax_monoidal_functor namespace monoidal_functor section variables {C : Type u₁} [category.{v₁} C] [monoidal_category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] variable (F : monoidal_functor.{v₁ v₂} C D) lemma map_tensor {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : F.map (f ⊗ g) = inv (F.μ X X') ≫ ((F.map f) ⊗ (F.map g)) ≫ F.μ Y Y' := by simp lemma map_left_unitor (X : C) : F.map (λ_ X).hom = inv (F.μ (𝟙_ C) X) ≫ (inv F.ε ⊗ 𝟙 (F.obj X)) ≫ (λ_ (F.obj X)).hom := begin simp only [lax_monoidal_functor.left_unitality], slice_rhs 2 3 { rw ←comp_tensor_id, simp, }, simp, end lemma map_right_unitor (X : C) : F.map (ρ_ X).hom = inv (F.μ X (𝟙_ C)) ≫ (𝟙 (F.obj X) ⊗ inv F.ε) ≫ (ρ_ (F.obj X)).hom := begin simp only [lax_monoidal_functor.right_unitality], slice_rhs 2 3 { rw ←id_tensor_comp, simp, }, simp, end /-- The tensorator as a natural isomorphism. -/ noncomputable def μ_nat_iso : (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := nat_iso.of_components (by { intros, apply F.μ_iso }) (by { intros, apply F.to_lax_monoidal_functor.μ_natural }) @[simp] lemma μ_iso_hom (X Y : C) : (F.μ_iso X Y).hom = F.μ X Y := rfl @[simp, reassoc] lemma μ_inv_hom_id (X Y : C) : (F.μ_iso X Y).inv ≫ F.μ X Y = 𝟙 _ := (F.μ_iso X Y).inv_hom_id @[simp] lemma μ_hom_inv_id (X Y : C) : F.μ X Y ≫ (F.μ_iso X Y).inv = 𝟙 _ := (F.μ_iso X Y).hom_inv_id @[simp] lemma ε_iso_hom : F.ε_iso.hom = F.ε := rfl @[simp, reassoc] lemma ε_inv_hom_id : F.ε_iso.inv ≫ F.ε = 𝟙 _ := F.ε_iso.inv_hom_id @[simp] lemma ε_hom_inv_id : F.ε ≫ F.ε_iso.inv = 𝟙 _ := F.ε_iso.hom_inv_id end section variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] /-- The identity monoidal functor. -/ @[simps] def id : monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. 𝟭 C } instance : inhabited (monoidal_functor C C) := ⟨id C⟩ end end monoidal_functor variables {C : Type u₁} [category.{v₁} C] [monoidal_category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] [monoidal_category.{v₃} E] namespace lax_monoidal_functor variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- The proofs here are horrendous; rewrite_search helps a lot. /-- The composition of two lax monoidal functors is again lax monoidal. -/ @[simps] def comp : lax_monoidal_functor.{v₁ v₃} C E := { ε := G.ε ≫ (G.map F.ε), μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), μ_natural' := λ _ _ _ _ f g, begin simp only [functor.comp_map, assoc], rw [←category.assoc, lax_monoidal_functor.μ_natural, category.assoc, ←map_comp, ←map_comp, ←lax_monoidal_functor.μ_natural] end, associativity' := λ X Y Z, begin dsimp, rw id_tensor_comp, slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, slice_rhs 1 3 { rw ←G.associativity, }, rw comp_tensor_id, slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, F.associativity], end, left_unitality' := λ X, begin dsimp, rw [G.left_unitality, comp_tensor_id, category.assoc, category.assoc], apply congr_arg, rw [F.left_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, right_unitality' := λ X, begin dsimp, rw [G.right_unitality, id_tensor_comp, category.assoc, category.assoc], apply congr_arg, rw [F.right_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, .. (F.to_functor) ⋙ (G.to_functor) }. infixr ` ⊗⋙ `:80 := comp end lax_monoidal_functor namespace monoidal_functor variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) /-- The composition of two monoidal functors is again monoidal. -/ @[simps] def comp : monoidal_functor.{v₁ v₃} C E := { ε_is_iso := by { dsimp, apply_instance }, μ_is_iso := by { dsimp, apply_instance }, .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. infixr ` ⊗⋙ `:80 := comp -- We overload notation; potentially dangerous, but it seems to work. end monoidal_functor /-- If we have a right adjoint functor `G` to a monoidal functor `F`, then `G` has a lax monoidal structure as well. -/ @[simps] noncomputable def monoidal_adjoint (F : monoidal_functor C D) {G : D ⥤ C} (h : F.to_functor ⊣ G) : lax_monoidal_functor D C := { to_functor := G, ε := h.hom_equiv _ _ (inv F.ε), μ := λ X Y, h.hom_equiv _ (X ⊗ Y) (inv (F.μ (G.obj X) (G.obj Y)) ≫ (h.counit.app X ⊗ h.counit.app Y)), μ_natural' := λ X Y X' Y' f g, begin rw [←h.hom_equiv_naturality_left, ←h.hom_equiv_naturality_right, equiv.apply_eq_iff_eq, assoc, is_iso.eq_inv_comp, ←F.to_lax_monoidal_functor.μ_natural_assoc, is_iso.hom_inv_id_assoc, ←tensor_comp, adjunction.counit_naturality, adjunction.counit_naturality, tensor_comp], end, associativity' := λ X Y Z, begin rw [←h.hom_equiv_naturality_right, ←h.hom_equiv_naturality_left, ←h.hom_equiv_naturality_left, ←h.hom_equiv_naturality_left, equiv.apply_eq_iff_eq, ← cancel_epi (F.to_lax_monoidal_functor.μ (G.obj X ⊗ G.obj Y) (G.obj Z)), ← cancel_epi (F.to_lax_monoidal_functor.μ (G.obj X) (G.obj Y) ⊗ 𝟙 (F.obj (G.obj Z))), F.to_lax_monoidal_functor.associativity_assoc (G.obj X) (G.obj Y) (G.obj Z), ←F.to_lax_monoidal_functor.μ_natural_assoc, assoc, is_iso.hom_inv_id_assoc, ←F.to_lax_monoidal_functor.μ_natural_assoc, is_iso.hom_inv_id_assoc, ←tensor_comp, ←tensor_comp, id_comp, functor.map_id, functor.map_id, id_comp, ←tensor_comp_assoc, ←tensor_comp_assoc, id_comp, id_comp, h.hom_equiv_unit, h.hom_equiv_unit, functor.map_comp, assoc, assoc, h.counit_naturality, h.left_triangle_components_assoc, is_iso.hom_inv_id_assoc, functor.map_comp, assoc, h.counit_naturality, h.left_triangle_components_assoc, is_iso.hom_inv_id_assoc], exact associator_naturality (h.counit.app X) (h.counit.app Y) (h.counit.app Z), end, left_unitality' := λ X, begin rw [←h.hom_equiv_naturality_right, ←h.hom_equiv_naturality_left, ←equiv.symm_apply_eq, h.hom_equiv_counit, F.map_left_unitor, h.hom_equiv_unit, assoc, assoc, assoc, F.map_tensor, assoc, assoc, is_iso.hom_inv_id_assoc, ←tensor_comp_assoc, functor.map_id, id_comp, functor.map_comp, assoc, h.counit_naturality, h.left_triangle_components_assoc, ←left_unitor_naturality, ←tensor_comp_assoc, id_comp, comp_id], end, right_unitality' := λ X, begin rw [←h.hom_equiv_naturality_right, ←h.hom_equiv_naturality_left, ←equiv.symm_apply_eq, h.hom_equiv_counit, F.map_right_unitor, assoc, assoc, ←right_unitor_naturality, ←tensor_comp_assoc, comp_id, id_comp, h.hom_equiv_unit, F.map_tensor, assoc, assoc, assoc, is_iso.hom_inv_id_assoc, functor.map_comp, functor.map_id, ←tensor_comp_assoc, assoc, h.counit_naturality, h.left_triangle_components_assoc, id_comp], end }. /-- If a monoidal functor `F` is an equivalence of categories then its inverse is also monoidal. -/ noncomputable def monoidal_inverse (F : monoidal_functor C D) [is_equivalence F.to_functor] : monoidal_functor D C := { to_lax_monoidal_functor := monoidal_adjoint F (as_equivalence _).to_adjunction, ε_is_iso := by { dsimp [equivalence.to_adjunction], apply_instance }, μ_is_iso := λ X Y, by { dsimp [equivalence.to_adjunction], apply_instance } } @[simp] lemma monoidal_inverse_to_functor (F : monoidal_functor C D) [is_equivalence F.to_functor] : (monoidal_inverse F).to_functor = F.to_functor.inv := rfl end category_theory
ec1f2c53e51a9c50bcde2768c50400b12a7145be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/to_lin.lean
45e7a9858988946e6e7bf184e5b25eb19dd0dfe8
[ "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
35,453
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, Patrick Massot, Casper Putz, Anne Baanen -/ import data.matrix.block import data.matrix.notation import linear_algebra.matrix.finite_dimensional import linear_algebra.std_basis import ring_theory.algebra_tower import algebra.module.algebra import algebra.algebra.subalgebra.tower /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `matrix.to_lin`: the inverse of `linear_map.to_matrix` * `linear_map.to_matrix'`: the `R`-linear equivalence from `(m → R) →ₗ[R] (n → R)` to `matrix m n R` (with the standard basis on `m → R` and `n → R`) * `matrix.to_lin'`: the inverse of `linear_map.to_matrix'` * `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between `R`-endomorphisms of `M` and `matrix n n R` ## Issues This file was originally written without attention to non-commutative rings, and so mostly only works in the commutative setting. This should be fixed. In particular, `matrix.mul_vec` gives us a linear equivalence `matrix m n R ≃ₗ[R] (n → R) →ₗ[Rᵐᵒᵖ] (m → R)` while `matrix.vec_mul` gives us a linear equivalence `matrix m n R ≃ₗ[Rᵐᵒᵖ] (m → R) →ₗ[R] (n → R)`. At present, the first equivalence is developed in detail but only for commutative rings (and we omit the distinction between `Rᵐᵒᵖ` and `R`), while the second equivalence is developed only in brief, but for not-necessarily-commutative rings. Naming is slightly inconsistent between the two developments. In the original (commutative) development `linear` is abbreviated to `lin`, although this is not consistent with the rest of mathlib. In the new (non-commutative) development `linear` is not abbreviated, and declarations use `_right` to indicate they use the right action of matrices on vectors (via `matrix.vec_mul`). When the two developments are made uniform, the names should be made uniform, too, by choosing between `linear` and `lin` consistently, and (presumably) adding `_left` where necessary. ## Tags linear_map, matrix, linear_equiv, diagonal, det, trace -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix universes u v w instance {n m} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance section to_matrix_right variables {R : Type*} [semiring R] variables {l m n : Type*} /-- `matrix.vec_mul M` is a linear map. -/ @[simps] def matrix.vec_mul_linear [fintype m] (M : matrix m n R) : (m → R) →ₗ[R] (n → R) := { to_fun := λ x, M.vec_mul x, map_add' := λ v w, funext (λ i, add_dot_product _ _ _), map_smul' := λ c v, funext (λ i, smul_dot_product _ _ _) } variables [fintype m] [decidable_eq m] @[simp] lemma matrix.vec_mul_std_basis (M : matrix m n R) (i j) : M.vec_mul (std_basis R (λ _, R) i 1) j = M i j := begin have : (∑ i', (if i = i' then 1 else 0) * M i' j) = M i j, { simp_rw [boole_mul, finset.sum_ite_eq, finset.mem_univ, if_true] }, convert this, ext, split_ifs with h; simp only [std_basis_apply], { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h), pi.zero_apply] } end /-- Linear maps `(m → R) →ₗ[R] (n → R)` are linearly equivalent over `Rᵐᵒᵖ` to `matrix m n R`, by having matrices act by right multiplication. -/ def linear_map.to_matrix_right' : ((m → R) →ₗ[R] (n → R)) ≃ₗ[Rᵐᵒᵖ] matrix m n R := { to_fun := λ f i j, f (std_basis R (λ _, R) i 1) j, inv_fun := matrix.vec_mul_linear, right_inv := λ M, by { ext i j, simp only [matrix.vec_mul_std_basis, matrix.vec_mul_linear_apply] }, left_inv := λ f, begin apply (pi.basis_fun R m).ext, intro j, ext i, simp only [pi.basis_fun_apply, matrix.vec_mul_std_basis, matrix.vec_mul_linear_apply] end, map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] }, map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply, ring_hom.id_apply] } } /-- A `matrix m n R` is linearly equivalent over `Rᵐᵒᵖ` to a linear map `(m → R) →ₗ[R] (n → R)`, by having matrices act by right multiplication. -/ abbreviation matrix.to_linear_map_right' : matrix m n R ≃ₗ[Rᵐᵒᵖ] ((m → R) →ₗ[R] (n → R)) := linear_map.to_matrix_right'.symm @[simp] lemma matrix.to_linear_map_right'_apply (M : matrix m n R) (v : m → R) : matrix.to_linear_map_right' M v = M.vec_mul v := rfl @[simp] lemma matrix.to_linear_map_right'_mul [fintype l] [decidable_eq l] (M : matrix l m R) (N : matrix m n R) : matrix.to_linear_map_right' (M ⬝ N) = (matrix.to_linear_map_right' N).comp (matrix.to_linear_map_right' M) := linear_map.ext $ λ x, (vec_mul_vec_mul _ M N).symm lemma matrix.to_linear_map_right'_mul_apply [fintype l] [decidable_eq l] (M : matrix l m R) (N : matrix m n R) (x) : matrix.to_linear_map_right' (M ⬝ N) x = (matrix.to_linear_map_right' N (matrix.to_linear_map_right' M x)) := (vec_mul_vec_mul _ M N).symm @[simp] lemma matrix.to_linear_map_right'_one : matrix.to_linear_map_right' (1 : matrix m m R) = id := by { ext, simp [linear_map.one_apply, std_basis_apply] } /-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `n → A` and `m → A` corresponding to `M.vec_mul` and `M'.vec_mul`. -/ @[simps] def matrix.to_linear_equiv_right'_of_inv [fintype n] [decidable_eq n] {M : matrix m n R} {M' : matrix n m R} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : (n → R) ≃ₗ[R] (m → R) := { to_fun := M'.to_linear_map_right', inv_fun := M.to_linear_map_right', left_inv := λ x, by rw [← matrix.to_linear_map_right'_mul_apply, hM'M, matrix.to_linear_map_right'_one, id_apply], right_inv := λ x, by rw [← matrix.to_linear_map_right'_mul_apply, hMM', matrix.to_linear_map_right'_one, id_apply], ..linear_map.to_matrix_right'.symm M' } end to_matrix_right /-! From this point on, we only work with commutative rings, and fail to distinguish between `Rᵐᵒᵖ` and `R`. This should eventually be remedied. -/ section to_matrix' variables {R : Type*} [comm_semiring R] variables {l m n : Type*} /-- `matrix.mul_vec M` is a linear map. -/ @[simps] def matrix.mul_vec_lin [fintype n] (M : matrix m n R) : (n → R) →ₗ[R] (m → R) := { to_fun := M.mul_vec, map_add' := λ v w, funext (λ i, dot_product_add _ _ _), map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) } variables [fintype n] [decidable_eq n] lemma matrix.mul_vec_std_basis (M : matrix m n R) (i j) : M.mul_vec (std_basis R (λ _, R) j 1) i = M i j := (congr_fun (matrix.mul_vec_single _ _ (1 : R)) i).trans $ mul_one _ @[simp] lemma matrix.mul_vec_std_basis_apply (M : matrix m n R) (j) : M.mul_vec (std_basis R (λ _, R) j 1) = Mᵀ j := funext $ λ i, matrix.mul_vec_std_basis M i j /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := λ f, of (λ i j, f (std_basis R (λ _, R) j 1) i), inv_fun := matrix.mul_vec_lin, right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply, of_apply] }, left_inv := λ f, begin apply (pi.basis_fun R n).ext, intro j, ext i, simp only [pi.basis_fun_apply, matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply, of_apply] end, map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply, of_apply] }, map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply, ring_hom.id_apply, of_apply] } } /-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/ def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) := linear_map.to_matrix'.symm @[simp] lemma linear_map.to_matrix'_symm : (linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' := rfl @[simp] lemma matrix.to_lin'_symm : (matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' := rfl @[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) : linear_map.to_matrix' (matrix.to_lin' M) = M := linear_map.to_matrix'.apply_symm_apply M @[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) : matrix.to_lin' (linear_map.to_matrix' f) = f := matrix.to_lin'.apply_symm_apply f @[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) : linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i := begin simp only [linear_map.to_matrix', linear_equiv.coe_mk, of_apply], congr, ext j', split_ifs with h, { rw [h, std_basis_same] }, apply std_basis_ne _ _ _ _ h end @[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) : matrix.to_lin' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin'_one : matrix.to_lin' (1 : matrix n n R) = id := by { ext, simp [linear_map.one_apply, std_basis_apply] } @[simp] lemma linear_map.to_matrix'_id : (linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] } @[simp] lemma matrix.to_lin'_mul [fintype m] [decidable_eq m] (M : matrix l m R) (N : matrix m n R) : matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) := linear_map.ext $ λ x, (mul_vec_mul_vec _ _ _).symm /-- Shortcut lemma for `matrix.to_lin'_mul` and `linear_map.comp_apply` -/ lemma matrix.to_lin'_mul_apply [fintype m] [decidable_eq m] (M : matrix l m R) (N : matrix m n R) (x) : matrix.to_lin' (M ⬝ N) x = (matrix.to_lin' M (matrix.to_lin' N x)) := by rw [matrix.to_lin'_mul, linear_map.comp_apply] lemma linear_map.to_matrix'_comp [fintype l] [decidable_eq l] (f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin', by rw [this, linear_map.to_matrix'_to_lin'], by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix'] lemma linear_map.to_matrix'_mul [fintype m] [decidable_eq m] (f g : (m → R) →ₗ[R] (m → R)) : (f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' := linear_map.to_matrix'_comp f g @[simp] lemma linear_map.to_matrix'_algebra_map (x : R) : linear_map.to_matrix' (algebra_map R (module.End R (n → R)) x) = scalar n x := by simp [module.algebra_map_End_eq_smul_id] lemma matrix.ker_to_lin'_eq_bot_iff {M : matrix n n R} : M.to_lin'.ker = ⊥ ↔ ∀ v, M.mul_vec v = 0 → v = 0 := by simp only [submodule.eq_bot_iff, linear_map.mem_ker, matrix.to_lin'_apply] lemma matrix.range_to_lin' (M : matrix m n R) : M.to_lin'.range = span R (range Mᵀ) := by simp_rw [range_eq_map, ←supr_range_std_basis, map_supr, range_eq_map, ←ideal.span_singleton_one, ideal.span, submodule.map_span, image_image, image_singleton, matrix.to_lin'_apply, M.mul_vec_std_basis_apply, supr_span, range_eq_Union] /-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `m → A` and `n → A` corresponding to `M.mul_vec` and `M'.mul_vec`. -/ @[simps] def matrix.to_lin'_of_inv [fintype m] [decidable_eq m] {M : matrix m n R} {M' : matrix n m R} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : (m → R) ≃ₗ[R] (n → R) := { to_fun := matrix.to_lin' M', inv_fun := M.to_lin', left_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hMM', matrix.to_lin'_one, id_apply], right_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hM'M, matrix.to_lin'_one, id_apply], .. matrix.to_lin' M' } /-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `matrix n n R`. -/ def linear_map.to_matrix_alg_equiv' : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv linear_map.to_matrix' linear_map.to_matrix'_mul linear_map.to_matrix'_algebra_map /-- A `matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/ def matrix.to_lin_alg_equiv' : matrix n n R ≃ₐ[R] ((n → R) →ₗ[R] (n → R)) := linear_map.to_matrix_alg_equiv'.symm @[simp] lemma linear_map.to_matrix_alg_equiv'_symm : (linear_map.to_matrix_alg_equiv'.symm : matrix n n R ≃ₐ[R] _) = matrix.to_lin_alg_equiv' := rfl @[simp] lemma matrix.to_lin_alg_equiv'_symm : (matrix.to_lin_alg_equiv'.symm : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] _) = linear_map.to_matrix_alg_equiv' := rfl @[simp] lemma linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv' (M : matrix n n R) : linear_map.to_matrix_alg_equiv' (matrix.to_lin_alg_equiv' M) = M := linear_map.to_matrix_alg_equiv'.apply_symm_apply M @[simp] lemma matrix.to_lin_alg_equiv'_to_matrix_alg_equiv' (f : (n → R) →ₗ[R] (n → R)) : matrix.to_lin_alg_equiv' (linear_map.to_matrix_alg_equiv' f) = f := matrix.to_lin_alg_equiv'.apply_symm_apply f @[simp] lemma linear_map.to_matrix_alg_equiv'_apply (f : (n → R) →ₗ[R] (n → R)) (i j) : linear_map.to_matrix_alg_equiv' f i j = f (λ j', if j' = j then 1 else 0) i := by simp [linear_map.to_matrix_alg_equiv'] @[simp] lemma matrix.to_lin_alg_equiv'_apply (M : matrix n n R) (v : n → R) : matrix.to_lin_alg_equiv' M v = M.mul_vec v := rfl @[simp] lemma matrix.to_lin_alg_equiv'_one : matrix.to_lin_alg_equiv' (1 : matrix n n R) = id := matrix.to_lin'_one @[simp] lemma linear_map.to_matrix_alg_equiv'_id : (linear_map.to_matrix_alg_equiv' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 := linear_map.to_matrix'_id @[simp] lemma matrix.to_lin_alg_equiv'_mul (M N : matrix n n R) : matrix.to_lin_alg_equiv' (M ⬝ N) = (matrix.to_lin_alg_equiv' M).comp (matrix.to_lin_alg_equiv' N) := matrix.to_lin'_mul _ _ lemma linear_map.to_matrix_alg_equiv'_comp (f g : (n → R) →ₗ[R] (n → R)) : (f.comp g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := linear_map.to_matrix'_comp _ _ lemma linear_map.to_matrix_alg_equiv'_mul (f g : (n → R) →ₗ[R] (n → R)) : (f * g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' := linear_map.to_matrix_alg_equiv'_comp f g lemma matrix.rank_vec_mul_vec {K m n : Type u} [field K] [fintype n] [decidable_eq n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin' ≤ 1 := begin rw [vec_mul_vec_eq, matrix.to_lin'_mul], refine le_trans (rank_comp_le1 _ _) _, refine (rank_le_domain _).trans_eq _, rw [dim_fun', fintype.card_unit, nat.cast_one] end end to_matrix' section to_matrix variables {R : Type*} [comm_semiring R] variables {l m n : Type*} [fintype n] [fintype m] [decidable_eq n] variables {M₁ M₂ : Type*} [add_comm_monoid M₁] [add_comm_monoid M₂] [module R M₁] [module R M₂] variables (v₁ : basis n R M₁) (v₂ : basis m R M₂) /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/ def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R := linear_equiv.trans (linear_equiv.arrow_congr v₁.equiv_fun v₂.equiv_fun) linear_map.to_matrix' /-- `linear_map.to_matrix'` is a particular case of `linear_map.to_matrix`, for the standard basis `pi.basis_fun R n`. -/ lemma linear_map.to_matrix_eq_to_matrix' : linear_map.to_matrix (pi.basis_fun R n) (pi.basis_fun R n) = linear_map.to_matrix' := rfl /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/ def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) := (linear_map.to_matrix v₁ v₂).symm /-- `matrix.to_lin'` is a particular case of `matrix.to_lin`, for the standard basis `pi.basis_fun R n`. -/ lemma matrix.to_lin_eq_to_lin' : matrix.to_lin (pi.basis_fun R n) (pi.basis_fun R m) = matrix.to_lin' := rfl @[simp] lemma linear_map.to_matrix_symm : (linear_map.to_matrix v₁ v₂).symm = matrix.to_lin v₁ v₂ := rfl @[simp] lemma matrix.to_lin_symm : (matrix.to_lin v₁ v₂).symm = linear_map.to_matrix v₁ v₂ := rfl @[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) : matrix.to_lin v₁ v₂ (linear_map.to_matrix v₁ v₂ f) = f := by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) : linear_map.to_matrix v₁ v₂ (matrix.to_lin v₁ v₂ M) = M := by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply] lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i := begin rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply, linear_equiv.arrow_congr_apply, basis.equiv_fun_symm_apply, finset.sum_eq_single j, if_pos rfl, one_smul, basis.equiv_fun_apply], { intros j' _ hj', rw [if_neg hj', zero_smul] }, { intro hj, have := finset.mem_univ j, contradiction } end lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) : linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i := linear_map.to_matrix_apply v₁ v₂ f i j lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) : (linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) := linear_map.to_matrix_transpose_apply v₁ v₂ f j lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) : matrix.to_lin v₁ v₂ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₂ j := show v₂.equiv_fun.symm (matrix.to_lin' M (v₁.repr v)) = _, by rw [matrix.to_lin'_apply, v₂.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) : matrix.to_lin v₁ v₂ M (v₁ i) = ∑ j, M j i • v₂ j := begin rw [matrix.to_lin_apply, finset.sum_congr rfl (λ j hj, _)], rw [basis.repr_self, matrix.mul_vec, dot_product, finset.sum_eq_single i, finsupp.single_eq_same, mul_one], { intros i' _ i'_ne, rw [finsupp.single_eq_of_ne i'_ne.symm, mul_zero] }, { intros, have := finset.mem_univ i, contradiction }, end /-- This will be a special case of `linear_map.to_matrix_id_eq_basis_to_matrix`. -/ lemma linear_map.to_matrix_id : linear_map.to_matrix v₁ v₁ id = 1 := begin ext i j, simp [linear_map.to_matrix_apply, matrix.one_apply, finsupp.single_apply, eq_comm] end lemma linear_map.to_matrix_one : linear_map.to_matrix v₁ v₁ 1 = 1 := linear_map.to_matrix_id v₁ @[simp] lemma matrix.to_lin_one : matrix.to_lin v₁ v₁ 1 = id := by rw [← linear_map.to_matrix_id v₁, matrix.to_lin_to_matrix] theorem linear_map.to_matrix_reindex_range [decidable_eq M₁] [decidable_eq M₂] (f : M₁ →ₗ[R] M₂) (k : m) (i : n) : linear_map.to_matrix v₁.reindex_range v₂.reindex_range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix v₁ v₂ f k i := by simp_rw [linear_map.to_matrix_apply, basis.reindex_range_self, basis.reindex_range_repr] variables {M₃ : Type*} [add_comm_monoid M₃] [module R M₃] (v₃ : basis l R M₃) lemma linear_map.to_matrix_comp [fintype l] [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) : linear_map.to_matrix v₁ v₃ (f.comp g) = linear_map.to_matrix v₂ v₃ f ⬝ linear_map.to_matrix v₁ v₂ g := by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_equiv.arrow_congr_comp _ v₂.equiv_fun, linear_map.to_matrix'_comp] lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix v₁ v₁ (f * g) = linear_map.to_matrix v₁ v₁ f ⬝ linear_map.to_matrix v₁ v₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_comp v₁ v₁ v₁ f g] } @[simp] lemma linear_map.to_matrix_algebra_map (x : R) : linear_map.to_matrix v₁ v₁ (algebra_map R (module.End R M₁) x) = scalar n x := by simp [module.algebra_map_End_eq_smul_id, linear_map.to_matrix_id] lemma linear_map.to_matrix_mul_vec_repr (f : M₁ →ₗ[R] M₂) (x : M₁) : (linear_map.to_matrix v₁ v₂ f).mul_vec (v₁.repr x) = v₂.repr (f x) := by { ext i, rw [← matrix.to_lin'_apply, linear_map.to_matrix, linear_equiv.trans_apply, matrix.to_lin'_to_matrix', linear_equiv.arrow_congr_apply, v₂.equiv_fun_apply], congr, exact v₁.equiv_fun.symm_apply_apply x } @[simp] lemma linear_map.to_matrix_basis_equiv [fintype l] [decidable_eq l] (b : basis l R M₁) (b' : basis l R M₂) : linear_map.to_matrix b' b (b'.equiv b (equiv.refl l) : M₂ →ₗ[R] M₁) = 1 := begin ext i j, simp [linear_map.to_matrix_apply, matrix.one_apply, finsupp.single_apply, eq_comm], end lemma matrix.to_lin_mul [fintype l] [decidable_eq m] (A : matrix l m R) (B : matrix m n R) : matrix.to_lin v₁ v₃ (A ⬝ B) = (matrix.to_lin v₂ v₃ A).comp (matrix.to_lin v₁ v₂ B) := begin apply (linear_map.to_matrix v₁ v₃).injective, haveI : decidable_eq l := λ _ _, classical.prop_decidable _, rw linear_map.to_matrix_comp v₁ v₂ v₃, repeat { rw linear_map.to_matrix_to_lin }, end /-- Shortcut lemma for `matrix.to_lin_mul` and `linear_map.comp_apply`. -/ lemma matrix.to_lin_mul_apply [fintype l] [decidable_eq m] (A : matrix l m R) (B : matrix m n R) (x) : matrix.to_lin v₁ v₃ (A ⬝ B) x = (matrix.to_lin v₂ v₃ A) (matrix.to_lin v₁ v₂ B x) := by rw [matrix.to_lin_mul v₁ v₂, linear_map.comp_apply] /-- If `M` and `M` are each other's inverse matrices, `matrix.to_lin M` and `matrix.to_lin M'` form a linear equivalence. -/ @[simps] def matrix.to_lin_of_inv [decidable_eq m] {M : matrix m n R} {M' : matrix n m R} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : M₁ ≃ₗ[R] M₂ := { to_fun := matrix.to_lin v₁ v₂ M, inv_fun := matrix.to_lin v₂ v₁ M', left_inv := λ x, by rw [← matrix.to_lin_mul_apply, hM'M, matrix.to_lin_one, id_apply], right_inv := λ x, by rw [← matrix.to_lin_mul_apply, hMM', matrix.to_lin_one, id_apply], .. matrix.to_lin v₁ v₂ M } /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between linear maps `M₁ →ₗ M₁` and square matrices over `R` indexed by the basis. -/ def linear_map.to_matrix_alg_equiv : (M₁ →ₗ[R] M₁) ≃ₐ[R] matrix n n R := alg_equiv.of_linear_equiv (linear_map.to_matrix v₁ v₁) (linear_map.to_matrix_mul v₁) (linear_map.to_matrix_algebra_map v₁) /-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra equivalence between square matrices over `R` indexed by the basis and linear maps `M₁ →ₗ M₁`. -/ def matrix.to_lin_alg_equiv : matrix n n R ≃ₐ[R] (M₁ →ₗ[R] M₁) := (linear_map.to_matrix_alg_equiv v₁).symm @[simp] lemma linear_map.to_matrix_alg_equiv_symm : (linear_map.to_matrix_alg_equiv v₁).symm = matrix.to_lin_alg_equiv v₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_symm : (matrix.to_lin_alg_equiv v₁).symm = linear_map.to_matrix_alg_equiv v₁ := rfl @[simp] lemma matrix.to_lin_alg_equiv_to_matrix_alg_equiv (f : M₁ →ₗ[R] M₁) : matrix.to_lin_alg_equiv v₁ (linear_map.to_matrix_alg_equiv v₁ f) = f := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.apply_symm_apply] @[simp] lemma linear_map.to_matrix_alg_equiv_to_lin_alg_equiv (M : matrix n n R) : linear_map.to_matrix_alg_equiv v₁ (matrix.to_lin_alg_equiv v₁ M) = M := by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.symm_apply_apply] lemma linear_map.to_matrix_alg_equiv_apply (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_apply] lemma linear_map.to_matrix_alg_equiv_transpose_apply (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) := funext $ λ i, f.to_matrix_apply _ _ i j lemma linear_map.to_matrix_alg_equiv_apply' (f : M₁ →ₗ[R] M₁) (i j : n) : linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i := linear_map.to_matrix_alg_equiv_apply v₁ f i j lemma linear_map.to_matrix_alg_equiv_transpose_apply' (f : M₁ →ₗ[R] M₁) (j : n) : (linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) := linear_map.to_matrix_alg_equiv_transpose_apply v₁ f j lemma matrix.to_lin_alg_equiv_apply (M : matrix n n R) (v : M₁) : matrix.to_lin_alg_equiv v₁ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₁ j := show v₁.equiv_fun.symm (matrix.to_lin_alg_equiv' M (v₁.repr v)) = _, by rw [matrix.to_lin_alg_equiv'_apply, v₁.equiv_fun_symm_apply] @[simp] lemma matrix.to_lin_alg_equiv_self (M : matrix n n R) (i : n) : matrix.to_lin_alg_equiv v₁ M (v₁ i) = ∑ j, M j i • v₁ j := matrix.to_lin_self _ _ _ _ lemma linear_map.to_matrix_alg_equiv_id : linear_map.to_matrix_alg_equiv v₁ id = 1 := by simp_rw [linear_map.to_matrix_alg_equiv, alg_equiv.of_linear_equiv_apply, linear_map.to_matrix_id] @[simp] lemma matrix.to_lin_alg_equiv_one : matrix.to_lin_alg_equiv v₁ 1 = id := by rw [← linear_map.to_matrix_alg_equiv_id v₁, matrix.to_lin_alg_equiv_to_matrix_alg_equiv] theorem linear_map.to_matrix_alg_equiv_reindex_range [decidable_eq M₁] (f : M₁ →ₗ[R] M₁) (k i : n) : linear_map.to_matrix_alg_equiv v₁.reindex_range f ⟨v₁ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_map.to_matrix_alg_equiv v₁ f k i := by simp_rw [linear_map.to_matrix_alg_equiv_apply, basis.reindex_range_self, basis.reindex_range_repr] lemma linear_map.to_matrix_alg_equiv_comp (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv v₁ (f.comp g) = linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g := by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_comp v₁ v₁ v₁ f g] lemma linear_map.to_matrix_alg_equiv_mul (f g : M₁ →ₗ[R] M₁) : linear_map.to_matrix_alg_equiv v₁ (f * g) = linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g := by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl, linear_map.to_matrix_alg_equiv_comp v₁ f g] } lemma matrix.to_lin_alg_equiv_mul (A B : matrix n n R) : matrix.to_lin_alg_equiv v₁ (A ⬝ B) = (matrix.to_lin_alg_equiv v₁ A).comp (matrix.to_lin_alg_equiv v₁ B) := by convert matrix.to_lin_mul v₁ v₁ v₁ A B @[simp] lemma matrix.to_lin_fin_two_prod_apply (a b c d : R) (x : R × R) : matrix.to_lin (basis.fin_two_prod R) (basis.fin_two_prod R) !![a, b; c, d] x = (a * x.fst + b * x.snd, c * x.fst + d * x.snd) := by simp [matrix.to_lin_apply, matrix.mul_vec, matrix.dot_product] lemma matrix.to_lin_fin_two_prod (a b c d : R) : matrix.to_lin (basis.fin_two_prod R) (basis.fin_two_prod R) !![a, b; c, d] = (a • linear_map.fst R R R + b • linear_map.snd R R R).prod (c • linear_map.fst R R R + d • linear_map.snd R R R) := linear_map.ext $ matrix.to_lin_fin_two_prod_apply _ _ _ _ @[simp] lemma to_matrix_distrib_mul_action_to_linear_map (x : R) : linear_map.to_matrix v₁ v₁ (distrib_mul_action.to_linear_map R M₁ x) = matrix.diagonal (λ _, x) := begin ext, rw [linear_map.to_matrix_apply, distrib_mul_action.to_linear_map_apply, linear_equiv.map_smul, basis.repr_self, finsupp.smul_single_one, finsupp.single_eq_pi_single, matrix.diagonal, pi.single_apply], end end to_matrix namespace algebra section lmul variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T] variables {m n : Type*} [fintype m] [decidable_eq m] [decidable_eq n] variables (b : basis m R S) (c : basis n S T) open algebra lemma to_matrix_lmul' (x : S) (i j) : linear_map.to_matrix b b (lmul R S x) i j = b.repr (x * b j) i := by simp only [linear_map.to_matrix_apply', coe_lmul_eq_mul, linear_map.mul_apply'] @[simp] lemma to_matrix_lsmul (x : R) : linear_map.to_matrix b b (algebra.lsmul R S x) = matrix.diagonal (λ _, x) := to_matrix_distrib_mul_action_to_linear_map b x /-- `left_mul_matrix b x` is the matrix corresponding to the linear map `λ y, x * y`. `left_mul_matrix_eq_repr_mul` gives a formula for the entries of `left_mul_matrix`. This definition is useful for doing (more) explicit computations with `linear_map.mul_left`, such as the trace form or norm map for algebras. -/ noncomputable def left_mul_matrix : S →ₐ[R] matrix m m R := { to_fun := λ x, linear_map.to_matrix b b (algebra.lmul R S x), map_zero' := by rw [alg_hom.map_zero, linear_equiv.map_zero], map_one' := by rw [alg_hom.map_one, linear_map.to_matrix_one], map_add' := λ x y, by rw [alg_hom.map_add, linear_equiv.map_add], map_mul' := λ x y, by rw [alg_hom.map_mul, linear_map.to_matrix_mul, matrix.mul_eq_mul], commutes' := λ r, by { ext, rw [lmul_algebra_map, to_matrix_lsmul, algebra_map_eq_diagonal, pi.algebra_map_def, algebra.id.map_eq_self] } } lemma left_mul_matrix_apply (x : S) : left_mul_matrix b x = linear_map.to_matrix b b (lmul R S x) := rfl lemma left_mul_matrix_eq_repr_mul (x : S) (i j) : left_mul_matrix b x i j = b.repr (x * b j) i := -- This is defeq to just `to_matrix_lmul' b x i j`, -- but the unfolding goes a lot faster with this explicit `rw`. by rw [left_mul_matrix_apply, to_matrix_lmul' b x i j] lemma left_mul_matrix_mul_vec_repr (x y : S) : (left_mul_matrix b x).mul_vec (b.repr y) = b.repr (x * y) := (linear_map.mul_left R x).to_matrix_mul_vec_repr b b y @[simp] lemma to_matrix_lmul_eq (x : S) : linear_map.to_matrix b b (linear_map.mul_left R x) = left_mul_matrix b x := rfl lemma left_mul_matrix_injective : function.injective (left_mul_matrix b) := λ x x' h, calc x = algebra.lmul R S x 1 : (mul_one x).symm ... = algebra.lmul R S x' 1 : by rw (linear_map.to_matrix b b).injective h ... = x' : mul_one x' variable [fintype n] lemma smul_left_mul_matrix (x) (ik jk) : left_mul_matrix (b.smul c) x ik jk = left_mul_matrix b (left_mul_matrix c x ik.2 jk.2) ik.1 jk.1 := by simp only [left_mul_matrix_apply, linear_map.to_matrix_apply, mul_comm, basis.smul_apply, basis.smul_repr, finsupp.smul_apply, id.smul_eq_mul, linear_equiv.map_smul, mul_smul_comm, coe_lmul_eq_mul, linear_map.mul_apply'] lemma smul_left_mul_matrix_algebra_map (x : S) : left_mul_matrix (b.smul c) (algebra_map _ _ x) = block_diagonal (λ k, left_mul_matrix b x) := begin ext ⟨i, k⟩ ⟨j, k'⟩, rw [smul_left_mul_matrix, alg_hom.commutes, block_diagonal_apply, algebra_map_matrix_apply], split_ifs with h; simp [h], end lemma smul_left_mul_matrix_algebra_map_eq (x : S) (i j k) : left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k) = left_mul_matrix b x i j := by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_eq] lemma smul_left_mul_matrix_algebra_map_ne (x : S) (i j) {k k'} (h : k ≠ k') : left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k') = 0 := by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_ne _ _ _ h] end lmul end algebra namespace linear_map section finite_dimensional open_locale classical variables {K : Type*} [field K] variables {V : Type*} [add_comm_group V] [module K V] [finite_dimensional K V] variables {W : Type*} [add_comm_group W] [module K W] [finite_dimensional K W] instance finite_dimensional : finite_dimensional K (V →ₗ[K] W) := linear_equiv.finite_dimensional (linear_map.to_matrix (basis.of_vector_space K V) (basis.of_vector_space K W)).symm section variables {A : Type*} [ring A] [algebra K A] [module A V] [is_scalar_tower K A V] [module A W] [is_scalar_tower K A W] /-- Linear maps over a `k`-algebra are finite dimensional (over `k`) if both the source and target are, since they form a subspace of all `k`-linear maps. -/ instance finite_dimensional' : finite_dimensional K (V →ₗ[A] W) := finite_dimensional.of_injective (restrict_scalars_linear_map K A V W) (restrict_scalars_injective _) end /-- The dimension of the space of linear transformations is the product of the dimensions of the domain and codomain. -/ @[simp] lemma finrank_linear_map : finite_dimensional.finrank K (V →ₗ[K] W) = (finite_dimensional.finrank K V) * (finite_dimensional.finrank K W) := begin let hbV := basis.of_vector_space K V, let hbW := basis.of_vector_space K W, rw [linear_equiv.finrank_eq (linear_map.to_matrix hbV hbW), matrix.finrank_matrix, finite_dimensional.finrank_eq_card_basis hbV, finite_dimensional.finrank_eq_card_basis hbW, mul_comm], end end finite_dimensional end linear_map section variables {R : Type v} [comm_ring R] {n : Type*} [decidable_eq n] variables {M M₁ M₂ : Type*} [add_comm_group M] [module R M] variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the algebra structures. -/ def alg_equiv_matrix' [fintype n] : module.End R (n → R) ≃ₐ[R] matrix n n R := { map_mul' := linear_map.to_matrix'_comp, map_add' := linear_map.to_matrix'.map_add, commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1, rw ←linear_map.to_matrix'_id, refl, apply_instance }, ..linear_map.to_matrix' } /-- A linear equivalence of two modules induces an equivalence of algebras of their endomorphisms. -/ def linear_equiv.alg_conj (e : M₁ ≃ₗ[R] M₂) : module.End R M₁ ≃ₐ[R] module.End R M₂ := { map_mul' := λ f g, by apply e.arrow_congr_comp, map_add' := e.conj.map_add, commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id, rw [linear_equiv.map_smul, linear_equiv.conj_id], }, ..e.conj } /-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to square matrices. -/ def alg_equiv_matrix [fintype n] (h : basis n R M) : module.End R M ≃ₐ[R] matrix n n R := h.equiv_fun.alg_conj.trans alg_equiv_matrix' end
b0cdeb4765b1281f922a77a2700293db5440b67b
96e0c08045ccd89f1e6556c1437c2ba0f560218b
/src/main.lean
183231d4bd743d03a0c8e770491b38ed73eb829c
[]
no_license
JasonKYi/bilinear_sesquilinear_forms
8fc78ea6716cc4b884c9ff7e27ddaa77bbd1f3f0
d54ff4537426e180473c8091375df2e3e528693d
refs/heads/master
1,678,081,159,270
1,613,904,502,000
1,613,904,502,000
329,987,442
0
0
null
null
null
null
UTF-8
Lean
false
false
17,418
lean
import linear_algebra.bilinear_form import algebra.invertible import annihilator -- import linear_algebra.direct_sum_module open_locale classical universes u v w namespace bilin_form variables {M : Type u} {R : Type v} [add_comm_group M] [ring R] [module R M] /-- The perpendicular submodule of a submodule `N` is the set of elements all of which are orthogonal to all elements of `N`. -/ def ortho (B : bilin_form R M) (N : submodule R M) : submodule R M := { carrier := { m | ∀ n ∈ N, is_ortho B m n }, zero_mem' := λ x _, ortho_zero x, add_mem' := λ x y hx hy n hn, by rw [is_ortho, add_left, show B x n = 0, by exact hx n hn, show B y n = 0, by exact hy n hn, zero_add], smul_mem' := λ c x hx n hn, by rw [is_ortho, smul_left, show B x n = 0, by exact hx n hn, mul_zero] } /-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only if for all `i ≠ j`, `B (v i) (v j) = 0`. -/ def is_ortho' {n : Type w} (B : bilin_form R M) (v : n → M) : Prop := ∀ i j : n, i ≠ j → B (v j) (v i) = 0 /-- The restriction of a bilinear form on a submodule. -/ def restrict (B : bilin_form R M) (W : submodule R M) : bilin_form R W := { bilin := λ a b, B a.1 b.1, bilin_add_left := by simp, bilin_smul_left := by simp, bilin_add_right := by simp, bilin_smul_right := by simp }. @[simp] lemma restrict_def (B : bilin_form R M) (W : submodule R M) (x y : W) : B.restrict W x y = B x.1 y.1 := rfl lemma restrict_sym (B : bilin_form R M) (hB : sym_bilin_form.is_sym B) (W : submodule R M) : sym_bilin_form.is_sym $ B.restrict W := λ x y, hB x.1 y.1 end bilin_form /-- `std_basis` is the standard basis for vectors. -/ noncomputable def std_basis {R : Type v} [ring R] {n : Type w} (i : n) : n → R := λ j, if j = i then 1 else 0 namespace std_basis variables {R : Type v} [ring R] {n : Type w} lemma eq_update (m : n) : std_basis m = function.update 0 m (1 : R) := by { ext, rw function.update_apply, refl } lemma linear_map.eq_std_basis (m : n) : (std_basis m : n → R) = linear_map.std_basis R (λ _, R) m 1 := by { rw linear_map.std_basis_apply, exact eq_update m } @[simp] lemma neq_eq_zero {i j : n} (h : i ≠ j) : std_basis i j = (0 : R) := if_neg h.symm @[simp] lemma eq_eq_one {i j : n} (h : i = j) : std_basis i j = (1 : R) := if_pos h.symm lemma is_basis [fintype n] : @is_basis n R (n → R) std_basis _ _ _ := begin convert pi.is_basis_fun R n, ext1 m, exact linear_map.eq_std_basis m, end lemma dot_product_eq_val (v : n → R) (i : n) [fintype n]: v i = matrix.dot_product v (std_basis i) := begin rw [matrix.dot_product, finset.sum_eq_single i, eq_eq_one rfl, mul_one], exact λ _ _ hb, by rw [neq_eq_zero hb.symm, mul_zero], exact λ hi, false.elim (hi $ finset.mem_univ _) end end std_basis namespace bilin_form variables {M : Type u} {R : Type v} /-- A nondegenerate bilinear form is a bilinear form such that the only element that is orthogonal to every other element is `0`. -/ def nondegenerate [add_comm_group M] [ring R] [module R M] (B : bilin_form R M) := ∀ m : M, (∀ n : M, B m n = 0) → m = 0 variables {n : Type w} [fintype n] variables [add_comm_group M] [comm_ring R] [module R M] section matrix lemma matrix.to_lin'_apply' (A : matrix n n R) (v w : n → R) : (matrix.to_bilin' A) v w = matrix.dot_product v (A.mul_vec w) := begin simp_rw [matrix.to_bilin'_apply, matrix.dot_product, matrix.mul_vec, matrix.dot_product], refine finset.sum_congr rfl (λ _ _, _), rw finset.mul_sum, refine finset.sum_congr rfl (λ _ _, _), rw ← mul_assoc, end lemma matrix.dot_product_eq_zero (v : n → R) (h : ∀ w, matrix.dot_product v w = 0) : v = 0 := begin refine funext (λ x, _), rw [std_basis.dot_product_eq_val v x, h _], refl, end lemma matrix.dot_product_vec_mul_eq_mul_vec {R : Type u} [ring R] (A : matrix n n R) (v w : n → R) : matrix.dot_product (A.vec_mul v) w = matrix.dot_product v (A.mul_vec w) := begin simp_rw [matrix.dot_product, matrix.vec_mul, matrix.mul_vec, matrix.dot_product, finset.mul_sum, finset.sum_mul, ← mul_assoc], rw [finset.sum_comm] end /-- Let `A` be a symmetric matrix. Then `A` has trivial kernel, that is it is invertible if and only if the induced bilinear form of `A` is nondegenerate. -/ theorem matrix.invertible_iff_nondegenerate (A : matrix n n R) (temp : sym_bilin_form.is_sym A.to_bilin') : A.to_bilin'.nondegenerate ↔ A.to_lin'.ker = ⊥ := begin rw linear_map.ker_eq_bot', split; intro h, { refine λ m hm, h _ (λ x, _), rw [matrix.to_lin'_apply] at hm, rw [temp, matrix.to_lin'_apply', hm], exact matrix.dot_product_zero _ }, { intros m hm, apply h, refine matrix.dot_product_eq_zero _ (λ w, _), have := hm w, rwa [temp, matrix.to_lin'_apply', matrix.dot_product_comm] at this } end -- TODO: -- We would like a necessary and sufficent condition on which A.to_bilin' is -- symmetric so the condition is a prop on matrices not the induced bilinear -- product. end matrix /-- Let `B` be a symmetric, nondegenerate bilinear form on a nontrivial module `M` over the ring `R` with invertible `2`. Then, there exists some `x : M` such that `B x x ≠ 0`. -/ lemma exists_bilin_form_self_neq_zero [htwo : invertible (2 : R)] {B : bilin_form R M} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) (hK : ∃ x : M, x ≠ 0) : ∃ x, B x x ≠ 0 := begin by_contra, push_neg at h, have : ∀ u v : M, 2 * B u v = 0, { intros u v, rw [show 2 * B u v = B u u + B v u + B u v + B v v, by rw [h u, h v, hB₂ v u]; ring, show B u u + B v u + B u v + B v v = B (u + v) (u + v), by simp [← add_assoc], h _] }, have hcon : ∀ u v : M, B u v = 0, { intros u v, rw [show 0 = htwo.inv_of * (2 * B u v), by rw this; ring], simp [← mul_assoc] }, exact let ⟨v, hv⟩ := hK in hv $ hB₁ v (hcon v), end variables {V : Type u} {K : Type v} variables [field K] [add_comm_group V] [vector_space K V] /-- A set of orthogonal vectors `v` with respect to some bilinear form `B` is linearly independent if for all `i`, `B (v i) (v i) ≠ 0`. -/ lemma is_ortho_linear_independent {n : Type w} (B : bilin_form K V) {v : n → V} (hv₁ : B.is_ortho' v) (hv₂ : ∀ i, B (v i) (v i) ≠ 0) : linear_independent K v := begin rw linear_independent_iff', intros s w hs i hi, have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0, { rw [hs, zero_left] }, have hsum : s.sum (λ (j : n), w j * B (v j) (v i)) = s.sum (λ (j : n), if i = j then w j * B (v j) (v i) else 0), { refine finset.sum_congr rfl (λ j hj, _), by_cases (i = j), { rw [if_pos h] }, { rw [if_neg h, hv₁ _ _ h, mul_zero] } }, simp_rw [map_sum_left, smul_left, hsum, finset.sum_ite_eq, if_pos hi, mul_eq_zero] at this, cases this, { assumption }, { exact false.elim (hv₂ i $ this) } end -- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0` lemma span_inf_ortho_eq_bot {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) : submodule.span K ({x} : set V) ⊓ B.ortho (submodule.span K ({x} : set V)) = ⊥ := begin rw ← finset.coe_singleton, refine eq_bot_iff.2 (λ y h, _), rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩, have := h.2 x _, { rw finset.sum_singleton at this ⊢, suffices hμzero : μ x = 0, { rw [hμzero, zero_smul, submodule.mem_bot] }, change B (μ x • x) x = 0 at this, rw [smul_left] at this, exact or.elim (zero_eq_mul.mp this.symm) id (λ hfalse, false.elim $ hx hfalse) }, { rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ } end -- ↓ This lemma only applies in field since we use the inverse lemma span_sup_ortho_eq_top {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) : submodule.span K ({x} : set V) ⊔ B.ortho (submodule.span K ({x} : set V)) = ⊤ := begin refine eq_top_iff.2 (λ y _, _), rw submodule.mem_sup, refine ⟨(B x y * (B x x)⁻¹) • x, _, y - (B x y * (B x x)⁻¹) • x, _, _⟩, { exact submodule.mem_span_singleton.2 ⟨(B x y * (B x x)⁻¹), rfl⟩ }, { intros z hz, rcases submodule.mem_span_singleton.1 hz with ⟨μ, rfl⟩, simp [is_ortho, mul_assoc, inv_mul_cancel hx, hB₂ x] }, { simp } end lemma is_compl_prop [hK : invertible (2 : K)] {B : bilin_form K V} -- temp (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) (hV : ∃ x : V, x ≠ 0) : ∃ W : submodule K V, W ⊓ B.ortho W = ⊥ ∧ W ⊔ B.ortho W = ⊤ := begin rcases exists_bilin_form_self_neq_zero hB₁ hB₂ hV with ⟨x, hx⟩, refine ⟨submodule.span K ({x} : set V), span_inf_ortho_eq_bot hB₁ hB₂ hx, span_sup_ortho_eq_top hB₁ hB₂ hx⟩ end def is_compl_singleton [hK : invertible (2 : K)] {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) : is_compl (submodule.span K ({x} : set V)) (B.ortho (submodule.span K ({x} : set V))) := { inf_le_bot := eq_bot_iff.1 $ span_inf_ortho_eq_bot hB₁ hB₂ hx, top_le_sup := eq_top_iff.1 $ span_sup_ortho_eq_top hB₁ hB₂ hx } /-- The natural isomorphism between a singleton and the quotient by its orthogonal complement. -/ noncomputable def quotient_equiv_of_ortho_singleton [hK : invertible (2 : K)] {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) := submodule.quotient_equiv_of_is_compl _ _ (is_compl_singleton hB₁ hB₂ hx) /-- The natural isomorphism from the product between a singleton and its orthogonal component and the whole space. -/ noncomputable def prod_equiv_of_ortho_singleton [hK : invertible (2 : K)] {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) := submodule.prod_equiv_of_is_compl _ _ (is_compl_singleton hB₁ hB₂ hx) lemma restrict_ortho_singleton_nondegenerate (B : bilin_form K V) (hB₁ : nondegenerate B) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) : nondegenerate $ B.restrict $ B.ortho (submodule.span K ({x} : set V)) := begin refine λ m hm, submodule.coe_eq_zero.1 (hB₁ m.1 (λ n, _)), have : n ∈ submodule.span K ({x} : set V) ⊔ B.ortho (submodule.span K ({x} : set V)) := (span_sup_ortho_eq_top hB₁ hB₂ hx).symm ▸ submodule.mem_top, rcases submodule.mem_sup.1 this with ⟨y, hy, z, hz, rfl⟩, specialize hm ⟨z, hz⟩, rw [restrict_def, subtype.val_eq_coe] at hm, erw [add_right, show B m.1 y = 0, by exact m.2 y hy, hm, add_zero] end /- Let V be a finite dimensional vector space over the field K with the nondegenerate bilinear form B. Then for all m ∈ M, f_m : M → R : n ↦ B m n is a linear functional in the dual space. Furthermore, the map, φ : M → M* : m ↦ f_m is an isomorphism. -/ /-- Given a bilinear form `B`, `to_dual_aux` maps elements `m` of the module `M` to the functional `λ x, B m x` in the dual space. -/ def to_dual_aux (B : bilin_form R M) (m : M) : module.dual R M := { to_fun := λ n, B m n, map_add' := add_right m, map_smul' := λ _ _, by simp only [algebra.id.smul_eq_mul, smul_right] } @[simp] lemma to_dual_aux_def {B : bilin_form R M} {m n : M} : B.to_dual_aux m n = B m n := rfl /-- Given a bilinear form `B` on the modual `M`, `to_dual' B` is the linear map from `M` to its dual such that `to_dual B m` is the functional `λ x, B m x`. -/ def to_dual' (B : bilin_form R M) : M →ₗ[R] module.dual R M := { to_fun := λ m, to_dual_aux B m, map_add' := by { intros, ext, simp }, map_smul' := by { intros, ext, simp } } lemma to_dual'_injective (B : bilin_form R M) (hB : B.nondegenerate) : function.injective (to_dual' B) := B.to_dual'.to_add_monoid_hom.injective_iff.2 (λ a ha, hB _ (linear_map.congr_fun ha)) section finite_dimensional open finite_dimensional variable [finite_dimensional K V] -- In order to show that `to_dual` is a surjective map we used the fact that -- the dimensions of a vector space equal to the dimensions of its dual. -- So rather than working with modules over rings, we work with vecotor spaces lemma to_dual'_bijective (B : bilin_form K V) (hB : B.nondegenerate) : function.bijective (to_dual' B) := begin refine ⟨B.to_dual'_injective hB, _⟩, change function.surjective B.to_dual', refine (linear_map.injective_iff_surjective_of_findim_eq_findim (linear_equiv.findim_eq _)).1 (B.to_dual'_injective hB), have hB := classical.some_spec (exists_is_basis_finite K V), haveI := classical.choice hB.2, exact is_basis.to_dual_equiv _ hB.1 end /-- To dual is the `linear_equiv` with the underlying linear map `to_dual'`. -/ noncomputable def to_dual (B : bilin_form K V) (hB : B.nondegenerate) : V ≃ₗ[K] module.dual K V := { map_smul' := B.to_dual'.map_smul', .. add_equiv.of_bijective B.to_dual'.to_add_monoid_hom (to_dual'_bijective B hB) } -- We start proving that bilinear forms are diagonalisable -- or equivilently there exists a orthogonal basis -- ↓ Move lemma is_basis.trivial (hV : findim K V = 0) : is_basis K (λ x : fin 0, (0 : V)) := begin split, rw linear_independent_iff', intros, exact fin.elim0 i, rw ← findim_top at hV, rw [eq_top_iff, (@findim_eq_zero K V _ _ _ _ _).1 hV], exact bot_le end lemma findim_ortho_span_singleton [hK : invertible (2 : K)] {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) {x : V} (hx : B x x ≠ 0) : findim K V = findim K (B.ortho (submodule.span K ({x} : set V))) + 1 := begin rw [← submodule.findim_quotient_add_findim (submodule.span K ({x} : set V)), findim_span_singleton (show x ≠ 0, by exact λ hx', hx (hx'.symm ▸ zero_left _)), (quotient_equiv_of_ortho_singleton hB₁ hB₂ hx).findim_eq] end /-- Given a nondegenerate symmetric basis `B` on some vector space `V` over the field `K` with invertible `2`, there exists a orthogonal basis. -/ theorem exists_orthogonal_basis [hK : invertible (2 : K)] {B : bilin_form K V} (hB₁ : B.nondegenerate) (hB₂ : sym_bilin_form.is_sym B) : ∃ v : fin (findim K V) → V, B.is_ortho' v ∧ is_basis K v ∧ ∀ i, B (v i) (v i) ≠ 0 := begin tactic.unfreeze_local_instances, induction hd : findim K V with d hi generalizing V, { refine ⟨λ _, 0, λ _ _ _, zero_left _, is_basis.trivial hd, fin.elim0⟩ }, { cases exists_bilin_form_self_neq_zero hB₁ hB₂ _ with x hx, { have hd' := hd, rw findim_ortho_span_singleton hB₁ hB₂ hx at hd, rcases @hi (B.ortho (submodule.span K ({x} : set V))) _ _ _ (B.restrict _) (B.restrict_ortho_singleton_nondegenerate hB₁ hB₂ hx) (B.restrict_sym hB₂ _) (nat.succ.inj hd) with ⟨v', hv₁, hv₂, hv₃⟩, -- We now have a orthogonal basis on the orthogonal space refine ⟨λ i, if h : i ≠ 0 then coe (v' (i.pred h)) else x, λ i j hij, _, _, _⟩, { by_cases hi : i = 0, { subst i, simp only [eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff, dite_not], rw dif_neg hij.symm, exact (v' (j.pred hij.symm)).2 _ (submodule.mem_span_singleton_self x) }, by_cases hj : j = 0, { subst j, simp only [eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff, dite_not], rw [dif_neg hi, hB₂], exact (v' (i.pred hi)).2 _ (submodule.mem_span_singleton_self x) }, { simp_rw [dif_pos hi, dif_pos hj], { rw [hB₂, ← hv₁ (j.pred hj) (i.pred hi) _], refl, simpa using hij.symm } } }, { refine is_basis_of_linear_independent_of_card_eq_findim (B.is_ortho_linear_independent _ _) (by rw [hd', fintype.card_fin]), { intros i j hij, by_cases hi : i = 0, { subst hi, simp only [eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff, dite_not], rw dif_neg hij.symm, exact (v' (j.pred hij.symm)).2 _ (submodule.mem_span_singleton_self x) }, by_cases hj : j = 0, { subst j, simp only [eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff, dite_not], rw [dif_neg hi, hB₂], exact (v' (i.pred hi)).2 _ (submodule.mem_span_singleton_self x) }, { simp_rw [dif_pos hi, dif_pos hj], { rw [hB₂, ← hv₁ (j.pred hj) (i.pred hi) _], refl, simpa using hij.symm } } }, { intro i, by_cases hi : i ≠ 0, { rw dif_pos hi, exact hv₃ (i.pred hi) }, { rw dif_neg hi, exact hx } } }, { intro i, by_cases hi : i ≠ 0, { rw dif_pos hi, exact hv₃ (i.pred hi) }, { rw dif_neg hi, exact hx } } }, suffices : nontrivial V, { rcases nontrivial_iff.1 this with ⟨x, y, hxy⟩, by_cases (x = 0), { exact ⟨y, h ▸ hxy.symm⟩ }, { exact ⟨x, h⟩ } }, apply (@findim_pos_iff K _ _ _ _ _).1, rw hd, exact nat.succ_pos _, apply_instance } end . end finite_dimensional end bilin_form
c3d3715ee234ca2073e19556acee505a15d51f36
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/analysis/normed_space/operator_norm.lean
ccac54a8e0d09a600686bfe37d9135dec3c453c9
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,876
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import linear_algebra.finite_dimensional import analysis.normed_space.riesz_lemma import analysis.asymptotics /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ noncomputable theory open_locale classical variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : nnreal} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := ⟨f, h_add, h_smul⟩ in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 lemma linear_map.bound_of_shell (f : E →ₗ[𝕜] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) (x : E) : ∥f x∥ ≤ C * ∥x∥ := begin by_cases hx : x = 0, { simp [hx] }, rcases rescale_to_shell hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, simpa only [f.map_smul, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ)] using hf (δ • x) leδx δxle end /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `ε`. The nondiscreteness is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [mem_closed_ball, dist_zero_right, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨ε⁻¹ * ∥c∥, mul_pos (inv_pos.2 ε_pos) (lt_trans zero_lt_one hc), _⟩, suffices : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ ε⁻¹ * ∥c∥ * ∥x∥, from f.bound_of_shell ε_pos hc this, intros x hle hlt, refine (hε _ hlt.le).trans _, rwa [mul_assoc, ← div_le_iff' (inv_pos.2 ε_pos), div_eq_mul_inv, inv_inv', one_mul, ← div_le_iff' (zero_lt_one.trans hc)] end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, (div_le_iff hlt).mp ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc }))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : E) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_iff_of_nonneg_of_le (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : nnreal} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_shell {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := f.op_norm_le_bound hC $ (f : E →ₗ[𝕜] F).bound_of_shell ε_pos hc hf lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_0_eq end lemma op_norm_le_of_shell' {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ∥c∥ < 1) (hf : ∀ x, ε * ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_0_eq at hx } }, { rw [← inv_inv' c, normed_field.norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [normed_field.norm_inv, div_eq_mul_inv, inv_inv'] } end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : nnreal → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := exists_ne (0 : E) in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this @[simp] lemma norm_id_field : ∥id 𝕜 𝕜∥ = 1 := norm_id @[simp] lemma norm_id_field' : ∥(1 : 𝕜 →L[𝕜] 𝕜)∥ = 1 := norm_id_field lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, have ha : 0 ≤ a, { apply nonneg_of_mul_nonneg_right, rw ← hf x, apply norm_nonneg, exact norm_pos_iff.mpr hx }, refine le_antisymm_iff.mpr ⟨_, _⟩, { exact continuous_linear_map.op_norm_le_bound f ha (λ y, le_of_eq (hf y)) }, { rw continuous_linear_map.norm_def, apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty, intros c h, rw mem_set_of_eq at h, apply (mul_le_mul_right (norm_pos_iff.mpr hx)).mp, rw ← hf x, exact h.2 x } end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : nnreal} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { refine (hε _).le, rw [f.map_zero, dist_zero_right], exact hx.trans_lt (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxlt, ledx, dinv⟩, rw [← f.map_smul d] at dxlt, have : ∥d • x∥ ≤ 1 := H dxlt.le, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.injective_coe_fn $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : nnreal} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h namespace continuous_linear_map /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- Given `c : c : E →L[𝕜] 𝕜`, `c.smul_rightL` is the continuous linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. -/ def smul_rightL (c : E →L[𝕜] 𝕜) : F →L[𝕜] (E →L[𝕜] F) := (c.smul_rightₗ : F →ₗ[𝕜] (E →L[𝕜] F)).mk_continuous _ (λ f, le_of_eq $ c.norm_smul_right_apply f) @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥c.smul_rightL f∥ = ∥c∥ * ∥f∥ := by simp [continuous_linear_map.smul_rightL, continuous_linear_map.smul_rightₗ] @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥(c.smul_rightL : F →L[𝕜] (E →L[𝕜] F))∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜 F) /-- The linear map obtained by applying a continuous linear map at a given vector. -/ def applyₗ (v : E) : (E →L[𝕜] F) →ₗ[𝕜] F := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } lemma continuous_applyₗ (v : E) : continuous (continuous_linear_map.applyₗ 𝕜 F v) := begin apply (continuous_linear_map.applyₗ 𝕜 F v).continuous_of_bound, intro f, rw mul_comm, exact f.le_op_norm v, end /-- The continuous linear map obtained by applying a continuous linear map at a given vector. -/ def apply (v : E) : (E →L[𝕜] F) →L[𝕜] F := ⟨continuous_linear_map.applyₗ 𝕜 F v, continuous_linear_map.continuous_applyₗ _ _ _⟩ variables {𝕜 F} section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_left 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw algebra.lmul_left_apply, exact norm_mul_le x y}) /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_right 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw [algebra.lmul_right_apply, mul_comm], exact norm_mul_le y x}) /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left_right (vw : 𝕜' × 𝕜') : 𝕜' →L[𝕜] 𝕜' := (lmul_right 𝕜 𝕜' vw.2).comp (lmul_left 𝕜 𝕜' vw.1) @[simp] lemma lmul_left_apply (x y : 𝕜') : lmul_left 𝕜 𝕜' x y = x * y := rfl @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma lmul_left_right_apply (vw : 𝕜' × 𝕜') (x : 𝕜') : lmul_left_right 𝕜 𝕜' vw x = vw.1 * x * vw.2 := rfl end multiplication_linear section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] [normed_space 𝕜' E'] variables [is_scalar_tower 𝕜 𝕜' E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : E' →L[𝕜] F' := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, norm_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' →ₗ[𝕜] F') = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, norm_cast squash] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars section extend_scalars variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] instance has_scalar_extend_scalars : has_scalar 𝕜' (E →L[𝕜] F') := { smul := λ c f, (c • f.to_linear_map).mk_continuous (∥c∥ * ∥f∥) begin assume x, calc ∥c • (f x)∥ = ∥c∥ * ∥f x∥ : norm_smul c _ ... ≤ ∥c∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left (le_op_norm f x) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : (mul_assoc _ _ _).symm end } instance module_extend_scalars : module 𝕜' (E →L[𝕜] F') := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance normed_space_extend_scalars : normed_space 𝕜' (E →L[𝕜] F') := { norm_smul_le := λ c f, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ } /-- When `f` is a continuous linear map taking values in `S`, then `λb, f b • x` is a continuous linear map. -/ def smul_algebra_right (f : E →L[𝕜] 𝕜') (x : F') : E →L[𝕜] F' := { cont := by continuity!, .. f.to_linear_map.smul_algebra_right x } @[simp] theorem smul_algebra_right_apply (f : E →L[𝕜] 𝕜') (x : F') (c : E) : smul_algebra_right f x c = f c • x := rfl end extend_scalars end continuous_linear_map section has_sum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variables {ι R M M₂ : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] [topological_space M] [topological_space M₂] omit 𝕜 /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →L[R] M₂) {x : M} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous alias continuous_linear_map.has_sum ← has_sum.mapL protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : summable (λ b:ι, φ (f b)) := (hf.has_sum.mapL φ).summable alias continuous_linear_map.summable ← summable.mapL /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) := ⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →L[R] M), λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →L[R] M₂).has_sum h⟩ protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃L[R] M₂) : summable (λ b:ι, e (f b)) ↔ summable f := ⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →L[R] M₂).summable⟩ end has_sum namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end variable (𝕜) /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear equivalence from `E` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (submodule.span 𝕜 ({x} : set E)) := of_homothety 𝕜 (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ abbreviation coord (x : E) (h : x ≠ 0) : (submodule.span 𝕜 ({x} : set E)) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (submodule.span 𝕜 ({x} : set E)) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span 𝕜 ({x} : set E)) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₗ[𝕜] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma lmul_left_norm (v : 𝕜') : ∥lmul_left 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_left 𝕜 𝕜' v) (1:𝕜') } end @[simp] lemma lmul_right_norm (v : 𝕜') : ∥lmul_right 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_right 𝕜 𝕜' v) (1:𝕜') } end lemma lmul_left_right_norm_le (vw : 𝕜' × 𝕜') : ∥lmul_left_right 𝕜 𝕜' vw∥ ≤ ∥vw.1∥ * ∥vw.2∥ := by simpa [mul_comm] using op_norm_comp_le (lmul_right 𝕜 𝕜' vw.2) (lmul_left 𝕜 𝕜' vw.1) end continuous_linear_map
07a7aee9efed7251a6ba2518ab107f6894f3bb24
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/rewrite_search/explain.lean
3eb86118bfb108b1e7caf9780ecdaaaede676bba
[ "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
9,769
lean
/- Copyright (c) 2020 Kevin Lacker, Keeley Hoek, Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Keeley Hoek, Scott Morrison -/ import tactic.rewrite_search.types import tactic.converter.interactive -- Required for us to emit more compact `conv` invocations /-! # Tools to extract valid Lean code from a path found by rewrite search. -/ open interactive interactive.types expr tactic namespace tactic.rewrite_search universes u /-- A `dir_pair` is a pair of items designed to be accessed according to `dir`, a "direction" defined in the `expr_lens` library. -/ @[derive inhabited] structure dir_pair (α : Type u) := (l r : α) namespace dir_pair open expr_lens variables {α β : Type} (p : dir_pair α) /-- Get one side of the pair, picking the side according to the direction. -/ def get : dir → α | dir.F := p.l | dir.A := p.r /-- Set one side of the pair, picking the side according to the direction. -/ def set : dir → α → dir_pair α | dir.F v := ⟨v, p.r⟩ | dir.A v := ⟨p.l, v⟩ /-- Convert the pair to a list of its elements. -/ def to_list : list α := [p.l, p.r] /-- Convert the pair to a readable string format. -/ def to_string [has_to_string α] (p : dir_pair α) : string := to_string p.l ++ "-" ++ to_string p.r instance has_to_string [has_to_string α] : has_to_string (dir_pair α) := ⟨to_string⟩ end dir_pair /-- Helper for getting the nth item in a list of rules -/ private meta def nth_rule (rs : list (expr × bool)) (i : ℕ) : expr × bool := (rs.nth i).iget /-- Convert a rule into the string of Lean code used to refer to this rule. -/ private meta def pp_rule (r : expr × bool) : tactic string := do pp ← pp r.1, return $ (if r.2 then "←" else "") ++ to_string pp private meta def how.to_rewrite (rs : list (expr × bool)) : how → option (expr × bool) | h := nth_rule rs h.rule_index /-- Explain a single rewrite using `nth_rewrite`. -/ private meta def explain_using_location (rs : list (expr × bool)) (s : side) : how → tactic (option string) | h := do rule ← pp_rule $ nth_rule rs h.rule_index, return $ some ("nth_rewrite_" ++ s.to_xhs ++ " " ++ to_string h.location ++ " " ++ rule) /-- Explain a list of rewrites using `nth_rewrite`. -/ private meta def using_location.explain_rewrites (rs : list (expr × bool)) (s : side) (steps : list how) : tactic string := do rules ← steps.mmap $ λ h : how, option.to_list <$> explain_using_location rs s h, return $ string.intercalate ",\n " rules.join namespace using_conv /-- `app_addr` represents a tree structure that `conv` tactics use for a rewrite. -/ inductive app_addr | node (children : dir_pair (option app_addr)) : app_addr | rw : list ℕ → app_addr open app_addr private meta def app_addr.to_string : app_addr → string | (node c) := "(node " ++ ((c.to_list.filter_map id).map app_addr.to_string).to_string ++ ")" | (rw rws) := "(rw " ++ rws.to_string ++ ")" /-- A data structure for the result of a splice operation. obstructed: There was more of the addr to be added left, but we hit a rw contained: The added addr was already contained, and did not terminate at an existing rw new: The added addr terminated at an existing rw or we could create a new one for it -/ @[derive inhabited] inductive splice_result | obstructed | contained | new (addr : app_addr) open splice_result private meta def pack_splice_result (s : expr_lens.dir) : splice_result → dir_pair (option app_addr) → splice_result | (new addr) c := new $ app_addr.node $ c.set s (some addr) | sr _ := sr private meta def splice_in_aux (new_rws : list ℕ) : option app_addr → list expr_lens.dir → splice_result | (some $ node _) [] := contained | (some $ node c) (s :: rest) := pack_splice_result s (splice_in_aux (c.get s) rest) c | (some $ rw _) (_ :: _) := obstructed | (some $ rw rws) [] := new $ rw (rws ++ new_rws) | none [] := new $ rw new_rws | none l := splice_in_aux (some $ node ⟨none, none⟩) l open expr_lens private meta def to_congr_form : list expr_lens.dir → tactic (list expr_lens.dir) | [] := return [] | (dir.F :: (dir.A :: rest)) := do r ← to_congr_form rest, return (dir.F :: r) | (dir.A :: rest) := do r ← to_congr_form rest, return (dir.A :: r) | [dir.F] := fail "app list ends in side.L!" | (dir.F :: (dir.F :: _)) := fail "app list has repeated side.L!" /-- Attempt to add new rewrites into the `app_addr` tree. -/ private meta def splice_in (a : option app_addr) (rws : list ℕ) (s : list expr_lens.dir) : tactic splice_result := splice_in_aux rws a <$> to_congr_form s /-- Construct a single `erw` tactic for the given rules. -/ private meta def build_rw_tactic (rs : list (expr × bool)) (hs : list ℕ) : tactic string := do rws ← (hs.map $ nth_rule rs).mmap pp_rule, return $ "erw [" ++ (string.intercalate ", " rws) ++ "]" private meta def explain_tree_aux (rs : list (expr × bool)) : app_addr → tactic (option (list string)) | (app_addr.rw rws) := (λ a, some [a]) <$> build_rw_tactic rs rws | (app_addr.node ⟨func, arg⟩) := do sf ← match func with | none := pure none | some func := explain_tree_aux func end, sa ← match arg with | none := pure none | some arg := explain_tree_aux arg end, return $ match (sf, sa) with | (none, none) := none | (some sf, none) := ["congr"].append sf | (none, some sa) := ["congr", "skip"].append sa | (some sf, some sa) := (["congr"].append sf).append (["skip"].append sf) end /-- Construct a string of Lean code that does a rewrite for the provided tree. -/ private meta def explain_tree (rs : list (expr × bool)) (tree : app_addr) : tactic (list string) := list.join <$> option.to_list <$> explain_tree_aux rs tree /-- Gather all rewrites into trees, then generate a line of code for each tree. The return value has one `conv_x` tactic on each line. -/ private meta def explanation_lines (rs : list (expr × bool)) (s : side) : option app_addr → list how → tactic (list string) | none [] := return [] | (some tree) [] := do tacs ← explain_tree rs tree, return $ if tacs.length = 0 then [] else ["conv_" ++ s.to_xhs ++ " { " ++ string.intercalate ", " tacs ++ " }"] | tree (h :: rest) := do (new_tree, rest_if_fail) ← match h.addr with | (some addr) := do new_tree ← splice_in tree [h.rule_index] addr, return (some new_tree, list.cons h rest) | none := do return (none, rest) end, match new_tree with | some (new new_tree) := explanation_lines new_tree rest | _ := do line ← explanation_lines tree [], lines ← explanation_lines none rest_if_fail, return $ line ++ lines end /-- Explain a list of rewrites using `conv_x` tactics. -/ meta def explain_rewrites (rs : list (expr × bool)) (s : side) (hows : list how) : tactic string := string.intercalate ",\n " <$> explanation_lines rs s none hows end using_conv private meta def explain_rewrites_concisely (steps : list (expr × bool)) (needs_refl : bool) : tactic string := do rules ← string.intercalate ", " <$> steps.mmap pp_rule, return $ "erw [" ++ rules ++ "]" ++ (if needs_refl then ", refl" else "") /-- Fails if we can't just use rewrite. Otherwise, returns 'tt' if we need a `refl` at the end. -/ private meta def check_if_simple_rewrite_succeeds (rewrites : list (expr × bool)) (goal : expr) : tactic bool := lock_tactic_state $ do m ← mk_meta_var goal, set_goals [m], rewrites.mmap' $ λ q, rewrite_target q.1 {symm := q.2, md := semireducible}, (reflexivity reducible >> return ff) <|> (reflexivity >> return tt) /-- Construct a list of rewrites from a proof unit. -/ meta def proof_unit.rewrites (u : proof_unit) (rs : list (expr × bool)) : list (expr × bool) := u.steps.filter_map $ how.to_rewrite rs /-- Construct an explanation string from a proof unit. -/ meta def proof_unit.explain (u : proof_unit) (rs : list (expr × bool)) (explain_using_conv : bool) : tactic string := if explain_using_conv then using_conv.explain_rewrites rs u.side u.steps else using_location.explain_rewrites rs u.side u.steps private meta def explain_proof_full (rs : list (expr × bool)) (explain_using_conv : bool) : list proof_unit → tactic string | [] := return "" | (u :: rest) := do -- Don't use transitivity for the last unit, since it must be redundant. head ← if rest.length = 0 ∨ u.side = side.L then pure [] else (do n ← infer_type u.proof >>= (λ e, prod.snd <$> (match_eq e <|> match_iff e)) >>= pp, pure $ ["transitivity " ++ to_string n]), unit_expl ← u.explain rs explain_using_conv, rest_expl ← explain_proof_full rest, let expls := (head ++ [unit_expl, rest_expl]).filter $ λ t, ¬(t.length = 0), return $ string.intercalate ",\n " expls private meta def explain_proof_concisely (rules : list (expr × bool)) (proof : expr) (l : list proof_unit) : tactic string := do let rws : list (expr × bool) := list.join $ l.map (λ u, do (r, s) ← u.rewrites rules, return (r, if u.side = side.L then s else ¬s)), goal ← infer_type proof, needs_refl ← check_if_simple_rewrite_succeeds rws goal, explain_rewrites_concisely rws needs_refl /-- Trace a human-readable explanation in Lean code of a proof generated by rewrite search. Emit it as "Try this: <code>" with each successive line of code indented. -/ meta def explain_search_result (cfg : config) (rules : list (expr × bool)) (proof : expr) (units : list proof_unit) : tactic unit := if units.empty then trace "Try this: exact rfl" else do explanation ← explain_proof_concisely rules proof units <|> explain_proof_full rules cfg.explain_using_conv units, trace $ "Try this: " ++ explanation end tactic.rewrite_search
320809795508ae686a2ec614575511424593c079
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/wfEqns4.lean
f2104eadab4b76c7848aed20ab9dbc60b7939154
[ "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
985
lean
import Lean open Lean open Lean.Meta def tst (declName : Name) : MetaM Unit := do IO.println (← getUnfoldEqnFor? declName) mutual def f : Nat → α → α → α | 0, a, b => a | n, a, b => g a n b |>.1 def g : α → Nat → α → (α × α) | a, 0, b => (a, b) | a, n, b => (h a b n, a) def h : α → α → Nat → α | a, b, 0 => b | a, b, n+1 => f n a b end termination_by' invImage (fun | PSum.inl ⟨n, _, _⟩ => (n, 2) | PSum.inr <| PSum.inl ⟨_, n, _⟩ => (n, 1) | PSum.inr <| PSum.inr ⟨_, _, n⟩ => (n, 0)) (Prod.lex sizeOfWFRel sizeOfWFRel) decreasing_by simp [invImage, InvImage, Prod.lex, sizeOfWFRel, measure, Nat.lt_wfRel, WellFoundedRelation.rel] first | apply Prod.Lex.left apply Nat.lt_succ_self | apply Prod.Lex.right decide #eval f 5 'a' 'b' #eval tst ``f #check @f._eq_1 #check @f._eq_2 #check @f._unfold #eval tst ``h #check @h._eq_1 #check @h._eq_2 #check @h._unfold
a736cc2bce6c5836d1fc262d036557e21cd9fee5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/set_theory/ordinal/arithmetic.lean
5bfc553e3f012cf79d0b6c75c376e5fba33683ac
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
97,796
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios -/ import set_theory.ordinal.basic import tactic.by_contra /-! # Ordinal arithmetic Ordinals have an addition (corresponding to disjoint union) that turns them into an additive monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns them into a monoid. One can also define correspondingly a subtraction, a division, a successor function, a power function and a logarithm function. We also define limit ordinals and prove the basic induction principle on ordinals separating successor ordinals and limit ordinals, in `limit_rec_on`. ## Main definitions and results * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. * `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`. * `o₁ * o₂` is the lexicographic order on `o₂ × o₁`. * `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the divisibility predicate, and a modulo operation. * `order.succ o = o + 1` is the successor of `o`. * `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`. We also define the power function and the logarithm function on ordinals, and discuss the properties of casts of natural numbers of and of `ω` with respect to these operations. Some properties of the operations are also used to discuss general tools on ordinals: * `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor. * `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. * `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. * `enum_ord`: enumerates an unbounded set of ordinals by the ordinals themselves. * `sup`, `lsub`: the supremum / least strict upper bound of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`. * `bsup`, `blsub`: the supremum / least strict upper bound of a set of ordinals indexed by ordinals less than a given ordinal `o`. Various other basic arithmetic results are given in `principal.lean` instead. -/ noncomputable theory open function cardinal set equiv order open_locale classical cardinal ordinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} namespace ordinal /-! ### Further properties of addition on ordinals -/ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by { rw [←add_one_eq_succ, lift_add, lift_one], refl } instance add_contravariant_class_le : contravariant_class ordinal.{u} ordinal.{u} (+) (≤) := ⟨λ a b c, induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj' e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj' (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_rel_embedding, embedding.coe_fn_mk] using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩, λ a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩⟩ theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ (0 : ordinal) = 1 := zero_add 1 @[simp] theorem succ_one : succ (1 : ordinal) = 2 := rfl theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le_iff] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero] theorem succ_pos (o : ordinal) : 0 < succ o := (ordinal.zero_le o).trans_lt (lt_succ o) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [←add_one_eq_succ, card_add, card_one] theorem nat_cast_succ (n : ℕ) : ↑n.succ = succ (n : ordinal) := rfl theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] theorem lt_one_iff_zero {a : ordinal} : a < 1 ↔ a = 0 := by simpa using @lt_succ_bot_iff _ _ _ a _ _ private theorem add_lt_add_iff_left' (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] instance add_covariant_class_lt : covariant_class ordinal.{u} ordinal.{u} (+) (<) := ⟨λ a b c, (add_lt_add_iff_left' a).2⟩ instance add_contravariant_class_lt : contravariant_class ordinal.{u} ordinal.{u} (+) (<) := ⟨λ a b c, (add_lt_add_iff_left' a).1⟩ instance add_swap_contravariant_class_lt : contravariant_class ordinal.{u} ordinal.{u} (swap (+)) (<) := ⟨λ a b c, lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)⟩ theorem add_le_add_iff_right {a b : ordinal} : ∀ n : ℕ, a + n ≤ b + n ↔ a ≤ b | 0 := by simp | (n+1) := by rw [nat_cast_succ, add_succ, add_succ, succ_le_succ_iff, add_le_add_iff_right] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] /-! ### The zero ordinal -/ @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, mk_ne_zero_iff.2 _ h) (ordinal.zero_le _), rw [← succ_le_iff, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, λ e, by simp only [e, card_zero]⟩ protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_of_nonempty _ instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩ @[simp] theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ordinal.one_ne_zero.symm⟩ instance unique_Iio_one : unique (Iio (1 : ordinal)) := { default := ⟨0, zero_lt_one⟩, uniq := λ a, subtype.ext $ lt_one_iff_zero.1 a.prop } instance : zero_le_one_class ordinal := ⟨zero_lt_one.le⟩ instance unique_out_one : unique (1 : ordinal).out.α := { default := enum (<) 0 (by simp), uniq := λ a, begin rw ←enum_typein (<) a, unfold default, congr, rw ←lt_one_iff_zero, apply typein_lt_self end } theorem one_out_eq (x : (1 : ordinal).out.α) : x = enum (<) 0 (by simp) := unique.eq_default x @[simp] theorem typein_one_out (x : (1 : ordinal).out.α) : typein (<) x = 0 := by rw [one_out_eq x, typein_enum] theorem le_one_iff {a : ordinal} : a ≤ 1 ↔ a = 0 ∨ a = 1 := by simpa using @le_succ_bot_iff _ _ _ a _ theorem add_eq_zero_iff {a b : ordinal} : a + b = 0 ↔ (a = 0 ∧ b = 0) := induction_on a $ λ α r _, induction_on b $ λ β s _, begin simp_rw [←type_sum_lex, type_eq_zero_iff_is_empty], exact is_empty_sum end theorem left_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : a = 0 := (add_eq_zero_iff.1 h).1 theorem right_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : b = 0 := (add_eq_zero_iff.1 h).2 /-! ### The predecessor of an ordinal -/ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal) : ordinal := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_injective $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_succ a else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact (lt_succ a).ne e, λ h, dif_neg h⟩ theorem pred_eq_iff_not_succ' {o} : pred o = o ↔ ∀ a, o ≠ succ a := by simpa using pred_eq_iff_not_succ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm @[simp] theorem pred_zero : pred 0 = 0 := pred_eq_iff_not_succ'.2 $ λ a, (succ_ne_zero a).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o b : ordinal} (h : ¬ ∃ a, o = succ a) : succ b < o ↔ b < o := ⟨(lt_succ b).trans, λ l, lt_of_le_of_ne (succ_le_of_lt l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ_iff] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ a in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-! ### Limit ordinals -/ /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem is_limit.succ_lt {o a : ordinal} (h : is_limit o) : a < o → succ a < o := h.2 a theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ o)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o a : ordinal} (h : is_limit o) : succ a < o ↔ a < o := ⟨(lt_succ a).trans, h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, l.le.trans h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ a)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), λ H a h, begin obtain ⟨a', rfl⟩ := lift_down h.le, rw [←lift_succ, lift_lt], exact H a' (lift_lt.1 h) end⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (ordinal.zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ /-- Main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := lt_wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, lt_wf.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, lt_wf.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, lt_wf.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl instance order_top_out_succ (o : ordinal) : order_top (succ o).out.α := ⟨_, le_enum_succ⟩ theorem enum_succ_eq_top {o : ordinal} : enum (<) o (by { rw type_lt, exact lt_succ o }) = (⊤ : (succ o).out.α) := rfl lemma has_succ_of_type_succ_lt {α} {r : α → α → Prop} [wo : is_well_order α r] (h : ∀ a < type r, succ a < type r) (x : α) : ∃ y, r x y := begin use enum r (succ (typein r x)) (h _ (typein_lt_type r x)), convert (enum_lt_enum (typein_lt_type r x) _).mpr (lt_succ _), rw [enum_typein] end theorem out_no_max_of_succ_lt {o : ordinal} (ho : ∀ a < o, succ a < o) : no_max_order o.out.α := ⟨has_succ_of_type_succ_lt (by rwa type_lt)⟩ lemma bounded_singleton {r : α → α → Prop} [is_well_order α r] (hr : (type r).is_limit) (x) : bounded r {x} := begin refine ⟨enum r (succ (typein r x)) (hr.2 _ (typein_lt_type r x)), _⟩, intros b hb, rw mem_singleton_iff.1 hb, nth_rewrite 0 ←enum_typein r x, rw @enum_lt_enum _ r, apply lt_succ end lemma type_subrel_lt (o : ordinal.{u}) : type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o := begin refine quotient.induction_on o _, rintro ⟨α, r, wo⟩, resetI, apply quotient.sound, constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (enum_iso r).symm end lemma mk_initial_seg (o : ordinal.{u}) : #{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card := by rw [lift_card, ←type_subrel_lt, card_type] /-! ### Normal ordinal functions -/ /-- A normal ordinal function is a strictly increasing function which is order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.strict_mono {f} (H : is_normal f) : strict_mono f := λ a b, limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _)) (λ b IH h, (lt_or_eq_of_le (le_of_lt_succ h)).elim (λ h, (IH h).trans (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 le_rfl _ (l.2 _ h))) theorem is_normal.monotone {f} (H : is_normal f) : monotone f := H.strict_mono.monotone theorem is_normal_iff_strict_mono_limit (f : ordinal → ordinal) : is_normal f ↔ (strict_mono f ∧ ∀ o, is_limit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a) := ⟨λ hf, ⟨hf.strict_mono, λ a ha c, (hf.2 a ha c).2⟩, λ ⟨hs, hl⟩, ⟨λ a, hs (lt_succ a), λ a ha c, ⟨λ hac b hba, ((hs hba).trans_le hac).le, hl a ha c⟩⟩⟩ theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := strict_mono.lt_iff_lt $ H.strict_mono theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.self_le {f} (H : is_normal f) (a) : a ≤ f a := lt_wf.self_le_of_strict_mono H.strict_mono a theorem is_normal.le_set {f o} (H : is_normal f) (p : set ordinal) (p0 : p.nonempty) (b) (H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f a ≤ o := ⟨λ h a pa, (H.le_iff.2 ((H₂ _).1 le_rfl _ pa)).trans h, λ h, begin revert H₂, refine limit_rec_on b (λ H₂, _) (λ S _ H₂, _) (λ S L _ H₂, (H.2 _ L _).2 (λ a h', _)), { cases p0 with x px, have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px), rw this at px, exact h _ px }, { rcases not_ball.1 (mt (H₂ S).2 $ (lt_succ S).not_le) with ⟨a, h₁, h₂⟩, exact (H.le_iff.2 $ succ_le_of_lt $ not_le.1 h₂).trans (h _ h₁) }, { rcases not_ball.1 (mt (H₂ a).2 h'.not_le) with ⟨b, h₁, h₂⟩, exact (H.le_iff.2 $ (not_le.1 h₂).le).trans (h _ h₁) } end⟩ theorem is_normal.le_set' {f o} (H : is_normal f) (p : set α) (p0 : p.nonempty) (g : α → ordinal) (b) (H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, g a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f (g a) ≤ o := by simpa [H₂] using H.le_set (g '' p) (p0.image g) b theorem is_normal.refl : is_normal id := ⟨lt_succ, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (f ∘ g) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) ⟨_, l.pos⟩ g _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ (ordinal.zero_le _).trans_lt $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in (succ_le_of_lt h₂).trans_lt (H.lt_iff.2 h₁)⟩ theorem is_normal.le_iff_eq {f} (H : is_normal f) {a} : f a ≤ a ↔ f a = a := (H.self_le a).le_iff_eq theorem add_le_of_limit {a b c : ordinal} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, (add_le_add_left l.le _).trans h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [←typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le_iff] at this, refine (rel_embedding.of_monotone (λ a, _) (λ a b, _)).ordinal_type_le.trans_lt this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ b), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit alias add_is_limit ← is_limit.add /-! ### Subtraction on ordinals-/ /-- The set in the definition of subtraction is nonempty. -/ theorem sub_nonempty {a b : ordinal} : {o | a ≤ b + o}.nonempty := ⟨a, le_add_left _ _⟩ /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ instance : has_sub ordinal := ⟨λ a b, Inf {o | a ≤ b + o}⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := Inf_mem sub_nonempty theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, (le_add_sub a b).trans (add_le_add_left h _), λ h, cInf_le' h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_rfl) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := (le_add_sub a b).antisymm' begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le_iff, ← lt_sub, e], exact lt_succ c }, { exact (add_le_of_limit l).2 (λ c l, (lt_sub.1 l).le) } end theorem le_sub_of_le {a b c : ordinal} (h : b ≤ a) : c ≤ a - b ↔ b + c ≤ a := by rw [←add_le_add_iff_left b, ordinal.add_sub_cancel_of_le h] theorem sub_lt_of_le {a b c : ordinal} (h : b ≤ a) : a - b < c ↔ a < b + c := lt_iff_lt_of_le_iff_le (le_sub_of_le h) instance : has_exists_add_of_le ordinal := ⟨λ a b h, ⟨_, (ordinal.add_sub_cancel_of_le h).symm⟩⟩ @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← ordinal.le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + ω = ω := begin refine le_antisymm _ (le_add_left _ _), rw [omega, ← lift_one.{0}, ← lift_add, lift_le, ← type_unit, ← type_sum_lex], refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp, priority 990] theorem one_add_of_omega_le {o} (h : ω ≤ o) : 1 + o = o := by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega] /-! ### Multiplication of ordinals-/ /-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on `o₂ × o₁`. -/ instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_prod_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type (prod.lex s r) = type r * type s := rfl private theorem mul_eq_zero' {a b : ordinal} : a * b = 0 ↔ a = 0 ∨ b = 0 := induction_on a $ λ α _ _, induction_on b $ λ β _ _, begin simp_rw [←type_prod_lex, type_eq_zero_iff_is_empty], rw or_comm, exact is_empty_prod end instance : monoid_with_zero ordinal := { zero := 0, mul_zero := λ a, mul_eq_zero'.2 $ or.inr rfl, zero_mul := λ a, mul_eq_zero'.2 $ or.inl rfl, ..ordinal.monoid } instance : no_zero_divisors ordinal := ⟨λ a b, mul_eq_zero'.1⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) instance : left_distrib_class ordinal.{u} := ⟨λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, sum_prod_distrib_apply_left, sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩⟩ theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one a b instance mul_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (*) (≤) := ⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine (rel_embedding.of_monotone (λ a : α × γ, (f a.1, a.2)) (λ a b h, _)).ordinal_type_le, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') }, { exact prod.lex.right _ h' } end⟩ instance mul_swap_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (swap (*)) (≤) := ⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine (rel_embedding.of_monotone (λ a : γ × α, (a.1, f a.2)) (λ a b h, _)).ordinal_type_le, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ h' }, { exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') } end⟩ theorem le_mul_left (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ a * b := by { convert mul_le_mul_left' (one_le_iff_pos.2 hb) a, rw mul_one a } theorem le_mul_right (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ b * a := by { convert mul_le_mul_right' (one_le_iff_pos.2 hb) a, rw one_mul a } private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s] {c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) : false := begin suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [←typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw mul_succ at this, have := ((add_lt_add_iff_left _).2 (typein_lt_type _ a)).trans_le this, refine (rel_embedding.of_monotone (λ a, _) (λ a b, _)).ordinal_type_le.trans_lt this, { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp [e₂, dif_neg e₁, show b₂ ≠ b₁, by cc] }, { simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, (mul_le_mul_left' l.le _).trans h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [ordinal.pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact b0.false.elim }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end theorem smul_eq_mul : ∀ (n : ℕ) (a : ordinal), n • a = a * n | 0 a := by rw [zero_smul, nat.cast_zero, mul_zero] | (n + 1) a := by rw [succ_nsmul', nat.cast_add, mul_add, nat.cast_one, mul_one, smul_eq_mul] /-! ### Division on ordinals -/ /-- The set in the definition of division is nonempty. -/ theorem div_nonempty {a b : ordinal} (h : b ≠ 0) : {o | a < b * succ o}.nonempty := ⟨a, succ_le_iff.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right' (succ_le_of_lt (ordinal.pos_iff_ne_zero.2 h)) (succ a)⟩ /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_div ordinal := ⟨λ a b, if h : b = 0 then 0 else Inf {o | a < b * succ o}⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl lemma div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = Inf {o | a < b * succ o} := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact Inf_mem (div_nonempty h) theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, (lt_mul_succ_div a b0).trans_le (mul_le_mul_left' (succ_le_succ_iff.2 h) _), λ h, by rw div_def a b0; exact cInf_le' h⟩ theorem lt_div {a b c : ordinal} (h : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le h, not_lt] theorem div_pos {b c : ordinal} (h : c ≠ 0) : 0 < b / c ↔ c ≤ b := by simp [lt_div h] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp only [mul_zero, ordinal.zero_le] }, { intros, rw [succ_le_iff, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else (div_le b0).2 $ h.trans_lt $ mul_lt_mul_of_pos_left (lt_succ c) (ordinal.pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 le_rfl theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := begin rw [←ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ (ordinal.zero_le _).trans_lt h], simpa only [succ_zero, mul_one] using h end @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) := begin split; intro h, { by_cases h' : b = 0, { rw [h', add_zero] at h, right, exact ⟨h', h⟩ }, left, rw [←add_sub_cancel a b], apply sub_is_limit h, suffices : a + 0 < a + b, simpa only [add_zero], rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] }, rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero] end theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left' (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) a theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (eq_zero_of_zero_dvd h₁).symm else if b0 : b = 0 then by subst b; exact eq_zero_of_zero_dvd h₂ else (le_of_dvd b0 h₁).antisymm (le_of_dvd a0 h₂) instance : is_antisymm ordinal (∣) := ⟨@dvd_antisymm⟩ /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := ordinal.add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] theorem dvd_of_mod_eq_zero {a b : ordinal} (H : a % b = 0) : b ∣ a := ⟨a / b, by simpa [H] using (div_add_mod a b).symm⟩ theorem mod_eq_zero_of_dvd {a b : ordinal} (H : b ∣ a) : a % b = 0 := begin rcases H with ⟨c, rfl⟩, rcases eq_or_ne b 0 with rfl | hb, { simp }, { simp [mod_def, hb] } end theorem dvd_iff_mod_eq_zero {a b : ordinal} : b ∣ a ↔ a % b = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-! ### Families of ordinals There are two kinds of indexed families that naturally arise when dealing with ordinals: those indexed by some type in the appropriate universe, and those indexed by ordinals less than another. The following API allows one to convert from one kind of family to the other. In many cases, this makes it easy to prove claims about one kind of family via the corresponding claim on the other. -/ /-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a specified well-ordering. -/ def bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) : Π a < type r, α := λ a ha, f (enum r a ha) /-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a well-ordering given by the axiom of choice. -/ def bfamily_of_family {ι : Type u} : (ι → α) → Π a < type (@well_ordering_rel ι), α := bfamily_of_family' well_ordering_rel /-- Converts a family indexed by an `ordinal.{u}` to one indexed by an `Type u` using a specified well-ordering. -/ def family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) : ι → α := λ i, f (typein r i) (by { rw ←ho, exact typein_lt_type r i }) /-- Converts a family indexed by an `ordinal.{u}` to one indexed by a `Type u` using a well-ordering given by the axiom of choice. -/ def family_of_bfamily (o : ordinal) (f : Π a < o, α) : o.out.α → α := family_of_bfamily' (<) (type_lt o) f @[simp] theorem bfamily_of_family'_typein {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) (i) : bfamily_of_family' r f (typein r i) (typein_lt_type r i) = f i := by simp only [bfamily_of_family', enum_typein] @[simp] theorem bfamily_of_family_typein {ι} (f : ι → α) (i) : bfamily_of_family f (typein _ i) (typein_lt_type _ i) = f i := bfamily_of_family'_typein _ f i @[simp] theorem family_of_bfamily'_enum {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) (i hi) : family_of_bfamily' r ho f (enum r i (by rwa ho)) = f i hi := by simp only [family_of_bfamily', typein_enum] @[simp] theorem family_of_bfamily_enum (o : ordinal) (f : Π a < o, α) (i hi) : family_of_bfamily o f (enum (<) i (by { convert hi, exact type_lt _ })) = f i hi := family_of_bfamily'_enum _ (type_lt o) f _ _ /-- The range of a family indexed by ordinals. -/ def brange (o : ordinal) (f : Π a < o, α) : set α := {a | ∃ i hi, f i hi = a} theorem mem_brange {o : ordinal} {f : Π a < o, α} {a} : a ∈ brange o f ↔ ∃ i hi, f i hi = a := iff.rfl theorem mem_brange_self {o} (f : Π a < o, α) (i hi) : f i hi ∈ brange o f := ⟨i, hi, rfl⟩ @[simp] theorem range_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) : range (family_of_bfamily' r ho f) = brange o f := begin refine set.ext (λ a, ⟨_, _⟩), { rintro ⟨b, rfl⟩, apply mem_brange_self }, { rintro ⟨i, hi, rfl⟩, exact ⟨_, family_of_bfamily'_enum _ _ _ _ _⟩ } end @[simp] theorem range_family_of_bfamily {o} (f : Π a < o, α) : range (family_of_bfamily o f) = brange o f := range_family_of_bfamily' _ _ f @[simp] theorem brange_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) : brange _ (bfamily_of_family' r f) = range f := begin refine set.ext (λ a, ⟨_, _⟩), { rintro ⟨i, hi, rfl⟩, apply mem_range_self }, { rintro ⟨b, rfl⟩, exact ⟨_, _, bfamily_of_family'_typein _ _ _⟩ }, end @[simp] theorem brange_bfamily_of_family {ι : Type u} (f : ι → α) : brange _ (bfamily_of_family f) = range f := brange_bfamily_of_family' _ _ @[simp] theorem brange_const {o : ordinal} (ho : o ≠ 0) {c : α} : brange o (λ _ _, c) = {c} := begin rw ←range_family_of_bfamily, exact @set.range_const _ o.out.α (out_nonempty_iff_ne_zero.2 ho) c end theorem comp_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) (g : α → β) : (λ i hi, g (bfamily_of_family' r f i hi)) = bfamily_of_family' r (g ∘ f) := rfl theorem comp_bfamily_of_family {ι : Type u} (f : ι → α) (g : α → β) : (λ i hi, g (bfamily_of_family f i hi)) = bfamily_of_family (g ∘ f) := rfl theorem comp_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) (g : α → β) : g ∘ (family_of_bfamily' r ho f) = family_of_bfamily' r ho (λ i hi, g (f i hi)) := rfl theorem comp_family_of_bfamily {o} (f : Π a < o, α) (g : α → β) : g ∘ (family_of_bfamily o f) = family_of_bfamily o (λ i hi, g (f i hi)) := rfl /-! ### Supremum of a family of ordinals -/ /-- The supremum of a family of ordinals -/ def sup {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal.{max u v} := supr f @[simp] theorem Sup_eq_sup {ι : Type u} (f : ι → ordinal.{max u v}) : Sup (set.range f) = sup f := rfl /-- The range of an indexed ordinal function, whose outputs live in a higher universe than the inputs, is always bounded above. See `ordinal.lsub` for an explicit bound. -/ theorem bdd_above_range {ι : Type u} (f : ι → ordinal.{max u v}) : bdd_above (set.range f) := ⟨(supr (succ ∘ card ∘ f)).ord, begin rintros a ⟨i, rfl⟩, exact le_of_lt (cardinal.lt_ord.2 ((lt_succ _).trans_le (le_csupr (bdd_above_range _) _))) end⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := λ i, le_cSup (bdd_above_range f) (mem_range_self i) theorem sup_le_iff {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := (cSup_le_iff' (bdd_above_range f)).trans (by simp) theorem sup_le {ι} {f : ι → ordinal} {a} : (∀ i, f i ≤ a) → sup f ≤ a := sup_le_iff.2 theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le_iff _ f a) theorem ne_sup_iff_lt_sup {ι} {f : ι → ordinal} : (∀ i, f i ≠ sup f) ↔ ∀ i, f i < sup f := ⟨λ hf _, lt_of_le_of_ne (le_sup _ _) (hf _), λ hf _, ne_of_lt (hf _)⟩ theorem sup_not_succ_of_ne_sup {ι} {f : ι → ordinal} (hf : ∀ i, f i ≠ sup f) {a} (hao : a < sup f) : succ a < sup f := begin by_contra' hoa, exact hao.not_le (sup_le $ λ i, le_of_lt_succ $ (lt_of_le_of_ne (le_sup _ _) (hf i)).trans_le hoa) end @[simp] theorem sup_eq_zero_iff {ι} {f : ι → ordinal} : sup f = 0 ↔ ∀ i, f i = 0 := begin refine ⟨λ h i, _, λ h, le_antisymm (sup_le (λ i, ordinal.le_zero.2 (h i))) (ordinal.zero_le _)⟩, rw [←ordinal.le_zero, ←h], exact le_sup f i end theorem is_normal.sup {f} (H : is_normal f) {ι} (g : ι → ordinal) [nonempty ι] : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le_iff, comp, H.le_set' set.univ set.univ_nonempty g]; simp [sup_le_iff] @[simp] theorem sup_empty {ι} [is_empty ι] (f : ι → ordinal) : sup f = 0 := csupr_of_empty f @[simp] theorem sup_const {ι} [hι : nonempty ι] (o : ordinal) : sup (λ _ : ι, o) = o := csupr_const @[simp] theorem sup_unique {ι} [unique ι] (f : ι → ordinal) : sup f = f default := supr_unique theorem sup_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f ⊆ set.range g) : sup.{u (max v w)} f ≤ sup.{v (max u w)} g := sup_le $ λ i, match h (mem_range_self i) with ⟨j, hj⟩ := hj ▸ le_sup _ _ end theorem sup_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f = set.range g) : sup.{u (max v w)} f = sup.{v (max u w)} g := (sup_le_of_range_subset h.le).antisymm (sup_le_of_range_subset.{v u w} h.ge) lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α) (h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) := (not_bounded_iff _).1 $ λ ⟨x, hx⟩, not_lt_of_le h $ lt_of_le_of_lt (sup_le $ λ y, le_of_lt $ (typein_lt_typein r).2 $ hx _ $ mem_range_self y) (typein_lt_type r x) theorem le_sup_shrink_equiv {s : set ordinal.{u}} (hs : small.{u} s) (a) (ha : a ∈ s) : a ≤ sup.{u u} (λ x, ((@equiv_shrink s hs).symm x).val) := by { convert le_sup.{u u} _ ((@equiv_shrink s hs) ⟨a, ha⟩), rw symm_apply_apply } instance small_Iio (o : ordinal.{u}) : small.{u} (set.Iio o) := let f : o.out.α → set.Iio o := λ x, ⟨typein (<) x, typein_lt_self x⟩ in let hf : surjective f := λ b, ⟨enum (<) b.val (by { rw type_lt, exact b.prop }), subtype.ext (typein_enum _ _)⟩ in small_of_surjective hf instance small_Iic (o : ordinal.{u}) : small.{u} (set.Iic o) := by { rw ←Iio_succ, apply_instance } theorem bdd_above_iff_small {s : set ordinal.{u}} : bdd_above s ↔ small.{u} s := ⟨λ ⟨a, h⟩, small_subset $ show s ⊆ Iic a, from λ x hx, h hx, λ h, ⟨sup.{u u} (λ x, ((@equiv_shrink s h).symm x).val), le_sup_shrink_equiv h⟩⟩ theorem bdd_above_of_small (s : set ordinal.{u}) [h : small.{u} s] : bdd_above s := bdd_above_iff_small.2 h theorem sup_eq_Sup {s : set ordinal.{u}} (hs : small.{u} s) : sup.{u u} (λ x, (@equiv_shrink s hs).symm x) = Sup s := let hs' := bdd_above_iff_small.2 hs in ((cSup_le_iff' hs').2 (le_sup_shrink_equiv hs)).antisymm' (sup_le (λ x, le_cSup hs' (subtype.mem _))) theorem Sup_ord {s : set cardinal.{u}} (hs : bdd_above s) : (Sup s).ord = Sup (ord '' s) := eq_of_forall_ge_iff $ λ a, begin rw [cSup_le_iff' (bdd_above_iff_small.2 (@small_image _ _ _ s (cardinal.bdd_above_iff_small.1 hs))), ord_le, cSup_le_iff' hs], simp [ord_le] end theorem supr_ord {ι} {f : ι → cardinal} (hf : bdd_above (range f)) : (supr f).ord = ⨆ i, (f i).ord := by { unfold supr, convert Sup_ord hf, rw range_comp } private theorem sup_le_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal) : sup (family_of_bfamily' r ho f) ≤ sup (family_of_bfamily' r' ho' f) := sup_le $ λ i, begin cases typein_surj r' (by { rw [ho', ←ho], exact typein_lt_type r i }) with j hj, simp_rw [family_of_bfamily', ←hj], apply le_sup end theorem sup_eq_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o : ordinal.{u}} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal.{max u v}) : sup (family_of_bfamily' r ho f) = sup (family_of_bfamily' r' ho' f) := sup_eq_of_range_eq.{u u v} (by simp) /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is a special case of `sup` over the family provided by `family_of_bfamily`. -/ def bsup (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} := sup (family_of_bfamily o f) @[simp] theorem sup_eq_bsup {o} (f : Π a < o, ordinal) : sup (family_of_bfamily o f) = bsup o f := rfl @[simp] theorem sup_eq_bsup' {o ι} (r : ι → ι → Prop) [is_well_order ι r] (ho : type r = o) (f) : sup (family_of_bfamily' r ho f) = bsup o f := sup_eq_sup r _ ho _ f @[simp] theorem Sup_eq_bsup {o} (f : Π a < o, ordinal) : Sup (brange o f) = bsup o f := by { congr, rw range_family_of_bfamily } @[simp] theorem bsup_eq_sup' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) : bsup _ (bfamily_of_family' r f) = sup f := by simp only [←sup_eq_bsup' r, enum_typein, family_of_bfamily', bfamily_of_family'] theorem bsup_eq_bsup {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r'] (f : ι → ordinal) : bsup _ (bfamily_of_family' r f) = bsup _ (bfamily_of_family' r' f) := by rw [bsup_eq_sup', bsup_eq_sup'] @[simp] theorem bsup_eq_sup {ι} (f : ι → ordinal) : bsup _ (bfamily_of_family f) = sup f := bsup_eq_sup' _ f @[congr] lemma bsup_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) : bsup o₁ f = bsup o₂ (λ a h, f a (h.trans_eq ho.symm)) := by subst ho theorem bsup_le_iff {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := sup_le_iff.trans ⟨λ h i hi, by { rw ←family_of_bfamily_enum o f, exact h _ }, λ h i, h _ _⟩ theorem bsup_le {o : ordinal} {f : Π b < o, ordinal} {a} : (∀ i h, f i h ≤ a) → bsup.{u v} o f ≤ a := bsup_le_iff.2 theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le_iff.1 le_rfl _ _ theorem lt_bsup {o} (f : Π a < o, ordinal) {a} : a < bsup o f ↔ ∃ i hi, a < f i hi := by simpa only [not_forall, not_le] using not_congr (@bsup_le_iff _ f a) theorem is_normal.bsup {f} (H : is_normal f) {o} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, begin resetI, haveI := type_ne_zero_iff_nonempty.1 h, rw [←sup_eq_bsup' r, H.sup, ←sup_eq_bsup' r]; refl end theorem lt_bsup_of_ne_bsup {o : ordinal} {f : Π a < o, ordinal} : (∀ i h, f i h ≠ o.bsup f) ↔ ∀ i h, f i h < o.bsup f := ⟨λ hf _ _, lt_of_le_of_ne (le_bsup _ _ _) (hf _ _), λ hf _ _, ne_of_lt (hf _ _)⟩ theorem bsup_not_succ_of_ne_bsup {o} {f : Π a < o, ordinal} (hf : ∀ {i : ordinal} (h : i < o), f i h ≠ o.bsup f) (a) : a < bsup o f → succ a < bsup o f := by { rw ←sup_eq_bsup at *, exact sup_not_succ_of_ne_sup (λ i, hf _) } @[simp] theorem bsup_eq_zero_iff {o} {f : Π a < o, ordinal} : bsup o f = 0 ↔ ∀ i hi, f i hi = 0 := begin refine ⟨λ h i hi, _, λ h, le_antisymm (bsup_le (λ i hi, ordinal.le_zero.2 (h i hi))) (ordinal.zero_le _)⟩, rw [←ordinal.le_zero, ←h], exact le_bsup f i hi, end theorem lt_bsup_of_limit {o : ordinal} {f : Π a < o, ordinal} (hf : ∀ {a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha') (ho : ∀ a < o, succ a < o) (i h) : f i h < bsup o f := (hf _ _ $ lt_succ i).trans_le (le_bsup f (succ i) $ ho _ h) theorem bsup_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : bsup _ f = f o (lt_succ o) := le_antisymm (bsup_le $ λ i hi, hf _ _ $ le_of_lt_succ hi) (le_bsup _ _ _) @[simp] theorem bsup_zero (f : Π a < (0 : ordinal), ordinal) : bsup 0 f = 0 := bsup_eq_zero_iff.2 (λ i hi, (ordinal.not_lt_zero i hi).elim) theorem bsup_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : bsup o (λ _ _, a) = a := le_antisymm (bsup_le (λ _ _, le_rfl)) (le_bsup _ 0 (ordinal.pos_iff_ne_zero.2 ho)) @[simp] theorem bsup_one (f : Π a < (1 : ordinal), ordinal) : bsup 1 f = f 0 zero_lt_one := by simp_rw [←sup_eq_bsup, sup_unique, family_of_bfamily, family_of_bfamily', typein_one_out] theorem bsup_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : bsup.{u (max v w)} o f ≤ bsup.{v (max u w)} o' g := bsup_le $ λ i hi, begin obtain ⟨j, hj, hj'⟩ := h ⟨i, hi, rfl⟩, rw ←hj', apply le_bsup end theorem bsup_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f = brange o' g) : bsup.{u (max v w)} o f = bsup.{v (max u w)} o' g := (bsup_le_of_brange_subset h.le).antisymm (bsup_le_of_brange_subset.{v u w} h.ge) /-- The least strict upper bound of a family of ordinals. -/ def lsub {ι} (f : ι → ordinal) : ordinal := sup (succ ∘ f) @[simp] theorem sup_eq_lsub {ι} (f : ι → ordinal) : sup (succ ∘ f) = lsub f := rfl theorem lsub_le_iff {ι} {f : ι → ordinal} {a} : lsub f ≤ a ↔ ∀ i, f i < a := by { convert sup_le_iff, simp only [succ_le_iff] } theorem lsub_le {ι} {f : ι → ordinal} {a} : (∀ i, f i < a) → lsub f ≤ a := lsub_le_iff.2 theorem lt_lsub {ι} (f : ι → ordinal) (i) : f i < lsub f := succ_le_iff.1 (le_sup _ i) theorem lt_lsub_iff {ι} {f : ι → ordinal} {a} : a < lsub f ↔ ∃ i, a ≤ f i := by simpa only [not_forall, not_lt, not_le] using not_congr (@lsub_le_iff _ f a) theorem sup_le_lsub {ι} (f : ι → ordinal) : sup f ≤ lsub f := sup_le $ λ i, (lt_lsub f i).le theorem lsub_le_sup_succ {ι} (f : ι → ordinal) : lsub f ≤ succ (sup f) := lsub_le $ λ i, lt_succ_iff.2 (le_sup f i) theorem sup_eq_lsub_or_sup_succ_eq_lsub {ι} (f : ι → ordinal) : sup f = lsub f ∨ succ (sup f) = lsub f := begin cases eq_or_lt_of_le (sup_le_lsub f), { exact or.inl h }, { exact or.inr ((succ_le_of_lt h).antisymm (lsub_le_sup_succ f)) } end theorem sup_succ_le_lsub {ι} (f : ι → ordinal) : succ (sup f) ≤ lsub f ↔ ∃ i, f i = sup f := begin refine ⟨λ h, _, _⟩, { by_contra' hf, exact (succ_le_iff.1 h).ne ((sup_le_lsub f).antisymm (lsub_le (ne_sup_iff_lt_sup.1 hf))) }, rintro ⟨_, hf⟩, rw [succ_le_iff, ←hf], exact lt_lsub _ _ end theorem sup_succ_eq_lsub {ι} (f : ι → ordinal) : succ (sup f) = lsub f ↔ ∃ i, f i = sup f := (lsub_le_sup_succ f).le_iff_eq.symm.trans (sup_succ_le_lsub f) theorem sup_eq_lsub_iff_succ {ι} (f : ι → ordinal) : sup f = lsub f ↔ ∀ a < lsub f, succ a < lsub f := begin refine ⟨λ h, _, λ hf, le_antisymm (sup_le_lsub f) (lsub_le (λ i, _))⟩, { rw ←h, exact λ a, sup_not_succ_of_ne_sup (λ i, (lsub_le_iff.1 (le_of_eq h.symm) i).ne) }, by_contra' hle, have heq := (sup_succ_eq_lsub f).2 ⟨i, le_antisymm (le_sup _ _) hle⟩, have := hf _ (by { rw ←heq, exact lt_succ (sup f) }), rw heq at this, exact this.false end theorem sup_eq_lsub_iff_lt_sup {ι} (f : ι → ordinal) : sup f = lsub f ↔ ∀ i, f i < sup f := ⟨λ h i, (by { rw h, apply lt_lsub }), λ h, le_antisymm (sup_le_lsub f) (lsub_le h)⟩ @[simp] lemma lsub_empty {ι} [h : is_empty ι] (f : ι → ordinal) : lsub f = 0 := by { rw [←ordinal.le_zero, lsub_le_iff], exact h.elim } lemma lsub_pos {ι} [h : nonempty ι] (f : ι → ordinal) : 0 < lsub f := h.elim $ λ i, (ordinal.zero_le _).trans_lt (lt_lsub f i) @[simp] theorem lsub_eq_zero_iff {ι} {f : ι → ordinal} : lsub f = 0 ↔ is_empty ι := begin refine ⟨λ h, ⟨λ i, _⟩, λ h, @lsub_empty _ h _⟩, have := @lsub_pos _ ⟨i⟩ f, rw h at this, exact this.false end @[simp] theorem lsub_const {ι} [hι : nonempty ι] (o : ordinal) : lsub (λ _ : ι, o) = succ o := sup_const (succ o) @[simp] theorem lsub_unique {ι} [hι : unique ι] (f : ι → ordinal) : lsub f = succ (f default) := sup_unique _ theorem lsub_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f ⊆ set.range g) : lsub.{u (max v w)} f ≤ lsub.{v (max u w)} g := sup_le_of_range_subset (by convert set.image_subset _ h; apply set.range_comp) theorem lsub_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f = set.range g) : lsub.{u (max v w)} f = lsub.{v (max u w)} g := (lsub_le_of_range_subset h.le).antisymm (lsub_le_of_range_subset.{v u w} h.ge) theorem lsub_not_mem_range {ι} (f : ι → ordinal) : lsub f ∉ set.range f := λ ⟨i, h⟩, h.not_lt (lt_lsub f i) theorem nonempty_compl_range {ι : Type u} (f : ι → ordinal.{max u v}) : (set.range f)ᶜ.nonempty := ⟨_, lsub_not_mem_range f⟩ @[simp] theorem lsub_typein (o : ordinal) : lsub.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o := (lsub_le.{u u} typein_lt_self).antisymm begin by_contra' h, nth_rewrite 0 ←type_lt o at h, simpa [typein_enum] using lt_lsub.{u u} (typein (<)) (enum (<) _ h) end theorem sup_typein_limit {o : ordinal} (ho : ∀ a, a < o → succ a < o) : sup.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o := by rw (sup_eq_lsub_iff_succ.{u u} (typein (<))).2; rwa lsub_typein o @[simp] theorem sup_typein_succ {o : ordinal} : sup.{u u} (typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) = o := begin cases sup_eq_lsub_or_sup_succ_eq_lsub.{u u} (typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) with h h, { rw sup_eq_lsub_iff_succ at h, simp only [lsub_typein] at h, exact (h o (lt_succ o)).false.elim }, rw [←succ_eq_succ_iff, h], apply lsub_typein end /-- The least strict upper bound of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is to `lsub` as `bsup` is to `sup`. -/ def blsub (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} := o.bsup (λ a ha, succ (f a ha)) @[simp] theorem bsup_eq_blsub (o : ordinal) (f : Π a < o, ordinal) : bsup o (λ a ha, succ (f a ha)) = blsub o f := rfl theorem lsub_eq_blsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f) : lsub (family_of_bfamily' r ho f) = blsub o f := sup_eq_bsup' r ho (λ a ha, succ (f a ha)) theorem lsub_eq_lsub {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal) : lsub (family_of_bfamily' r ho f) = lsub (family_of_bfamily' r' ho' f) := by rw [lsub_eq_blsub', lsub_eq_blsub'] @[simp] theorem lsub_eq_blsub {o} (f : Π a < o, ordinal) : lsub (family_of_bfamily o f) = blsub o f := lsub_eq_blsub' _ _ _ @[simp] theorem blsub_eq_lsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) : blsub _ (bfamily_of_family' r f) = lsub f := bsup_eq_sup' r (succ ∘ f) theorem blsub_eq_blsub {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r'] (f : ι → ordinal) : blsub _ (bfamily_of_family' r f) = blsub _ (bfamily_of_family' r' f) := by rw [blsub_eq_lsub', blsub_eq_lsub'] @[simp] theorem blsub_eq_lsub {ι} (f : ι → ordinal) : blsub _ (bfamily_of_family f) = lsub f := blsub_eq_lsub' _ _ @[congr] lemma blsub_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) : blsub o₁ f = blsub o₂ (λ a h, f a (h.trans_eq ho.symm)) := by subst ho theorem blsub_le_iff {o f a} : blsub o f ≤ a ↔ ∀ i h, f i h < a := by { convert bsup_le_iff, simp [succ_le_iff] } theorem blsub_le {o : ordinal} {f : Π b < o, ordinal} {a} : (∀ i h, f i h < a) → blsub o f ≤ a := blsub_le_iff.2 theorem lt_blsub {o} (f : Π a < o, ordinal) (i h) : f i h < blsub o f := blsub_le_iff.1 le_rfl _ _ theorem lt_blsub_iff {o f a} : a < blsub o f ↔ ∃ i hi, a ≤ f i hi := by simpa only [not_forall, not_lt, not_le] using not_congr (@blsub_le_iff _ f a) theorem bsup_le_blsub {o} (f : Π a < o, ordinal) : bsup o f ≤ blsub o f := bsup_le (λ i h, (lt_blsub f i h).le) theorem blsub_le_bsup_succ {o} (f : Π a < o, ordinal) : blsub o f ≤ succ (bsup o f) := blsub_le (λ i h, lt_succ_iff.2 (le_bsup f i h)) theorem bsup_eq_blsub_or_succ_bsup_eq_blsub {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ∨ succ (bsup o f) = blsub o f := by { rw [←sup_eq_bsup, ←lsub_eq_blsub], exact sup_eq_lsub_or_sup_succ_eq_lsub _ } theorem bsup_succ_le_blsub {o} (f : Π a < o, ordinal) : succ (bsup o f) ≤ blsub o f ↔ ∃ i hi, f i hi = bsup o f := begin refine ⟨λ h, _, _⟩, { by_contra' hf, exact ne_of_lt (succ_le_iff.1 h) (le_antisymm (bsup_le_blsub f) (blsub_le (lt_bsup_of_ne_bsup.1 hf))) }, rintro ⟨_, _, hf⟩, rw [succ_le_iff, ←hf], exact lt_blsub _ _ _ end theorem bsup_succ_eq_blsub {o} (f : Π a < o, ordinal) : succ (bsup o f) = blsub o f ↔ ∃ i hi, f i hi = bsup o f := (blsub_le_bsup_succ f).le_iff_eq.symm.trans (bsup_succ_le_blsub f) theorem bsup_eq_blsub_iff_succ {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ↔ ∀ a < blsub o f, succ a < blsub o f := by { rw [←sup_eq_bsup, ←lsub_eq_blsub], apply sup_eq_lsub_iff_succ } theorem bsup_eq_blsub_iff_lt_bsup {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ↔ ∀ i hi, f i hi < bsup o f := ⟨λ h i, (by { rw h, apply lt_blsub }), λ h, le_antisymm (bsup_le_blsub f) (blsub_le h)⟩ theorem bsup_eq_blsub_of_lt_succ_limit {o} (ho : is_limit o) {f : Π a < o, ordinal} (hf : ∀ a ha, f a ha < f (succ a) (ho.2 a ha)) : bsup o f = blsub o f := begin rw bsup_eq_blsub_iff_lt_bsup, exact λ i hi, (hf i hi).trans_le (le_bsup f _ _) end theorem blsub_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = succ (f o (lt_succ o)) := bsup_succ_of_mono $ λ i j hi hj h, succ_le_succ (hf hi hj h) @[simp] theorem blsub_eq_zero_iff {o} {f : Π a < o, ordinal} : blsub o f = 0 ↔ o = 0 := by { rw [←lsub_eq_blsub, lsub_eq_zero_iff], exact out_empty_iff_eq_zero } @[simp] lemma blsub_zero (f : Π a < (0 : ordinal), ordinal) : blsub 0 f = 0 := by rwa blsub_eq_zero_iff lemma blsub_pos {o : ordinal} (ho : 0 < o) (f : Π a < o, ordinal) : 0 < blsub o f := (ordinal.zero_le _).trans_lt (lt_blsub f 0 ho) theorem blsub_type (r : α → α → Prop) [is_well_order α r] (f) : blsub (type r) f = lsub (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [blsub_le_iff, lsub_le_iff]; exact ⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem blsub_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : blsub.{u v} o (λ _ _, a) = succ a := bsup_const.{u v} ho (succ a) @[simp] theorem blsub_one (f : Π a < (1 : ordinal), ordinal) : blsub 1 f = succ (f 0 zero_lt_one) := bsup_one _ @[simp] theorem blsub_id : ∀ o, blsub.{u u} o (λ x _, x) = o := lsub_typein theorem bsup_id_limit {o : ordinal} : (∀ a < o, succ a < o) → bsup.{u u} o (λ x _, x) = o := sup_typein_limit @[simp] theorem bsup_id_succ (o) : bsup.{u u} (succ o) (λ x _, x) = o := sup_typein_succ theorem blsub_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : blsub.{u (max v w)} o f ≤ blsub.{v (max u w)} o' g := bsup_le_of_brange_subset $ λ a ⟨b, hb, hb'⟩, begin obtain ⟨c, hc, hc'⟩ := h ⟨b, hb, rfl⟩, simp_rw ←hc' at hb', exact ⟨c, hc, hb'⟩ end theorem blsub_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : {o | ∃ i hi, f i hi = o} = {o | ∃ i hi, g i hi = o}) : blsub.{u (max v w)} o f = blsub.{v (max u w)} o' g := (blsub_le_of_brange_subset h.le).antisymm (blsub_le_of_brange_subset.{v u w} h.ge) theorem bsup_comp {o o' : ordinal} {f : Π a < o, ordinal} (hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) : bsup o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = bsup o f := begin apply le_antisymm; refine bsup_le (λ i hi, _), { apply le_bsup }, { rw [←hg, lt_blsub_iff] at hi, rcases hi with ⟨j, hj, hj'⟩, exact (hf _ _ hj').trans (le_bsup _ _ _) } end theorem blsub_comp {o o' : ordinal} {f : Π a < o, ordinal} (hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) : blsub o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = blsub o f := @bsup_comp o _ (λ a ha, succ (f a ha)) (λ i j _ _ h, succ_le_succ_iff.2 (hf _ _ h)) g hg theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : bsup.{u} o (λ x _, f x) = f o := by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id_limit h.2] } theorem is_normal.blsub_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : blsub.{u} o (λ x _, f x) = f o := by { rw [←H.bsup_eq h, bsup_eq_blsub_of_lt_succ_limit h], exact (λ a _, H.1 a) } theorem is_normal_iff_lt_succ_and_bsup_eq {f} : is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → bsup o (λ x _, f x) = f o := ⟨λ h, ⟨h.1, @is_normal.bsup_eq f h⟩, λ ⟨h₁, h₂⟩, ⟨h₁, λ o ho a, (by {rw ←h₂ o ho, exact bsup_le_iff})⟩⟩ theorem is_normal_iff_lt_succ_and_blsub_eq {f} : is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → blsub o (λ x _, f x) = f o := begin rw [is_normal_iff_lt_succ_and_bsup_eq, and.congr_right_iff], intro h, split; intros H o ho; have := H o ho; rwa ←bsup_eq_blsub_of_lt_succ_limit ho (λ a _, h a) at * end theorem is_normal.eq_iff_zero_and_succ {f g : ordinal.{u} → ordinal.{u}} (hf : is_normal f) (hg : is_normal g) : f = g ↔ f 0 = g 0 ∧ ∀ a, f a = g a → f (succ a) = g (succ a) := ⟨λ h, by simp [h], λ ⟨h₁, h₂⟩, funext (λ a, begin apply a.limit_rec_on, assumption', intros o ho H, rw [←is_normal.bsup_eq.{u u} hf ho, ←is_normal.bsup_eq.{u u} hg ho], congr, ext b hb, exact H b hb end)⟩ /-! ### Minimum excluded ordinals -/ /-- The minimum excluded ordinal in a family of ordinals. -/ def mex {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal := Inf (set.range f)ᶜ theorem mex_not_mem_range {ι : Type u} (f : ι → ordinal.{max u v}) : mex f ∉ set.range f := Inf_mem (nonempty_compl_range f) theorem ne_mex {ι} (f : ι → ordinal) : ∀ i, f i ≠ mex f := by simpa using mex_not_mem_range f theorem mex_le_of_ne {ι} {f : ι → ordinal} {a} (ha : ∀ i, f i ≠ a) : mex f ≤ a := cInf_le' (by simp [ha]) theorem exists_of_lt_mex {ι} {f : ι → ordinal} {a} (ha : a < mex f) : ∃ i, f i = a := by { by_contra' ha', exact ha.not_le (mex_le_of_ne ha') } theorem mex_le_lsub {ι} (f : ι → ordinal) : mex f ≤ lsub f := cInf_le' (lsub_not_mem_range f) theorem mex_monotone {α β} {f : α → ordinal} {g : β → ordinal} (h : set.range f ⊆ set.range g) : mex f ≤ mex g := begin refine mex_le_of_ne (λ i hi, _), cases h ⟨i, rfl⟩ with j hj, rw ←hj at hi, exact ne_mex g j hi end theorem mex_lt_ord_succ_mk {ι} (f : ι → ordinal) : mex f < (succ (#ι)).ord := begin by_contra' h, apply (lt_succ (#ι)).not_le, have H := λ a, exists_of_lt_mex ((typein_lt_self a).trans_le h), let g : (succ (#ι)).ord.out.α → ι := λ a, classical.some (H a), have hg : injective g := λ a b h', begin have Hf : ∀ x, f (g x) = typein (<) x := λ a, classical.some_spec (H a), apply_fun f at h', rwa [Hf, Hf, typein_inj] at h' end, convert cardinal.mk_le_of_injective hg, rw cardinal.mk_ord_out end /-- The minimum excluded ordinal of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is a special case of `mex` over the family provided by `family_of_bfamily`. This is to `mex` as `bsup` is to `sup`. -/ def bmex (o : ordinal) (f : Π a < o, ordinal) : ordinal := mex (family_of_bfamily o f) theorem bmex_not_mem_brange {o : ordinal} (f : Π a < o, ordinal) : bmex o f ∉ brange o f := by { rw ←range_family_of_bfamily, apply mex_not_mem_range } theorem ne_bmex {o : ordinal} (f : Π a < o, ordinal) {i} (hi) : f i hi ≠ bmex o f := begin convert ne_mex _ (enum (<) i (by rwa type_lt)), rw family_of_bfamily_enum end theorem bmex_le_of_ne {o : ordinal} {f : Π a < o, ordinal} {a} (ha : ∀ i hi, f i hi ≠ a) : bmex o f ≤ a := mex_le_of_ne (λ i, ha _ _) theorem exists_of_lt_bmex {o : ordinal} {f : Π a < o, ordinal} {a} (ha : a < bmex o f) : ∃ i hi, f i hi = a := begin cases exists_of_lt_mex ha with i hi, exact ⟨_, typein_lt_self i, hi⟩ end theorem bmex_le_blsub {o : ordinal} (f : Π a < o, ordinal) : bmex o f ≤ blsub o f := mex_le_lsub _ theorem bmex_monotone {o o' : ordinal} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : bmex o f ≤ bmex o' g := mex_monotone (by rwa [range_family_of_bfamily, range_family_of_bfamily]) theorem bmex_lt_ord_succ_card {o : ordinal} (f : Π a < o, ordinal) : bmex o f < (succ o.card).ord := by { rw ←mk_ordinal_out, exact (mex_lt_ord_succ_mk (family_of_bfamily o f)) } end ordinal /-! ### Results about injectivity and surjectivity -/ lemma not_surjective_of_ordinal {α : Type u} (f : α → ordinal.{u}) : ¬ surjective f := λ h, ordinal.lsub_not_mem_range.{u u} f (h _) lemma not_injective_of_ordinal {α : Type u} (f : ordinal.{u} → α) : ¬ injective f := λ h, not_surjective_of_ordinal _ (inv_fun_surjective h) lemma not_surjective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : α → ordinal.{u}) : ¬ surjective f := λ h, not_surjective_of_ordinal _ (h.comp (equiv_shrink _).symm.surjective) lemma not_injective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : ordinal.{u} → α) : ¬ injective f := λ h, not_injective_of_ordinal _ ((equiv_shrink _).injective.comp h) /-- The type of ordinals in universe `u` is not `small.{u}`. This is the type-theoretic analog of the Burali-Forti paradox. -/ theorem not_small_ordinal : ¬ small.{u} ordinal.{max u v} := λ h, @not_injective_of_ordinal_of_small _ h _ (λ a b, ordinal.lift_inj.1) /-! ### Enumerating unbounded sets of ordinals with ordinals -/ namespace ordinal section /-- Enumerator function for an unbounded set of ordinals. -/ def enum_ord (S : set ordinal.{u}) : ordinal → ordinal := lt_wf.fix (λ o f, Inf (S ∩ set.Ici (blsub.{u u} o f))) variables {S : set ordinal.{u}} /-- The equation that characterizes `enum_ord` definitionally. This isn't the nicest expression to work with, so consider using `enum_ord_def` instead. -/ theorem enum_ord_def' (o) : enum_ord S o = Inf (S ∩ set.Ici (blsub.{u u} o (λ a _, enum_ord S a))) := lt_wf.fix_eq _ _ /-- The set in `enum_ord_def'` is nonempty. -/ theorem enum_ord_def'_nonempty (hS : unbounded (<) S) (a) : (S ∩ set.Ici a).nonempty := let ⟨b, hb, hb'⟩ := hS a in ⟨b, hb, le_of_not_gt hb'⟩ private theorem enum_ord_mem_aux (hS : unbounded (<) S) (o) : (enum_ord S o) ∈ S ∩ set.Ici (blsub.{u u} o (λ c _, enum_ord S c)) := by { rw enum_ord_def', exact Inf_mem (enum_ord_def'_nonempty hS _) } theorem enum_ord_mem (hS : unbounded (<) S) (o) : enum_ord S o ∈ S := (enum_ord_mem_aux hS o).left theorem blsub_le_enum_ord (hS : unbounded (<) S) (o) : blsub.{u u} o (λ c _, enum_ord S c) ≤ enum_ord S o := (enum_ord_mem_aux hS o).right theorem enum_ord_strict_mono (hS : unbounded (<) S) : strict_mono (enum_ord S) := λ _ _ h, (lt_blsub.{u u} _ _ h).trans_le (blsub_le_enum_ord hS _) /-- A more workable definition for `enum_ord`. -/ theorem enum_ord_def (o) : enum_ord S o = Inf (S ∩ {b | ∀ c, c < o → enum_ord S c < b}) := begin rw enum_ord_def', congr, ext, exact ⟨λ h a hao, (lt_blsub.{u u} _ _ hao).trans_le h, blsub_le⟩ end /-- The set in `enum_ord_def` is nonempty. -/ lemma enum_ord_def_nonempty (hS : unbounded (<) S) {o} : {x | x ∈ S ∧ ∀ c, c < o → enum_ord S c < x}.nonempty := (⟨_, enum_ord_mem hS o, λ _ b, enum_ord_strict_mono hS b⟩) @[simp] theorem enum_ord_range {f : ordinal → ordinal} (hf : strict_mono f) : enum_ord (range f) = f := funext (λ o, begin apply ordinal.induction o, intros a H, rw enum_ord_def a, have Hfa : f a ∈ range f ∩ {b | ∀ c, c < a → enum_ord (range f) c < b} := ⟨mem_range_self a, λ b hb, (by {rw H b hb, exact hf hb})⟩, refine (cInf_le' Hfa).antisymm ((le_cInf_iff'' ⟨_, Hfa⟩).2 _), rintros _ ⟨⟨c, rfl⟩, hc : ∀ b < a, enum_ord (range f) b < f c⟩, rw hf.le_iff_le, contrapose! hc, exact ⟨c, hc, (H c hc).ge⟩, end) @[simp] theorem enum_ord_univ : enum_ord set.univ = id := by { rw ←range_id, exact enum_ord_range strict_mono_id } @[simp] theorem enum_ord_zero : enum_ord S 0 = Inf S := by { rw enum_ord_def, simp [ordinal.not_lt_zero] } theorem enum_ord_succ_le {a b} (hS : unbounded (<) S) (ha : a ∈ S) (hb : enum_ord S b < a) : enum_ord S (succ b) ≤ a := begin rw enum_ord_def, exact cInf_le' ⟨ha, λ c hc, ((enum_ord_strict_mono hS).monotone (le_of_lt_succ hc)).trans_lt hb⟩ end theorem enum_ord_le_of_subset {S T : set ordinal} (hS : unbounded (<) S) (hST : S ⊆ T) (a) : enum_ord T a ≤ enum_ord S a := begin apply ordinal.induction a, intros b H, rw enum_ord_def, exact cInf_le' ⟨hST (enum_ord_mem hS b), λ c h, (H c h).trans_lt (enum_ord_strict_mono hS h)⟩ end theorem enum_ord_surjective (hS : unbounded (<) S) : ∀ s ∈ S, ∃ a, enum_ord S a = s := λ s hs, ⟨Sup {a | enum_ord S a ≤ s}, begin apply le_antisymm, { rw enum_ord_def, refine cInf_le' ⟨hs, λ a ha, _⟩, have : enum_ord S 0 ≤ s := by { rw enum_ord_zero, exact cInf_le' hs }, rcases exists_lt_of_lt_cSup (by exact ⟨0, this⟩) ha with ⟨b, hb, hab⟩, exact (enum_ord_strict_mono hS hab).trans_le hb }, { by_contra' h, exact (le_cSup ⟨s, λ a, (lt_wf.self_le_of_strict_mono (enum_ord_strict_mono hS) a).trans⟩ (enum_ord_succ_le hS hs h)).not_lt (lt_succ _) } end⟩ /-- An order isomorphism between an unbounded set of ordinals and the ordinals. -/ def enum_ord_order_iso (hS : unbounded (<) S) : ordinal ≃o S := strict_mono.order_iso_of_surjective (λ o, ⟨_, enum_ord_mem hS o⟩) (enum_ord_strict_mono hS) (λ s, let ⟨a, ha⟩ := enum_ord_surjective hS s s.prop in ⟨a, subtype.eq ha⟩) theorem range_enum_ord (hS : unbounded (<) S) : range (enum_ord S) = S := by { rw range_eq_iff, exact ⟨enum_ord_mem hS, enum_ord_surjective hS⟩ } /-- A characterization of `enum_ord`: it is the unique strict monotonic function with range `S`. -/ theorem eq_enum_ord (f : ordinal → ordinal) (hS : unbounded (<) S) : strict_mono f ∧ range f = S ↔ f = enum_ord S := begin split, { rintro ⟨h₁, h₂⟩, rwa [←lt_wf.eq_strict_mono_iff_eq_range h₁ (enum_ord_strict_mono hS), range_enum_ord hS] }, { rintro rfl, exact ⟨enum_ord_strict_mono hS, range_enum_ord hS⟩ } end end /-! ### Ordinal exponential -/ /-- The ordinal exponential, defined by transfinite recursion. -/ instance : has_pow ordinal ordinal := ⟨λ a b, if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem opow_def (a b : ordinal) : a ^ b = if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) := rfl theorem zero_opow' (a : ordinal) : 0 ^ a = 1 - a := by simp only [opow_def, if_pos rfl] @[simp] theorem zero_opow {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_opow', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem opow_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [opow_def, if_pos h, sub_zero], simp only [opow_def, if_neg h, limit_rec_on_zero]] @[simp] theorem opow_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_opow (succ_ne_zero _), mul_zero] else by simp only [opow_def, limit_rec_on_succ, if_neg h] theorem opow_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp only [opow_def, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem opow_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [opow_limit a0 h, bsup_le_iff] theorem lt_opow_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, opow_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem opow_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, opow_succ]; simp only [opow_zero, one_mul] @[simp] theorem one_opow (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [opow_zero] }, { intros _ ih, simp only [opow_succ, ih, mul_one] }, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [opow_le_of_limit ordinal.one_ne_zero l], exact ⟨λ H, by simpa only [opow_zero] using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem opow_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [opow_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [opow_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_opow_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem opow_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := ordinal.pos_iff_ne_zero.1 $ opow_pos b $ ordinal.pos_iff_ne_zero.2 a0 theorem opow_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from zero_lt_one.trans h, ⟨λ b, by simpa only [mul_one, opow_succ] using (mul_lt_mul_iff_left (opow_pos b a0)).2 h, λ b l c, opow_le_of_limit (ne_of_gt a0) l⟩ theorem opow_lt_opow_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (opow_is_normal a1).lt_iff theorem opow_le_opow_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (opow_is_normal a1).le_iff theorem opow_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (opow_is_normal a1).inj theorem opow_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (opow_is_normal a1).is_limit theorem opow_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw opow_succ, exact mul_is_limit (opow_pos _ l.pos) l }, { exact opow_is_limit l.one_lt l' } end theorem opow_le_opow_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (opow_le_opow_iff_right h₁).2 h₂ }, { subst a, simp only [one_opow] } end theorem opow_le_opow_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [opow_zero] }, { simp only [zero_opow c0, ordinal.zero_le] } }, { apply limit_rec_on c, { simp only [opow_zero] }, { intros c IH, simpa only [opow_succ] using mul_le_mul' IH ab }, { exact λ c l IH, (opow_le_of_limit a0 l).2 (λ b' h, (IH _ h).trans (opow_le_opow_right ((ordinal.pos_iff_ne_zero.2 a0).trans_le ab) h.le)) } } end theorem left_le_opow (a : ordinal) {b : ordinal} (b1 : 0 < b) : a ≤ a ^ b := begin nth_rewrite 0 ←opow_one a, cases le_or_gt a 1 with a1 a1, { cases lt_or_eq_of_le a1 with a0 a1, { rw lt_one_iff_zero at a0, rw [a0, zero_opow ordinal.one_ne_zero], exact ordinal.zero_le _ }, rw [a1, one_opow, one_opow] }, rwa [opow_le_opow_iff_right a1, one_le_iff_pos] end theorem right_le_opow {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (opow_is_normal a1).self_le _ theorem opow_lt_opow_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by { rw [opow_succ, opow_succ], exact (mul_le_mul_right' (opow_le_opow_left c ab.le) a).trans_lt (mul_lt_mul_of_pos_left ab (opow_pos c ((ordinal.zero_le a).trans_lt ab))) } theorem opow_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin rcases eq_or_ne a 0 with rfl | a0, { rcases eq_or_ne c 0 with rfl | c0, { simp }, have : b + c ≠ 0 := ((ordinal.pos_iff_ne_zero.2 c0).trans_le (le_add_left _ _)).ne', simp only [zero_opow c0, zero_opow this, mul_zero] }, rcases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with rfl | a1, { simp only [one_opow, mul_one] }, apply limit_rec_on c, { simp }, { intros c IH, rw [add_succ, opow_succ, IH, opow_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((opow_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), dsimp only [function.comp], simp only [IH] {contextual := tt}, exact (((mul_is_normal $ opow_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans (opow_is_normal a1)).limit_le l).symm } end theorem opow_one_add (a b : ordinal) : a ^ (1 + b) = a * a ^ b := by rw [opow_add, opow_one] theorem opow_dvd_opow (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by { rw [← ordinal.add_sub_cancel_of_le h, opow_add], apply dvd_mul_right } theorem opow_dvd_opow_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((opow_lt_opow_iff_right a1).2 hn) $ le_of_dvd (opow_ne_zero _ $ one_le_iff_ne_zero.1 $ a1.le) h, opow_dvd_opow _⟩ theorem opow_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, opow_zero, one_opow]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, opow_zero]}, simp only [zero_opow b0, zero_opow c0, zero_opow (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_opow] }, apply limit_rec_on c, { simp only [mul_zero, opow_zero] }, { intros c IH, rw [mul_succ, opow_add, IH, opow_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((opow_is_normal a1).trans (mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _), dsimp only [function.comp], simp only [IH] {contextual := tt}, exact (opow_le_of_limit (opow_ne_zero _ a0) l).symm } end /-! ### Ordinal logarithm -/ /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b ^ u`. -/ @[pp_nodot] def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred (Inf {o | x < b ^ o}) else 0 /-- The set in the definition of `log` is nonempty. -/ theorem log_nonempty {b x : ordinal} (h : 1 < b) : {o | x < b ^ o}.nonempty := ⟨_, succ_le_iff.1 (right_le_opow _ h)⟩ theorem log_def {b : ordinal} (h : 1 < b) (x : ordinal) : log b x = pred (Inf {o | x < b ^ o}) := by simp only [log, dif_pos h] theorem log_of_not_one_lt_left {b : ordinal} (h : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg h] theorem log_of_left_le_one {b : ordinal} (h : b ≤ 1) : ∀ x, log b x = 0 := log_of_not_one_lt_left h.not_lt @[simp] lemma log_zero_left : ∀ b, log 0 b = 0 := log_of_left_le_one zero_le_one @[simp] theorem log_zero_right (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then begin rw [log_def b1, ← ordinal.le_zero, pred_le], apply cInf_le', dsimp, rw [succ_zero, opow_one], exact zero_lt_one.trans b1 end else by simp only [log_of_not_one_lt_left b1] @[simp] theorem log_one_left : ∀ b, log 1 b = 0 := log_of_left_le_one le_rfl theorem succ_log_def {b x : ordinal} (hb : 1 < b) (hx : x ≠ 0) : succ (log b x) = Inf {o | x < b ^ o} := begin let t := Inf {o | x < b ^ o}, have : x < b ^ t := Inf_mem (log_nonempty hb), rcases zero_or_succ_or_limit t with h|h|h, { refine ((one_le_iff_ne_zero.2 hx).not_lt _).elim, simpa only [h, opow_zero] }, { rw [show log b x = pred t, from log_def hb x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_opow_of_limit (zero_lt_one.trans hb).ne' h).1 this with ⟨a, h₁, h₂⟩, exact h₁.not_le.elim ((le_cInf_iff'' (log_nonempty hb)).1 le_rfl a h₂) } end theorem lt_opow_succ_log_self {b : ordinal} (hb : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin rcases eq_or_ne x 0 with rfl | hx, { apply opow_pos _ (zero_lt_one.trans hb) }, { rw succ_log_def hb hx, exact Inf_mem (log_nonempty hb) } end theorem opow_log_le_self (b) {x : ordinal} (hx : x ≠ 0) : b ^ log b x ≤ x := begin rcases eq_or_ne b 0 with rfl | b0, { rw zero_opow', refine (sub_le_self _ _).trans (one_le_iff_ne_zero.2 hx) }, rcases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with hb | rfl, { refine le_of_not_lt (λ h, (lt_succ (log b x)).not_le _), have := @cInf_le' _ _ {o | x < b ^ o} _ h, rwa ←succ_log_def hb hx at this }, { rwa [one_opow, one_le_iff_ne_zero] } end /-- `opow b` and `log b` (almost) form a Galois connection. -/ theorem opow_le_iff_le_log {b x c : ordinal} (hb : 1 < b) (hx : x ≠ 0) : b ^ c ≤ x ↔ c ≤ log b x := ⟨λ h, le_of_not_lt $ λ hn, (lt_opow_succ_log_self hb x).not_le $ ((opow_le_opow_iff_right hb).2 (succ_le_of_lt hn)).trans h, λ h, ((opow_le_opow_iff_right hb).2 h).trans (opow_log_le_self b hx)⟩ theorem lt_opow_iff_log_lt {b x c : ordinal} (hb : 1 < b) (hx : x ≠ 0) : x < b ^ c ↔ log b x < c := lt_iff_lt_of_le_iff_le (opow_le_iff_le_log hb hx) theorem log_pos {b o : ordinal} (hb : 1 < b) (ho : o ≠ 0) (hbo : b ≤ o) : 0 < log b o := by rwa [←succ_le_iff, succ_zero, ←opow_le_iff_le_log hb ho, opow_one] theorem log_eq_zero {b o : ordinal} (hbo : o < b) : log b o = 0 := begin rcases eq_or_ne o 0 with rfl | ho, { exact log_zero_right b }, cases le_or_lt b 1 with hb hb, { rcases le_one_iff.1 hb with rfl | rfl, { exact log_zero_left o }, { exact log_one_left o } }, { rwa [←ordinal.le_zero, ←lt_succ_iff, succ_zero, ←lt_opow_iff_log_lt hb ho, opow_one] } end @[mono] theorem log_mono_right (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if hx : x = 0 then by simp only [hx, log_zero_right, ordinal.zero_le] else if hb : 1 < b then (opow_le_iff_le_log hb (lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 hx) xy).ne').1 $ (opow_log_le_self _ hx).trans xy else by simp only [log_of_not_one_lt_left hb, ordinal.zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if hx : x = 0 then by simp only [hx, log_zero_right, ordinal.zero_le] else if hb : 1 < b then (right_le_opow _ hb).trans (opow_log_le_self b hx) else by simp only [log_of_not_one_lt_left hb, ordinal.zero_le] @[simp] theorem log_one_right (b : ordinal) : log b 1 = 0 := if hb : 1 < b then log_eq_zero hb else log_of_not_one_lt_left hb 1 theorem mod_opow_log_lt_self (b : ordinal) {o : ordinal} (ho : o ≠ 0) : o % b ^ log b o < o := begin rcases eq_or_ne b 0 with rfl | hb, { simpa using ordinal.pos_iff_ne_zero.2 ho }, { exact (mod_lt _ $ opow_ne_zero _ hb).trans_le (opow_log_le_self _ ho) } end theorem log_mod_opow_log_lt_log_self {b o : ordinal} (hb : 1 < b) (ho : o ≠ 0) (hbo : b ≤ o) : log b (o % b ^ log b o) < log b o := begin cases eq_or_ne (o % b ^ log b o) 0, { rw [h, log_zero_right], apply log_pos hb ho hbo }, { rw [←succ_le_iff, succ_log_def hb h], apply cInf_le', apply mod_lt, rw ←ordinal.pos_iff_ne_zero, exact opow_pos _ (zero_lt_one.trans hb) } end lemma opow_mul_add_pos {b v : ordinal} (hb : b ≠ 0) (u) (hv : v ≠ 0) (w) : 0 < b ^ u * v + w := (opow_pos u $ ordinal.pos_iff_ne_zero.2 hb).trans_le $ (le_mul_left _ $ ordinal.pos_iff_ne_zero.2 hv).trans $ le_add_right _ _ lemma opow_mul_add_lt_opow_mul_succ {b u w : ordinal} (v : ordinal) (hw : w < b ^ u) : b ^ u * v + w < b ^ u * (succ v) := by rwa [mul_succ, add_lt_add_iff_left] lemma opow_mul_add_lt_opow_succ {b u v w : ordinal} (hvb : v < b) (hw : w < b ^ u) : b ^ u * v + w < b ^ (succ u) := begin convert (opow_mul_add_lt_opow_mul_succ v hw).trans_le (mul_le_mul_left' (succ_le_of_lt hvb) _), exact opow_succ b u end theorem log_opow_mul_add {b u v w : ordinal} (hb : 1 < b) (hv : v ≠ 0) (hvb : v < b) (hw : w < b ^ u) : log b (b ^ u * v + w) = u := begin have hne' := (opow_mul_add_pos (zero_lt_one.trans hb).ne' u hv w).ne', by_contra' hne, cases lt_or_gt_of_ne hne with h h, { rw ←lt_opow_iff_log_lt hb hne' at h, exact h.not_le ((le_mul_left _ (ordinal.pos_iff_ne_zero.2 hv)).trans (le_add_right _ _)) }, { change _ < _ at h, rw [←succ_le_iff, ←opow_le_iff_le_log hb hne'] at h, exact (not_lt_of_le h) (opow_mul_add_lt_opow_succ hvb hw) } end theorem log_opow {b : ordinal} (hb : 1 < b) (x : ordinal) : log b (b ^ x) = x := begin convert log_opow_mul_add hb zero_ne_one.symm hb (opow_pos x (zero_lt_one.trans hb)), rw [add_zero, mul_one] end theorem div_opow_log_lt {b : ordinal} (o : ordinal) (hb : 1 < b) : o / b ^ log b o < b := begin rw [div_lt (opow_pos _ (zero_lt_one.trans hb)).ne', ←opow_succ], exact lt_opow_succ_log_self hb o end theorem add_log_le_log_mul {x y : ordinal} (b : ordinal) (hx : x ≠ 0) (hy : y ≠ 0) : log b x + log b y ≤ log b (x * y) := begin by_cases hb : 1 < b, { rw [←opow_le_iff_le_log hb (mul_ne_zero hx hy), opow_add], exact mul_le_mul' (opow_log_le_self b hx) (opow_log_le_self b hy) }, simp only [log_of_not_one_lt_left hb, zero_add] end /-! ### Casting naturals into ordinals, compatibility with operations -/ @[simp, norm_cast] theorem nat_cast_mul (m : ℕ) : ∀ n : ℕ, ((m * n : ℕ) : ordinal) = m * n | 0 := by simp | (n+1) := by rw [nat.mul_succ, nat.cast_add, nat_cast_mul, nat.cast_succ, mul_add_one] @[simp, norm_cast] theorem nat_cast_opow (m : ℕ) : ∀ n : ℕ, ((pow m n : ℕ) : ordinal) = m ^ n | 0 := by simp | (n+1) := by rw [pow_succ', nat_cast_mul, nat_cast_opow, nat.cast_succ, add_one_eq_succ, opow_succ] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [←cardinal.ord_nat, ←cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp, norm_cast] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp, norm_cast] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp, norm_cast] theorem nat_cast_sub (m n : ℕ) : ((m - n : ℕ) : ordinal) = m - n := begin cases le_total m n with h h, { rw [tsub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)], refl }, { apply (add_left_cancel n).1, rw [←nat.cast_add, add_tsub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)] } end @[simp, norm_cast] theorem nat_cast_div (m n : ℕ) : ((m / n : ℕ) : ordinal) = m / n := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, { have hn' := nat_cast_ne_zero.2 hn, apply le_antisymm, { rw [le_div hn', ←nat_cast_mul, nat_cast_le, mul_comm], apply nat.div_mul_le_self }, { rw [div_le hn', ←add_one_eq_succ, ←nat.cast_succ, ←nat_cast_mul, nat_cast_lt, mul_comm, ←nat.div_lt_iff_lt_mul (nat.pos_of_ne_zero hn)], apply nat.lt_succ_self } } end @[simp, norm_cast] theorem nat_cast_mod (m n : ℕ) : ((m % n : ℕ) : ordinal) = m % n := by rw [←add_left_cancel, div_add_mod, ←nat_cast_div, ←nat_cast_mul, ←nat.cast_add, nat.div_add_mod] @[simp] theorem lift_nat_cast : ∀ n : ℕ, lift.{u v} n = n | 0 := by simp | (n+1) := by simp [lift_nat_cast n] end ordinal /-! ### Properties of `omega` -/ namespace cardinal open ordinal @[simp] theorem ord_aleph_0 : ord.{u} ℵ₀ = ω := le_antisymm (ord_le.2 $ le_rfl) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ←lift_card, ←lift_aleph_0.{0 u}, lift_lt, ←typein_enum (<) h'], exact lt_aleph_0_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_aleph_0_le {c} (h : ℵ₀ ≤ c) : c + 1 = c := begin rw [add_comm, ←card_ord c, ←card_one, ←card_add, one_add_of_omega_le], rwa [←ord_aleph_0, ord_le_ord] end end cardinal namespace ordinal theorem lt_add_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b + c ↔ ∃ c' < c, a < b + c' := by rw [←is_normal.bsup_eq.{u u} (add_is_normal b) h, lt_bsup] theorem lt_omega {o : ordinal} : o < ω ↔ ∃ n : ℕ, o = n := by simp_rw [←cardinal.ord_aleph_0, cardinal.lt_ord, lt_aleph_0, card_eq_nat] theorem nat_lt_omega (n : ℕ) : ↑n < ω := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < ω := nat_lt_omega 0 theorem omega_ne_zero : ω ≠ 0 := omega_pos.ne' theorem one_lt_omega : 1 < ω := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit ω := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal} : ω ≤ o ↔ ∀ n : ℕ, ↑n ≤ o := ⟨λ h n, (nat_lt_omega _).le.trans h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ←succ_le_iff]; exact H (n+1)⟩ @[simp] theorem sup_nat_cast : sup nat.cast = ω := (sup_le $ λ n, (nat_lt_omega n).le).antisymm $ omega_le.2 $ le_sup _ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, ↑n < o | 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : ω ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ ω ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / ω, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [←div_lt omega_ne_zero, ←succ_le_iff, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact (add_le_add_right (mul_div_le _ _) _).trans (lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _).le }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (ordinal.pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply (mul_le_mul_left' (le_succ c') _).trans, rw IH _ h, apply (add_le_add_left _ _).trans, { rw ← mul_succ, exact mul_le_mul_left' (succ_le_of_lt $ l.2 _ h) _ }, { apply_instance }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right' (le_add_right _ _) _) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem add_le_of_forall_add_lt {a b c : ordinal} (hb : 0 < b) (h : ∀ d < b, a + d < c) : a + b ≤ c := begin have H : a + (c - a) = c := ordinal.add_sub_cancel_of_le (by {rw ←add_zero a, exact (h _ hb).le}), rw ←H, apply add_le_add_left _ a, by_contra' hb, exact (h _ hb).ne H end theorem is_normal.apply_omega {f : ordinal.{u} → ordinal.{u}} (hf : is_normal f) : sup.{0 u} (f ∘ nat.cast) = f ω := by rw [←sup_nat_cast, is_normal.sup.{0 u u} hf] @[simp] theorem sup_add_nat (o : ordinal) : sup (λ n : ℕ, o + n) = o + ω := (add_is_normal o).apply_omega @[simp] theorem sup_mul_nat (o : ordinal) : sup (λ n : ℕ, o * n) = o * ω := begin rcases eq_zero_or_pos o with rfl | ho, { rw zero_mul, exact sup_eq_zero_iff.2 (λ n, zero_mul n) }, { exact (mul_is_normal ho).apply_omega } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem sup_opow_nat {o : ordinal} (ho : 0 < o) : sup (λ n : ℕ, o ^ n) = o ^ ω := begin rcases lt_or_eq_of_le (one_le_iff_pos.2 ho) with ho₁ | rfl, { exact (opow_is_normal ho₁).apply_omega }, { rw one_opow, refine le_antisymm (sup_le (λ n, by rw one_opow)) _, convert le_sup _ 0, rw [nat.cast_zero, opow_zero] } end end ordinal
14d7df71920969e932948332b82d2030a4e98a09
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/tensor_product.lean
5b90fad0faae3045fd6a57415a4ef4b4031248bc
[ "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
16,523
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import linear_algebra.tensor_product import algebra.algebra.basic /-! # The tensor product of R-algebras We construct the R-algebra structure on `A ⊗[R] B`, when `A` and `B` are both `R`-algebras, and provide the structure isomorphisms * `R ⊗[R] A ≃ₐ[R] A` * `A ⊗[R] R ≃ₐ[R] A` * `A ⊗[R] B ≃ₐ[R] B ⊗[R] A` The code for * `((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C))` is written and compiles, but takes longer than the `-T100000` time limit, so is currently commented out. -/ universes u v₁ v₂ v₃ v₄ namespace algebra open_locale tensor_product open tensor_product namespace tensor_product section semiring variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, for a fixed pure tensor in the first argument, as an `R`-linear map. -/ def mul_aux (a₁ : A) (b₁ : B) : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) := begin -- Why doesn't `apply tensor_product.lift` work? apply @tensor_product.lift R _ A B (A ⊗[R] B) _ _ _ _ _ _ _, fsplit, intro a₂, fsplit, intro b₂, exact (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂), { intros b₂ b₂', simp [mul_add, tmul_add], }, { intros c b₂, simp [mul_smul, tmul_smul], }, { intros a₂ a₂', ext b₂, simp [mul_add, add_tmul], }, { intros c a₂, ext b₂, simp [mul_smul, smul_tmul], } end @[simp] lemma mul_aux_apply (a₁ a₂ : A) (b₁ b₂ : B) : (mul_aux a₁ b₁) (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, as an `R`-bilinear map. -/ def mul : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) := begin apply @tensor_product.lift R _ A B ((A ⊗[R] B) →ₗ[R] (A ⊗[R] B)) _ _ _ _ _ _ _, fsplit, intro a₁, fsplit, intro b₁, exact mul_aux a₁ b₁, { intros b₁ b₁', -- Why doesn't just `apply tensor_product.ext`, or indeed `ext` work?! apply @tensor_product.ext R _ A B (A ⊗[R] B) _ _ _ _ _ _, intros a₂ b₂, simp [add_mul, tmul_add], }, { intros c b₁, apply @tensor_product.ext R _ A B (A ⊗[R] B) _ _ _ _ _ _, intros a₂ b₂, simp, }, { intros a₁ a₁', ext1 b₁, apply @tensor_product.ext R _ A B (A ⊗[R] B) _ _ _ _ _ _, intros a₂ b₂, simp [add_mul, add_tmul], }, { intros c a₁, ext1 b₁, apply @tensor_product.ext R _ A B (A ⊗[R] B) _ _ _ _ _ _, intros a₂ b₂, simp [smul_tmul], }, end @[simp] lemma mul_apply (a₁ a₂ : A) (b₁ b₂ : B) : mul (a₁ ⊗ₜ[R] b₁) (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl lemma mul_assoc' (mul : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) →ₗ[R] (A ⊗[R] B)) (h : ∀ (a₁ a₂ a₃ : A) (b₁ b₂ b₃ : B), mul (mul (a₁ ⊗ₜ[R] b₁) (a₂ ⊗ₜ[R] b₂)) (a₃ ⊗ₜ[R] b₃) = mul (a₁ ⊗ₜ[R] b₁) (mul (a₂ ⊗ₜ[R] b₂) (a₃ ⊗ₜ[R] b₃))) : ∀ (x y z : A ⊗[R] B), mul (mul x y) z = mul x (mul y z) := begin intros, apply tensor_product.induction_on x, { simp, }, apply tensor_product.induction_on y, { simp, }, apply tensor_product.induction_on z, { simp, }, { intros, simp [h], }, { intros, simp [linear_map.map_add, *], }, { intros, simp [linear_map.map_add, *], }, { intros, simp [linear_map.map_add, *], }, end lemma mul_assoc (x y z : A ⊗[R] B) : mul (mul x y) z = mul x (mul y z) := mul_assoc' mul (by { intros, simp only [mul_apply, mul_assoc], }) x y z lemma one_mul (x : A ⊗[R] B) : mul (1 ⊗ₜ 1) x = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end lemma mul_one (x : A ⊗[R] B) : mul x (1 ⊗ₜ 1) = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end instance : semiring (A ⊗[R] B) := { zero := 0, add := (+), one := 1 ⊗ₜ 1, mul := λ a b, mul a b, one_mul := one_mul, mul_one := mul_one, mul_assoc := mul_assoc, zero_mul := by simp, mul_zero := by simp, left_distrib := by simp, right_distrib := by simp, .. (by apply_instance : add_comm_monoid (A ⊗[R] B)) }. lemma one_def : (1 : A ⊗[R] B) = (1 : A) ⊗ₜ (1 : B) := rfl @[simp] lemma tmul_mul_tmul (a₁ a₂ : A) (b₁ b₂ : B) : (a₁ ⊗ₜ[R] b₁) * (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl @[simp] lemma tmul_pow (a : A) (b : B) (k : ℕ) : (a ⊗ₜ[R] b)^k = (a^k) ⊗ₜ[R] (b^k) := begin induction k with k ih, { simp [one_def], }, { simp [pow_succ, ih], } end /-- The algebra map `R →+* (A ⊗[R] B)` giving `A ⊗[R] B` the structure of an `R`-algebra. -/ def tensor_algebra_map : R →+* (A ⊗[R] B) := { to_fun := λ r, algebra_map R A r ⊗ₜ[R] 1, map_one' := by { simp, refl }, map_mul' := by simp, map_zero' := by simp [zero_tmul], map_add' := by simp [add_tmul], } instance : algebra R (A ⊗[R] B) := { commutes' := λ r x, begin apply tensor_product.induction_on x, { simp, }, { intros a b, simp [tensor_algebra_map, algebra.commutes], }, { intros y y' h h', simp at h h', simp [mul_add, add_mul, h, h'], }, end, smul_def' := λ r x, begin apply tensor_product.induction_on x, { simp [smul_zero], }, { intros a b, rw [tensor_algebra_map, ←tmul_smul, ←smul_tmul, algebra.smul_def r a], simp, }, { intros, dsimp, simp [smul_add, mul_add, *], }, end, .. tensor_algebra_map, .. (by apply_instance : semimodule R (A ⊗[R] B)) }. @[simp] lemma algebra_map_apply (r : R) : (algebra_map R (A ⊗[R] B)) r = ((algebra_map R A) r) ⊗ₜ[R] 1 := rfl variables {C : Type v₃} [semiring C] [algebra R C] @[ext] theorem ext {g h : (A ⊗[R] B) →ₐ[R] C} (H : ∀ a b, g (a ⊗ₜ b) = h (a ⊗ₜ b)) : g = h := begin apply @alg_hom.to_linear_map_inj R (A ⊗[R] B) C _ _ _ _ _ _ _ _, ext, simp [H], end /-- The algebra morphism `A →ₐ[R] A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/ def include_left : A →ₐ[R] A ⊗[R] B := { to_fun := λ a, a ⊗ₜ 1, map_zero' := by simp, map_add' := by simp [add_tmul], map_one' := rfl, map_mul' := by simp, commutes' := by simp, } @[simp] lemma include_left_apply (a : A) : (include_left : A →ₐ[R] A ⊗[R] B) a = a ⊗ₜ 1 := rfl /-- The algebra morphism `B →ₐ[R] A ⊗[R] B` sending `b` to `1 ⊗ₜ b`. -/ def include_right : B →ₐ[R] A ⊗[R] B := { to_fun := λ b, 1 ⊗ₜ b, map_zero' := by simp, map_add' := by simp [tmul_add], map_one' := rfl, map_mul' := by simp, commutes' := λ r, begin simp only [algebra_map_apply], transitivity r • ((1 : A) ⊗ₜ[R] (1 : B)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end, } @[simp] lemma include_right_apply (b : B) : (include_right : B →ₐ[R] A ⊗[R] B) b = 1 ⊗ₜ b := rfl end semiring section ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [ring A] [algebra R A] variables {B : Type v₂} [ring B] [algebra R B] instance : ring (A ⊗[R] B) := { .. (by apply_instance : add_comm_group (A ⊗[R] B)), .. (by apply_instance : semiring (A ⊗[R] B)) }. end ring section comm_ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [comm_ring A] [algebra R A] variables {B : Type v₂} [comm_ring B] [algebra R B] instance : comm_ring (A ⊗[R] B) := { mul_comm := λ x y, begin apply tensor_product.induction_on x, { simp, }, { intros a₁ b₁, apply tensor_product.induction_on y, { simp, }, { intros a₂ b₂, simp [mul_comm], }, { intros a₂ b₂ ha hb, simp [mul_add, add_mul, ha, hb], }, }, { intros x₁ x₂ h₁ h₂, simp [mul_add, add_mul, h₁, h₂], }, end .. (by apply_instance : ring (A ⊗[R] B)) }. end comm_ring /-- Verify that typeclass search finds the ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely rings, by treating both as `ℤ`-algebras. -/ example {A : Type v₁} [ring A] {B : Type v₂} [ring B] : ring (A ⊗[ℤ] B) := by apply_instance /-- Verify that typeclass search finds the comm_ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely comm_rings, by treating both as `ℤ`-algebras. -/ example {A : Type v₁} [comm_ring A] {B : Type v₂} [comm_ring B] : comm_ring (A ⊗[ℤ] B) := by apply_instance /-! We now build the structure maps for the symmetric monoidal category of `R`-algebras. -/ section monoidal section variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type v₄} [semiring D] [algebra R D] /-- Build an algebra morphism from a linear map out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_hom_of_linear_map_tensor_product (f : A ⊗[R] B →ₗ[R] C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂)) = f (a₁ ⊗ₜ b₁) * f (a₂ ⊗ₜ b₂)) (w₂ : ∀ r, f ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R C) r): A ⊗[R] B →ₐ[R] C := { map_one' := by simpa using w₂ 1, map_zero' := by simp, map_mul' := λ x y, begin apply tensor_product.induction_on x, { simp, }, { intros a₁ b₁, apply tensor_product.induction_on y, { simp, }, { intros a₂ b₂, simp [w₁], }, { intros x₁ x₂ h₁ h₂, simp at h₁, simp at h₂, simp [mul_add, add_mul, h₁, h₂], }, }, { intros x₁ x₂ h₁ h₂, simp at h₁, simp at h₂, simp [mul_add, add_mul, h₁, h₂], } end, commutes' := λ r, by simp [w₂], .. f } @[simp] lemma alg_hom_of_linear_map_tensor_product_apply (f w₁ w₂ x) : (alg_hom_of_linear_map_tensor_product f w₁ w₂ : A ⊗[R] B →ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_tensor_product (f : A ⊗[R] B ≃ₗ[R] C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂)) = f (a₁ ⊗ₜ b₁) * f (a₂ ⊗ₜ b₂)) (w₂ : ∀ r, f ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R C) r): A ⊗[R] B ≃ₐ[R] C := { .. alg_hom_of_linear_map_tensor_product (f : A ⊗[R] B →ₗ[R] C) w₁ w₂, .. f } @[simp] lemma alg_equiv_of_linear_equiv_tensor_product_apply (f w₁ w₂ x) : (alg_equiv_of_linear_equiv_tensor_product f w₁ w₂ : A ⊗[R] B ≃ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a triple tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_triple_tensor_product (f : ((A ⊗[R] B) ⊗[R] C) ≃ₗ[R] D) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂) ⊗ₜ (c₁ * c₂)) = f (a₁ ⊗ₜ b₁ ⊗ₜ c₁) * f (a₂ ⊗ₜ b₂ ⊗ₜ c₂)) (w₂ : ∀ r, f (((algebra_map R A) r ⊗ₜ[R] (1 : B)) ⊗ₜ[R] (1 : C)) = (algebra_map R D) r) : (A ⊗[R] B) ⊗[R] C ≃ₐ[R] D := { to_fun := f, map_mul' := λ x y, begin apply tensor_product.induction_on x, { simp, }, { intros ab₁ c₁, apply tensor_product.induction_on y, { simp, }, { intros ab₂ c₂, apply tensor_product.induction_on ab₁, { simp, }, { intros a₁ b₁, apply tensor_product.induction_on ab₂, { simp, }, { simp [w₁], }, { intros x₁ x₂ h₁ h₂, simp at h₁ h₂, simp [mul_add, add_tmul, h₁, h₂], }, }, { intros x₁ x₂ h₁ h₂, simp at h₁ h₂, simp [add_mul, add_tmul, h₁, h₂], }, }, { intros x₁ x₂ h₁ h₂, simp [mul_add, add_mul, h₁, h₂], }, }, { intros x₁ x₂ h₁ h₂, simp [mul_add, add_mul, h₁, h₂], } end, commutes' := λ r, by simp [w₂], .. f } @[simp] lemma alg_equiv_of_linear_equiv_triple_tensor_product_apply (f w₁ w₂ x) : (alg_equiv_of_linear_equiv_triple_tensor_product f w₁ w₂ : (A ⊗[R] B) ⊗[R] C ≃ₐ[R] D) x = f x := rfl end variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type v₄} [semiring D] [algebra R D] section variables (R A) /-- The base ring is a left identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def lid : R ⊗[R] A ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.lid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem lid_tmul (r : R) (a : A) : (tensor_product.lid R A : (R ⊗ A → A)) (r ⊗ₜ a) = r • a := by simp [tensor_product.lid] /-- The base ring is a right identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def rid : A ⊗[R] R ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.rid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem rid_tmul (r : R) (a : A) : (tensor_product.rid R A : (A ⊗ R → A)) (a ⊗ₜ r) = r • a := by simp [tensor_product.rid] section variables (R A B) /-- The tensor product of R-algebras is commutative, up to algebra isomorphism. -/ protected def comm : A ⊗[R] B ≃ₐ[R] B ⊗[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.comm R A B) (by simp) (λ r, begin transitivity r • ((1 : B) ⊗ₜ[R] (1 : A)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end) @[simp] theorem comm_tmul (a : A) (b : B) : (tensor_product.comm R A B : (A ⊗[R] B → B ⊗[R] A)) (a ⊗ₜ b) = (b ⊗ₜ a) := by simp [tensor_product.comm] end section variables {R A B C} lemma assoc_aux_1 (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C) : (tensor_product.assoc R A B C) (((a₁ * a₂) ⊗ₜ[R] (b₁ * b₂)) ⊗ₜ[R] (c₁ * c₂)) = (tensor_product.assoc R A B C) ((a₁ ⊗ₜ[R] b₁) ⊗ₜ[R] c₁) * (tensor_product.assoc R A B C) ((a₂ ⊗ₜ[R] b₂) ⊗ₜ[R] c₂) := rfl lemma assoc_aux_2 (r : R) : (tensor_product.assoc R A B C) (((algebra_map R A) r ⊗ₜ[R] 1) ⊗ₜ[R] 1) = (algebra_map R (A ⊗ (B ⊗ C))) r := rfl -- variables (R A B C) -- -- local attribute [elab_simple] alg_equiv_of_linear_equiv_triple_tensor_product -- /-- The associator for tensor product of R-algebras, as an algebra isomorphism. -/ -- -- FIXME This is _really_ slow to compile. :-( -- protected def assoc : ((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C)) := -- alg_equiv_of_linear_equiv_triple_tensor_product -- (tensor_product.assoc R A B C) -- assoc_aux_1 assoc_aux_2 -- variables {R A B C} -- @[simp] theorem assoc_tmul (a : A) (b : B) (c : C) : -- ((tensor_product.assoc R A B C) : -- (A ⊗[R] B) ⊗[R] C → A ⊗[R] (B ⊗[R] C)) ((a ⊗ₜ b) ⊗ₜ c) = a ⊗ₜ (b ⊗ₜ c) := -- rfl end variables {R A B C D} /-- The tensor product of a pair of algebra morphisms. -/ def map (f : A →ₐ[R] B) (g : C →ₐ[R] D) : A ⊗[R] C →ₐ[R] B ⊗[R] D := alg_hom_of_linear_map_tensor_product (tensor_product.map f.to_linear_map g.to_linear_map) (by simp) (by simp [alg_hom.commutes]) @[simp] theorem map_tmul (f : A →ₐ[R] B) (g : C →ₐ[R] D) (a : A) (c : C) : map f g (a ⊗ₜ c) = f a ⊗ₜ g c := rfl /-- Construct an isomorphism between tensor products of R-algebras from isomorphisms between the tensor factors. -/ def congr (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) : A ⊗[R] C ≃ₐ[R] B ⊗[R] D := alg_equiv.of_alg_hom (map f g) (map f.symm g.symm) (ext $ λ b d, by simp) (ext $ λ a c, by simp) @[simp] lemma congr_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : congr f g x = (map (f : A →ₐ[R] B) (g : C →ₐ[R] D)) x := rfl @[simp] lemma congr_symm_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : (congr f g).symm x = (map (f.symm : B →ₐ[R] A) (g.symm : D →ₐ[R] C)) x := rfl end end monoidal end tensor_product end algebra
e21cec66e12eabf88dcc380cd5cc32e74d0f9f04
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/data/polynomial/degree/definitions.lean
ec3620b7fdebda92750e0414fd22339d38bc2c69
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,084
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import data.nat.with_bot /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} section semiring variables [semiring R] {p q r : polynomial R} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : polynomial R) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff alias polynomial.nat_degree_le_iff_degree_le ↔ . . lemma nat_degree_le_nat_degree (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial _ _ ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree_monomial n ha] lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial (i : ℕ) (r : R) (hr : r ≠ 0) : nat_degree (monomial i r) = i := by rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : polynomial R} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : polynomial R) : p = ∑ i in p.support, monomial i (p.coeff i) := p.sum_single.symm lemma as_sum_support_C_mul_X_pow (p : polynomial R) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := finsupp.sum_of_support_subset _ (supp_subset_range w) _ $ λ n hn, h n /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) lemma as_sum_range' (p : polynomial R) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range' (λ n, single_zero) _ w lemma as_sum_range (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_single.symm.trans $ p.sum_over_range $ λ n, single_zero lemma as_sum_range_C_mul_X_pow (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : polynomial R) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : polynomial R).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_subset end lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow _ _ h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma card_supp_le_succ_nat_degree (p : polynomial R) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff_coeff_ne_zero.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_single_ne_zero h end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : polynomial R).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] lemma C_eq_int_cast (n : ℤ) : C (n : R) = n := (C : R →+* _).map_int_cast n @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : polynomial R) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : polynomial R) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } end semiring section semiring variables [semiring R] {p q : polynomial R} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := (p.mem_support_to_fun p.nat_degree).mpr ((not_congr leading_coeff_eq_zero).mpr H) lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := begin apply le_antisymm, { apply finset.le_max', rw mem_support_iff_coeff_ne_zero, exact (not_congr leading_coeff_eq_zero).mpr h, }, { apply max'_le, refine le_nat_degree_of_mem_supp, }, end lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial _ _ ha], exact @finsupp.single_eq_same _ _ _ n a } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : polynomial R) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : polynomial R) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma degree_mul_monic (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_mul_monic {p q : polynomial R} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : polynomial R} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← le_zero_iff_eq, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem degree_lt_iff_coeff_zero (f : polynomial R) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ], exact λ h m, mt (h m), end lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero {p : polynomial R} (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero {p : polynomial R} (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : polynomial R) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] theorem not_is_unit_X : ¬ is_unit (X : polynomial R) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [degree_mul_monic monic_X] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [degree_mul_monic (monic_X_pow n)] end nonzero_semiring section ring variables [ring R] {p q : polynomial R} lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase _ _, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : (@finset.fold_hom _ _ _ (⊔) _ _ _ ⊥ finset.univ _ _ _ id (with_bot.sup_eq_max)).symm ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_some _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] [ring R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := have degree (C a) < degree (X : polynomial R), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_sub_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C (c : R) : next_coeff (X - C c) = - c := by simp [next_coeff_of_pos_nat_degree] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (C a) < degree ((X : polynomial R) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_sub_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : polynomial R) ▸ X_pow_sub_C_ne_zero zero_lt_one r lemma nat_degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).nat_degree = n := by { apply nat_degree_eq_of_degree_eq_some, simp [degree_X_pow_sub_C hn], } end nonzero_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_X_add_C (a b : R) (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := begin rw [add_comm, leading_coeff_add_of_degree_lt], { simp }, { simpa [degree_C ha] using lt_of_le_of_lt degree_C_le (with_bot.coe_lt_coe.2 zero_lt_one)} end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` is an `integral_domain`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : polynomial R →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : polynomial R) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := leading_coeff_hom.map_pow p n end integral_domain end polynomial
0512185b6c7b5d27245a336825442f6714079b89
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/real/pi.lean
b1bd8148353ded908d1aa17a977700a04253fe4d
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,463
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Benjamin Davidson -/ import analysis.special_functions.integrals /-! # Pi This file contains lemmas which establish bounds on or approximations of `real.pi`. Notably, these include `pi_gt_sqrt_two_add_series` and `pi_lt_sqrt_two_add_series`, which bound `π` using series; numerical bounds on `π` such as `pi_gt_314`and `pi_lt_315` (more precise versions are given, too); and exact (infinite) formulas involving `π`, such as `tendsto_sum_pi_div_four`, Leibniz's series for `π`, and `tendsto_prod_pi_div_two`, the Wallis product for `π`. -/ open_locale real namespace real lemma pi_gt_sqrt_two_add_series (n : ℕ) : 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) < π := begin have : sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2) < π, { rw [← lt_div_iff, ←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, all_goals { apply pow_pos, norm_num } }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : π < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : π < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [← div_lt_iff, ← sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { rw div_le_iff', { refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, { apply pow_pos, norm_num }}, apply add_le_add_left, rw div_le_div_right, rw [le_div_iff, ←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, rw ← le_div_iff, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div_eq_div_mul], convert le_refl _, all_goals { repeat {apply pow_pos}, norm_num }}, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div_eq_div_mul, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < π` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < π := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine (div_le_iff (pow_pos (by norm_num) _ : (0 : ℝ) < _)).mp (le_sqrt_of_sq_le _), rwa [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg c.cast_nonneg d.cast_nonneg), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < π` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `π < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : π < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_nonneg (le_of_lt zero_lt_two) _) }, { exact pow_pos zero_lt_two _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sq_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `π < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < π := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < π := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : π < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < π := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : π < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < π := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : π < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] /-! ### Leibniz's Series for Pi -/ open filter set open_locale classical big_operators topological_space local notation `|`x`|` := abs x /-- This theorem establishes **Leibniz's series for `π`**: The alternating sum of the reciprocals of the odd numbers is `π/4`. Note that this is a conditionally rather than absolutely convergent series. The main tool that this proof uses is the Mean Value Theorem (specifically avoiding the Fundamental Theorem of Calculus). Intuitively, the theorem holds because Leibniz's series is the Taylor series of `arctan x` centered about `0` and evaluated at the value `x = 1`. Therefore, much of this proof consists of reasoning about a function `f := arctan x - ∑ i in finset.range k, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1)`, the difference between `arctan` and the `k`-th partial sum of its Taylor series. Some ingenuity is required due to the fact that the Taylor series is not absolutely convergent at `x = 1`. This proof requires a bound on `f 1`, the key idea being that `f 1` can be split as the sum of `f 1 - f u` and `f u`, where `u` is a sequence of values in [0,1], carefully chosen such that each of these two terms can be controlled (in different ways). We begin the proof by (1) introducing that sequence `u` and then proving that another sequence constructed from `u` tends to `0` at `+∞`. After (2) converting the limit in our goal to an inequality, we (3) introduce the auxiliary function `f` defined above. Next, we (4) compute the derivative of `f`, denoted by `f'`, first generally and then on each of two subintervals of [0,1]. We then (5) prove a bound for `f'`, again both generally as well as on each of the two subintervals. Finally, we (6) apply the Mean Value Theorem twice, obtaining bounds on `f 1 - f u` and `f u - f 0` from the bounds on `f'` (note that `f 0 = 0`). -/ theorem tendsto_sum_pi_div_four : tendsto (λ k, ∑ i in finset.range k, ((-(1:ℝ))^i / (2*i+1))) at_top (𝓝 (π/4)) := begin rw [tendsto_iff_norm_tendsto_zero, ← tendsto_zero_iff_norm_tendsto_zero], -- (1) We introduce a useful sequence `u` of values in [0,1], then prove that another sequence -- constructed from `u` tends to `0` at `+∞` let u := λ k : ℕ, (k:nnreal) ^ (-1 / (2 * (k:ℝ) + 1)), have H : tendsto (λ k : ℕ, (1:ℝ) - (u k) + (u k) ^ (2 * (k:ℝ) + 1)) at_top (𝓝 0), { convert (((tendsto_rpow_div_mul_add (-1) 2 1 two_ne_zero.symm).neg.const_add 1).add tendsto_inv_at_top_zero).comp tendsto_coe_nat_at_top_at_top, { ext k, simp only [nnreal.coe_nat_cast, function.comp_app, nnreal.coe_rpow], rw [← rpow_mul (nat.cast_nonneg k) ((-1)/(2*(k:ℝ)+1)) (2*(k:ℝ)+1), @div_mul_cancel _ _ _ (2*(k:ℝ)+1) (by { norm_cast, simp only [nat.succ_ne_zero, not_false_iff] }), rpow_neg_one k, sub_eq_add_neg] }, { simp only [add_zero, add_right_neg] } }, -- (2) We convert the limit in our goal to an inequality refine squeeze_zero_norm _ H, intro k, -- Since `k` is now fixed, we henceforth denote `u k` as `U` let U := u k, -- (3) We introduce an auxiliary function `f` let b := λ (i:ℕ) x, (-(1:ℝ))^i * x^(2*i+1) / (2*i+1), let f := λ x, arctan x - (∑ i in finset.range k, b i x), suffices f_bound : |f 1 - f 0| ≤ (1:ℝ) - U + U ^ (2 * (k:ℝ) + 1), { rw ← norm_neg, convert f_bound, simp only [f], simp [b] }, -- We show that `U` is indeed in [0,1] have hU1 : (U:ℝ) ≤ 1, { by_cases hk : k = 0, { simpa only [U, hk] using zero_rpow_le_one _ }, { exact rpow_le_one_of_one_le_of_nonpos (by { norm_cast, exact nat.succ_le_iff.mpr (nat.pos_of_ne_zero hk) }) (le_of_lt (@div_neg_of_neg_of_pos _ _ (-(1:ℝ)) (2*k+1) (neg_neg_iff_pos.mpr zero_lt_one) (by { norm_cast, exact nat.succ_pos' }))) } }, have hU2 := nnreal.coe_nonneg U, -- (4) We compute the derivative of `f`, denoted by `f'` let f' := λ x : ℝ, (-x^2) ^ k / (1 + x^2), have has_deriv_at_f : ∀ x, has_deriv_at f (f' x) x, { intro x, have has_deriv_at_b : ∀ i ∈ finset.range k, (has_deriv_at (b i) ((-x^2)^i) x), { intros i hi, convert has_deriv_at.const_mul ((-1:ℝ)^i / (2*i+1)) (@has_deriv_at.pow _ _ _ _ _ (2*i+1) (has_deriv_at_id x)), { ext y, simp only [b, id.def], ring }, { simp only [nat.add_succ_sub_one, add_zero, mul_one, id.def, nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], rw [← mul_assoc, @div_mul_cancel _ _ _ (2*(i:ℝ)+1) (by { norm_cast, linarith }), pow_mul x 2 i, ← mul_pow (-1) (x^2) i], ring_nf } }, convert (has_deriv_at_arctan x).sub (has_deriv_at.sum has_deriv_at_b), have g_sum := @geom_sum_eq _ _ (-x^2) ((neg_nonpos.mpr (sq_nonneg x)).trans_lt zero_lt_one).ne k, simp only [geom_sum, f'] at g_sum ⊢, rw [g_sum, ← neg_add' (x^2) 1, add_comm (x^2) 1, sub_eq_add_neg, neg_div', neg_div_neg_eq], ring }, have hderiv1 : ∀ x ∈ Icc (U:ℝ) 1, has_deriv_within_at f (f' x) (Icc (U:ℝ) 1) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, have hderiv2 : ∀ x ∈ Icc 0 (U:ℝ), has_deriv_within_at f (f' x) (Icc 0 (U:ℝ)) x := λ x hx, (has_deriv_at_f x).has_deriv_within_at, -- (5) We prove a general bound for `f'` and then more precise bounds on each of two subintervals have f'_bound : ∀ x ∈ Icc (-1:ℝ) 1, |f' x| ≤ |x|^(2*k), { intros x hx, rw [abs_div, is_absolute_value.abv_pow abs (-x^2) k, abs_neg, is_absolute_value.abv_pow abs x 2, tactic.ring_exp.pow_e_pf_exp rfl rfl], refine div_le_of_nonneg_of_le_mul (abs_nonneg _) (pow_nonneg (abs_nonneg _) _) _, refine le_mul_of_one_le_right (pow_nonneg (abs_nonneg _) _) _, rw abs_of_nonneg ((add_nonneg zero_le_one (sq_nonneg x)) : (0 : ℝ) ≤ _), exact (le_add_of_nonneg_right (sq_nonneg x) : (1 : ℝ) ≤ _) }, have hbound1 : ∀ x ∈ Ico (U:ℝ) 1, |f' x| ≤ 1, { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left (le_trans hU2 hx_left) (le_of_lt hx_right) (2*k), rw [one_pow (2*k), ← abs_of_nonneg (le_trans hU2 hx_left)] at hincr, rw ← abs_of_nonneg (le_trans hU2 hx_left) at hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_of_lt hx_right)))] }, have hbound2 : ∀ x ∈ Ico 0 (U:ℝ), |f' x| ≤ U ^ (2*k), { rintros x ⟨hx_left, hx_right⟩, have hincr := pow_le_pow_of_le_left hx_left (le_of_lt hx_right) (2*k), rw ← abs_of_nonneg hx_left at hincr hx_right, rw ← abs_of_nonneg hU2 at hU1 hx_right, linarith [f'_bound x (mem_Icc.mpr (abs_le.mp (le_trans (le_of_lt hx_right) hU1)))] }, -- (6) We twice apply the Mean Value Theorem to obtain bounds on `f` from the bounds on `f'` have mvt1 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv1 hbound1 _ (right_mem_Icc.mpr hU1), have mvt2 := norm_image_sub_le_of_norm_deriv_le_segment' hderiv2 hbound2 _ (right_mem_Icc.mpr hU2), -- The following algebra is enough to complete the proof calc |f 1 - f 0| = |(f 1 - f U) + (f U - f 0)| : by ring_nf ... ≤ 1 * (1-U) + U^(2*k) * (U - 0) : le_trans (abs_add (f 1 - f U) (f U - f 0)) (add_le_add mvt1 mvt2) ... = 1 - U + U^(2*k) * U : by ring ... = 1 - (u k) + (u k)^(2*(k:ℝ)+1) : by { rw [← pow_succ' (U:ℝ) (2*k)], norm_cast }, end /-! ### The Wallis Product for Pi -/ open finset interval_integral lemma integral_sin_pow_div_tendsto_one : tendsto (λ k, (∫ x in 0..π, sin x ^ (2 * k + 1)) / ∫ x in 0..π, sin x ^ (2 * k)) at_top (𝓝 1) := begin have h₃ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≤ 1 := λ n, (div_le_one (integral_sin_pow_pos _)).mpr (integral_sin_pow_antimono _), have h₄ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≥ 2 * n / (2 * n + 1), { rintro ⟨n⟩, { have : 0 ≤ (1 + 1) / π, exact div_nonneg (by norm_num) pi_pos.le, simp [this] }, calc (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n.succ) ≥ (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n + 1) : by { refine div_le_div (integral_sin_pow_pos _).le (le_refl _) (integral_sin_pow_pos _) _, convert integral_sin_pow_antimono (2 * n + 1) using 1 } ... = 2 * ↑(n.succ) / (2 * ↑(n.succ) + 1) : by { rw div_eq_iff (integral_sin_pow_pos (2 * n + 1)).ne', convert integral_sin_pow (2 * n + 1), simp with field_simps, norm_cast } }, refine tendsto_of_tendsto_of_tendsto_of_le_of_le _ _ (λ n, (h₄ n).le) (λ n, (h₃ n)), { refine metric.tendsto_at_top.mpr (λ ε hε, ⟨⌈1 / ε⌉₊, λ n hn, _⟩), have h : (2:ℝ) * n / (2 * n + 1) - 1 = -1 / (2 * n + 1), { conv_lhs { congr, skip, rw ← @div_self _ _ ((2:ℝ) * n + 1) (by { norm_cast, linarith }), }, rw [← sub_div, ← sub_sub, sub_self, zero_sub] }, have hpos : (0:ℝ) < 2 * n + 1, { norm_cast, norm_num }, rw [dist_eq, h, abs_div, abs_neg, abs_one, abs_of_pos hpos, one_div_lt hpos hε], calc 1 / ε ≤ ⌈1 / ε⌉₊ : le_nat_ceil _ ... ≤ n : by exact_mod_cast hn.le ... < 2 * n + 1 : by { norm_cast, linarith } }, { exact tendsto_const_nhds }, end /-- This theorem establishes the Wallis Product for `π`. Our proof is largely about analyzing the behavior of the ratio of the integral of `sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. (Pieces involving general properties of the integral of `sin x ^n` can be found in `analysis.special_functions.integrals`.) First, we use integration by parts to obtain a recursive formula for `∫ x in 0..π, sin x ^ (n + 2)` in terms of `∫ x in 0..π, sin x ^ n`. From this we can obtain closed form products of `∫ x in 0..π, sin x ^ (2 * n)` and `∫ x in 0..π, sin x ^ (2 * n + 1)` via induction. Next, we study the behavior of the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1)) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. -/ theorem tendsto_prod_pi_div_two : tendsto (λ k, ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 (π/2)) := begin suffices h : tendsto (λ k, 2 / π * ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 1), { have := tendsto.const_mul (π / 2) h, have h : π / 2 ≠ 0, norm_num [pi_ne_zero], simp only [← mul_assoc, ← @inv_div _ _ π 2, mul_inv_cancel h, one_mul, mul_one] at this, exact this }, have h : (λ (k : ℕ), (2:ℝ) / π * ∏ (i : ℕ) in range k, ((2 * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) = λ k, (2 * ∏ i in range k, (2 * i + 2) / (2 * i + 3)) / (π * ∏ (i : ℕ) in range k, (2 * i + 1) / (2 * i + 2)), { funext, have h : ∏ (i : ℕ) in range k, ((2:ℝ) * ↑i + 2) / (2 * ↑i + 1) = 1 / (∏ (i : ℕ) in range k, (2 * ↑i + 1) / (2 * ↑i + 2)), { rw [one_div, ← finset.prod_inv_distrib'], refine prod_congr rfl (λ x hx, _), field_simp }, rw [prod_mul_distrib, h], field_simp }, simp only [h, ← integral_sin_pow_even, ← integral_sin_pow_odd], exact integral_sin_pow_div_tendsto_one, end end real
a549303756d9f6cf90d090b18e41878a59778953
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/calculus/parametric_interval_integral.lean
03a19aa2a3649cbb2125ba0eb1780aedab8dbf51
[ "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,550
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.parametric_integral import measure_theory.integral.interval_integral /-! # Derivatives of interval integrals depending on parameters In this file we restate theorems about derivatives of integrals depending on parameters for interval integrals. -/ open topological_space measure_theory filter metric open_locale topological_space filter interval variables {𝕜 : Type*} [is_R_or_C 𝕜] {μ : measure ℝ} {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [normed_space 𝕜 E] [complete_space E] {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {a b ε : ℝ} {bound : ℝ → ℝ} namespace interval_integral /-- Differentiation under integral of `x ↦ ∫ t in a..b, F x t` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_loc_of_lip {F : H → ℝ → E} {F' : ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lip : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_fderiv_at (λ x, F x t) (F' t) x₀) : interval_integrable F' μ a b ∧ has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lip bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_of_fderiv_le {F : H → ℝ → E} {F' : H → ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ‖F' x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x t) (F' x t) x) : has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, exact (has_fderiv_at_integral_of_dominated_of_fderiv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff).const_smul _ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_lip {F : 𝕜 → ℝ → E} {F' : ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lipsch : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable (bound : ℝ → ℝ) μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_deriv_at (λ x, F x t) (F' t) x₀) : (interval_integrable F' μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_deriv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lipsch bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_deriv_le {F : 𝕜 → ℝ → E} {F' : 𝕜 → ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ‖F' x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x t) (F' x t) x) : (interval_integrable (F' x₀) μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_deriv_at_integral_of_dominated_loc_of_deriv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end end interval_integral
2a822ecf4c3b376091089f13d7e8ee5afb42dcd2
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/instructor/lectures/lecture_20.lean
2983d542d9f002068ccc5952c92c65fef59a5af4
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
8,871
lean
import data.set /- The preceding import statement imports definitions for set theory beyond those that are included in the libraries that are loaded by default when Lean starts. -/ /- We've now seen how sets correspond in very close ways) to one-place predicates. This correspondence allows us to "reduce" the language of set theory to the language of predicate logic (here, in Lean). That, in turn, let's use predicate logic and our proof building and checking machinery to write propositions *in set theory* and to develop and automatically check proofs. -/ /- We will continue in this vein as we now consider a powerful generalization. If a one-place predicate can represent a set of individual values, a two-place predicate can represent a set of pairs of values. A three-place predicate can represent a set of 3-tuples of values. Etc. We call such sets *relations*. Here's an example: consider the set of pairs of natural numbers, where in each pair the second number is exactly one more than the first number, and where the first numbers are 0, 1, and 2. The set of pairs that satisfies this specifications is { (0, 1), (1, 2), (2, 3) }. Here's another example. Suppose α is string and β is nat. We can specify a *relation* between strings and natural numbers, where a pair, p = (s, n), is in the relation if an only if n is the length of s (in that specific pair). Here are some "tuples" (pairs in this case) that would be "in" this relation: ("Yo",2), ("Lean",4), ("Rocks!",6). A pair that is excluded is ("Naw!",5), as 5 is not equal to the length of "Naw!". We haven't give an algorithm here to *compute* the elements of this relation, but we have precisely *specified* what it is (as long as we properly define nat, string, length; we'll get there). -/ /- The idea that you should now have in mind is that we can represent a "binary relation on α ⨯ β", which mathematically is a set of α-β pairs, as a two-place predicate. We can then *verify* that any given pair is in the relation (if it is) by producing a proof of that fact. -/ /- EXAMPLE: equality To further ground the discussion, let's return to the equality relation. For any type, α, we have an equality relation. If α is ℕ, for example, then we have equality defined on the natural numbers. Some pairs that would be "in" the relation are in the set: {(0, 0), (1, 1), ..., (n,n), ...}. Pairs that would not be in the relation include (1, 2), (3, 9), and so forth. -/ #check @eq nat #check @eq string #check @eq bool /- The way we assure these properties is by defining new introduction axioms for a given relation in such a way that they can construct all and only the proofs that should be true. For example, eq.refl takes a single argument, e.g., n, and in return produces a proof of n = n. That's all the introduction rules for eq, and so anything can be proved equal to itself and no other equality proposition are provable. We haven't seen how to define predicates with associated proof construction rules, yet, but we will when we see how to define our own types (propositions are types and predicates are thus types with parameters). Suffice it to say for now that different relations will have different introduction rules! -/ /- Let's now visualize the set of all pairs of type ℕ ⨯ ℕ. Again, ℕ ⨯ ℕ is a type. It is the type of *pairs*, such as (p.1, p.2), where each of p.1 and p.2 are of type ℕ. Just think of a 2-D table, with natural numbers going up from zero across the top and the same down the left side. The pairs correspond to the cells where the rows and columns intersect in the table. Eventually every possible pair appears in the table. A relation is a *subset* of all such pairs, namely all and only those pairs that satisfy the membership predicate for the relation: just as with sets! In mathematical writing we will therefore often see definitions like this: Let R ⊆ ℕ × ℕ be a binary relation such that ∀ (n m ∈ ℕ), (m, n) ∈ R ↔ n = m + 1. Note that we're using "ordered pair notation" to represent pairs, i.e., values in ℕ × ℕ in this case. Lean supports these standard notations. -/ -- Here's a product type #check ℕ × ℕ -- Here's a value of this type #check (1, 1) /- And here are some relations. Take a minute to read and understand exactly what pairs are in each of these sets, and express your answers in English. -/ #check { p : ℕ × ℕ | p.1 <= p.2 } #check { p : ℕ × ℕ | p.2 = p.1 * p.1 } #check { p : string × ℕ | p.2 = string.length p.1} /- What we've now got again is a "reduction" from the mathematical concept of sets to predicate logic. We can then use logic to *verify* that a particular pair is or is not in a particular relation using all of our usual theorem proving tools! -/ example : (1, 1) ∈ { p : ℕ × ℕ | p.1 <= p.2 } := begin show { p : ℕ × ℕ | p.1 <= p.2 } (1, 1), -- apply predicate show 1 <= 1, -- proposition exact nat.less_than_or_equal.refl, -- proof end /- In English, the proposition is true by the reflexive property of ≤. -/ example : (3, 9) ∈ { p : ℕ × ℕ | p.2 = p.1 * p.1 } := begin show 9 = 3 * 3, exact rfl, end /- In English, the proposition is true by the reflexive property of =. -/ example : ("Hello", 5) ∈ { p : string × ℕ | p.2 = string.length p.1} := begin exact rfl, end -- Proof by reflexivity of =. example : (3, 10) ∈ { p : ℕ × ℕ | p.2 = p.1 * p.1 } := begin show 10 = 3 * 3, exact rfl, -- stuck end -- stuck (in fact it's provably false) example : (3, 10) ∈ compl { p : ℕ × ℕ | p.2 = p.1 * p.1 } := begin show ¬10=9, assume h, cases h, end -- Proof by negation and the reflexive property of =. /- Now please do this: take out a piece of paper and a pencil or pen draw the first 4 or 5 rows and columns to make a grid, and now put a little check mark in each cell in the grid that satisfies the specification: that the first nunber in the pair (let's let that be the row number) is less than or equal to the second, (the column number). Each cell corresponds to a proposition, and you have just marked exacty the ones for which you want to have proofs. The definition of the intro rule for <= precisely assures that this is so. In Lean the relation is le. Look at the type of nat.le. It's ℕ → ℕ → Prop. It's a two-place predicate, but the key point here is that it's defined to express exactly the "less than or equal to -/ #check nat.le /- At this point you might be wondering where do the introduction rules to build proofs to show that certain values satisfy a given predicate. The answer is still a little bit beyond what we're fully equipped to handle right now, but the general idea can now be stated. A predicate is a type of function that takes some arguments and yields some propositions, one for each possible combination or arguemnt values. The question is, where are the rules defined determine how to construct proofs for and such proposition. The technical answer is that they are given by "proof constructor" (axioms) defined right along with the predicate, itself. Here for example is the type definition of the ≤ relation in Lean. (Just real Π as being ∀.) The first rule says you can prove a ≤ a for any a, and the second rule says that if you know that a ≤ b, for any a and b, that you can then also prove a ≤ (b + 1). That's it. inductive less_than_or_equal (a : ℕ) : ℕ → Prop | refl : less_than_or_equal a | step : Π {b}, less_than_or_equal b → less_than_or_equal (succ b) (Note that in the definition, the predicate takes two arguments, first a, and then some value of type ℕ as required by ℕ → Prop). It is easiest and just fine for now to think of it as just taking two parameters and giving a proposition, for which the proof rules are given by the constructors! -/ #print nat.le /- Here are proofs of 0 ≤ 0, 0 ≤ 1, and 0 ≤ 2. -/ example : 0 ≤ 0 := -- nat.le 0 0 begin exact nat.less_than_or_equal.refl, end example : nat.le 0 1 := begin apply nat.less_than_or_equal.step, exact nat.less_than_or_equal.refl, end example : nat.le 0 2 := begin apply nat.less_than_or_equal.step, apply nat.less_than_or_equal.step, exact nat.less_than_or_equal.refl, end /- How about proving 0 ≤ 2 in English. "To prove 0 ≤ 2, by the step rule, it will suffice to prove 0 ≤ 1. To prove 0 ≤ 1, it will suffice to prove 0 ≤ 0. And a proof of this is given by the reflexivity of ≤. QED." -/ /- Now think about these two questions: (1) which entries in a table of ℕ × ℕ are "filled in" by the refl rule? And which by the step rule? Can you see how the step rule fills in *all* cells to the right of the diagonal, "inductively" (one step after another for any finite number of times)? -/
a52dcbbdd193ff27e065f28beefed669cc16907c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/structured_arrow.lean
29df20ca72fdcdc58b09c8782fc1887a949c2a48
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,844
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.punit import category_theory.comma import category_theory.limits.shapes.terminal import category_theory.essentially_small /-! # The category of "structured arrows" > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For `T : C ⥤ D`, a `T`-structured arrow with source `S : D` is just a morphism `S ⟶ T.obj Y`, for some `Y : C`. These form a category with morphisms `g : Y ⟶ Y'` making the obvious diagram commute. We prove that `𝟙 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`. -/ namespace category_theory -- morphism levels before object levels. See note [category_theory universes]. universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- The category of `T`-structured arrows with domain `S : D` (here `T : C ⥤ D`), has as its objects `D`-morphisms of the form `S ⟶ T Y`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_nonempty_instance] def structured_arrow (S : D) (T : C ⥤ D) := comma (functor.from_punit S) T namespace structured_arrow /-- The obvious projection functor from structured arrows. -/ @[simps] def proj (S : D) (T : C ⥤ D) : structured_arrow S T ⥤ C := comma.snd _ _ variables {S S' S'' : D} {Y Y' : C} {T : C ⥤ D} /-- Construct a structured arrow from a morphism. -/ def mk (f : S ⟶ T.obj Y) : structured_arrow S T := ⟨⟨⟨⟩⟩, Y, f⟩ @[simp] lemma mk_left (f : S ⟶ T.obj Y) : (mk f).left = ⟨⟨⟩⟩ := rfl @[simp] lemma mk_right (f : S ⟶ T.obj Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom_eq_self (f : S ⟶ T.obj Y) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : structured_arrow S T} (f : A ⟶ B) : A.hom ≫ T.map f.right = B.hom := by { have := f.w; tidy } /-- To construct a morphism of structured arrows, we need a morphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : structured_arrow S T} (g : f.right ⟶ f'.right) (w : f.hom ≫ T.map g = f'.hom) : f ⟶ f' := { left := eq_to_hom (by ext), right := g, w' := by { dsimp, simpa using w.symm, }, } /-- Given a structured arrow `X ⟶ F(U)`, and an arrow `U ⟶ Y`, we can construct a morphism of structured arrow given by `(X ⟶ F(U)) ⟶ (X ⟶ F(U) ⟶ F(Y))`. -/ def hom_mk' {F : C ⥤ D} {X : D} {Y : C} (U : structured_arrow X F) (f : U.right ⟶ Y) : U ⟶ mk (U.hom ≫ F.map f) := { left := eq_to_hom (by ext), right := f } /-- To construct an isomorphism of structured arrows, we need an isomorphism of the objects underlying the target, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : structured_arrow S T} (g : f.right ≅ f'.right) (w : f.hom ≫ T.map g.hom = f'.hom) : f ≅ f' := comma.iso_mk (eq_to_iso (by ext)) g (by simpa [eq_to_hom_map] using w.symm) lemma ext {A B : structured_arrow S T} (f g : A ⟶ B) : f.right = g.right → f = g := comma_morphism.ext _ _ (subsingleton.elim _ _) lemma ext_iff {A B : structured_arrow S T} (f g : A ⟶ B) : f = g ↔ f.right = g.right := ⟨λ h, h ▸ rfl, ext f g⟩ instance proj_faithful : faithful (proj S T) := { map_injective' := λ X Y, ext } /-- The converse of this is true with additional assumptions, see `mono_iff_mono_right`. -/ lemma mono_of_mono_right {A B : structured_arrow S T} (f : A ⟶ B) [h : mono f.right] : mono f := (proj S T).mono_of_mono_map h lemma epi_of_epi_right {A B : structured_arrow S T} (f : A ⟶ B) [h : epi f.right] : epi f := (proj S T).epi_of_epi_map h instance mono_hom_mk {A B : structured_arrow S T} (f : A.right ⟶ B.right) (w) [h : mono f] : mono (hom_mk f w) := (proj S T).mono_of_mono_map h instance epi_hom_mk {A B : structured_arrow S T} (f : A.right ⟶ B.right) (w) [h : epi f] : epi (hom_mk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for structured arrows. Prefer `structured_arrow.eta`, since equality of objects tends to cause problems. -/ lemma eq_mk (f : structured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- Eta rule for structured arrows. -/ @[simps] def eta (f : structured_arrow S T) : f ≅ mk f.hom := iso_mk (iso.refl _) (by tidy) /-- A morphism between source objects `S ⟶ S'` contravariantly induces a functor between structured arrows, `structured_arrow S' T ⥤ structured_arrow S T`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : S ⟶ S') : structured_arrow S' T ⥤ structured_arrow S T := comma.map_left _ ((functor.const _).map f) @[simp] lemma map_mk {f : S' ⟶ T.obj Y} (g : S ⟶ S') : (map g).obj (mk f) = mk (g ≫ f) := rfl @[simp] lemma map_id {f : structured_arrow S T} : (map (𝟙 S)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : S ⟶ S'} {f' : S' ⟶ S''} {h : structured_arrow S'' T} : (map (f ≫ f')).obj h = (map f).obj ((map f').obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨structured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits local attribute [tidy] tactic.discrete_cases /-- The identity structured arrow is initial. -/ def mk_id_initial [full T] [faithful T] : is_initial (mk (𝟙 (T.obj Y))) := { desc := λ c, hom_mk (T.preimage c.X.hom) (by { dsimp, simp, }), uniq' := λ c m _, begin ext, apply T.map_injective, simpa only [hom_mk_right, T.image_preimage, ←w m] using (category.id_comp _).symm, end } variables {A : Type u₃} [category.{v₃} A] {B : Type u₄} [category.{v₄} B] /-- The functor `(S, F ⋙ G) ⥤ (S, G)`. -/ @[simps] def pre (S : D) (F : B ⥤ C) (G : C ⥤ D) : structured_arrow S (F ⋙ G) ⥤ structured_arrow S G := comma.pre_right _ F G /-- The functor `(S, F) ⥤ (G(S), F ⋙ G)`. -/ @[simps] def post (S : C) (F : B ⥤ C) (G : C ⥤ D) : structured_arrow S F ⥤ structured_arrow (G.obj S) (F ⋙ G) := { obj := λ X, structured_arrow.mk (G.map X.hom), map := λ X Y f, structured_arrow.hom_mk f.right (by simp [functor.comp_map, ←G.map_comp, ← f.w]) } instance small_proj_preimage_of_locally_small {𝒢 : set C} [small.{v₁} 𝒢] [locally_small.{v₁} D] : small.{v₁} ((proj S T).obj ⁻¹' 𝒢) := begin suffices : (proj S T).obj ⁻¹' 𝒢 = set.range (λ f : Σ G : 𝒢, S ⟶ T.obj G, mk f.2), { rw this, apply_instance }, exact set.ext (λ X, ⟨λ h, ⟨⟨⟨_, h⟩, X.hom⟩, (eq_mk _).symm⟩, by tidy⟩) end end structured_arrow /-- The category of `S`-costructured arrows with target `T : D` (here `S : C ⥤ D`), has as its objects `D`-morphisms of the form `S Y ⟶ T`, for some `Y : C`, and morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute. -/ @[derive category, nolint has_nonempty_instance] def costructured_arrow (S : C ⥤ D) (T : D) := comma S (functor.from_punit T) namespace costructured_arrow /-- The obvious projection functor from costructured arrows. -/ @[simps] def proj (S : C ⥤ D) (T : D) : costructured_arrow S T ⥤ C := comma.fst _ _ variables {T T' T'' : D} {Y Y' : C} {S : C ⥤ D} /-- Construct a costructured arrow from a morphism. -/ def mk (f : S.obj Y ⟶ T) : costructured_arrow S T := ⟨Y, ⟨⟨⟩⟩, f⟩ @[simp] lemma mk_left (f : S.obj Y ⟶ T) : (mk f).left = Y := rfl @[simp] lemma mk_right (f : S.obj Y ⟶ T) : (mk f).right = ⟨⟨⟩⟩ := rfl @[simp] lemma mk_hom_eq_self (f : S.obj Y ⟶ T) : (mk f).hom = f := rfl @[simp, reassoc] lemma w {A B : costructured_arrow S T} (f : A ⟶ B) : S.map f.left ≫ B.hom = A.hom := by tidy /-- To construct a morphism of costructured arrows, we need a morphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def hom_mk {f f' : costructured_arrow S T} (g : f.left ⟶ f'.left) (w : S.map g ≫ f'.hom = f.hom) : f ⟶ f' := { left := g, right := eq_to_hom (by ext), w' := by simpa [eq_to_hom_map] using w, } /-- To construct an isomorphism of costructured arrows, we need an isomorphism of the objects underlying the source, and to check that the triangle commutes. -/ @[simps] def iso_mk {f f' : costructured_arrow S T} (g : f.left ≅ f'.left) (w : S.map g.hom ≫ f'.hom = f.hom) : f ≅ f' := comma.iso_mk g (eq_to_iso (by ext)) (by simpa [eq_to_hom_map] using w) lemma ext {A B : costructured_arrow S T} (f g : A ⟶ B) (h : f.left = g.left) : f = g := comma_morphism.ext _ _ h (subsingleton.elim _ _) lemma ext_iff {A B : costructured_arrow S T} (f g : A ⟶ B) : f = g ↔ f.left = g.left := ⟨λ h, h ▸ rfl, ext f g⟩ instance proj_faithful : faithful (proj S T) := { map_injective' := λ X Y, ext } lemma mono_of_mono_left {A B : costructured_arrow S T} (f : A ⟶ B) [h : mono f.left] : mono f := (proj S T).mono_of_mono_map h /-- The converse of this is true with additional assumptions, see `epi_iff_epi_left`. -/ lemma epi_of_epi_left {A B : costructured_arrow S T} (f : A ⟶ B) [h : epi f.left] : epi f := (proj S T).epi_of_epi_map h instance mono_hom_mk {A B : costructured_arrow S T} (f : A.left ⟶ B.left) (w) [h : mono f] : mono (hom_mk f w) := (proj S T).mono_of_mono_map h instance epi_hom_mk {A B : costructured_arrow S T} (f : A.left ⟶ B.left) (w) [h : epi f] : epi (hom_mk f w) := (proj S T).epi_of_epi_map h /-- Eta rule for costructured arrows. Prefer `costructured_arrow.eta`, as equality of objects tends to cause problems. -/ lemma eq_mk (f : costructured_arrow S T) : f = mk f.hom := by { cases f, congr, ext, } /-- Eta rule for costructured arrows. -/ @[simps] def eta (f : costructured_arrow S T) : f ≅ mk f.hom := iso_mk (iso.refl _) (by tidy) /-- A morphism between target objects `T ⟶ T'` covariantly induces a functor between costructured arrows, `costructured_arrow S T ⥤ costructured_arrow S T'`. Ideally this would be described as a 2-functor from `D` (promoted to a 2-category with equations as 2-morphisms) to `Cat`. -/ @[simps] def map (f : T ⟶ T') : costructured_arrow S T ⥤ costructured_arrow S T' := comma.map_right _ ((functor.const _).map f) @[simp] lemma map_mk {f : S.obj Y ⟶ T} (g : T ⟶ T') : (map g).obj (mk f) = mk (f ≫ g) := rfl @[simp] lemma map_id {f : costructured_arrow S T} : (map (𝟙 T)).obj f = f := by { rw eq_mk f, simp, } @[simp] lemma map_comp {f : T ⟶ T'} {f' : T' ⟶ T''} {h : costructured_arrow S T} : (map (f ≫ f')).obj h = (map f').obj ((map f).obj h) := by { rw eq_mk h, simp, } instance proj_reflects_iso : reflects_isomorphisms (proj S T) := { reflects := λ Y Z f t, by exactI ⟨⟨costructured_arrow.hom_mk (inv ((proj S T).map f)) (by simp), by tidy⟩⟩ } open category_theory.limits local attribute [tidy] tactic.discrete_cases /-- The identity costructured arrow is terminal. -/ def mk_id_terminal [full S] [faithful S] : is_terminal (mk (𝟙 (S.obj Y))) := { lift := λ c, hom_mk (S.preimage c.X.hom) (by { dsimp, simp, }), uniq' := begin rintros c m -, ext, apply S.map_injective, simpa only [hom_mk_left, S.image_preimage, ←w m] using (category.comp_id _).symm, end } variables {A : Type u₃} [category.{v₃} A] {B : Type u₄} [category.{v₄} B] /-- The functor `(F ⋙ G, S) ⥤ (G, S)`. -/ @[simps] def pre (F : B ⥤ C) (G : C ⥤ D) (S : D) : costructured_arrow (F ⋙ G) S ⥤ costructured_arrow G S := comma.pre_left F G _ /-- The functor `(F, S) ⥤ (F ⋙ G, G(S))`. -/ @[simps] def post (F : B ⥤ C) (G : C ⥤ D) (S : C) : costructured_arrow F S ⥤ costructured_arrow (F ⋙ G) (G.obj S) := { obj := λ X, costructured_arrow.mk (G.map X.hom), map := λ X Y f, costructured_arrow.hom_mk f.left (by simp [functor.comp_map, ←G.map_comp, ← f.w]), } instance small_proj_preimage_of_locally_small {𝒢 : set C} [small.{v₁} 𝒢] [locally_small.{v₁} D] : small.{v₁} ((proj S T).obj ⁻¹' 𝒢) := begin suffices : (proj S T).obj ⁻¹' 𝒢 = set.range (λ f : Σ G : 𝒢, S.obj G ⟶ T, mk f.2), { rw this, apply_instance }, exact set.ext (λ X, ⟨λ h, ⟨⟨⟨_, h⟩, X.hom⟩, (eq_mk _).symm⟩, by tidy⟩) end end costructured_arrow open opposite namespace structured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `d ⟶ F.obj c` to the category of costructured arrows `F.op.obj c ⟶ (op d)`. -/ @[simps] def to_costructured_arrow (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ⥤ costructured_arrow F.op (op d) := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (op X.unop.right) F.op X.unop.hom.op, map := λ X Y f, costructured_arrow.hom_mk (f.unop.right.op) begin dsimp, rw [← op_comp, ← f.unop.w, functor.const_obj_map], erw category.id_comp, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of structured arrows `op d ⟶ F.op.obj c` to the category of costructured arrows `F.obj c ⟶ d`. -/ @[simps] def to_costructured_arrow' (F : C ⥤ D) (d : D) : (structured_arrow (op d) F.op)ᵒᵖ ⥤ costructured_arrow F d := { obj := λ X, @costructured_arrow.mk _ _ _ _ _ (unop X.unop.right) F X.unop.hom.unop, map := λ X Y f, costructured_arrow.hom_mk f.unop.right.unop begin dsimp, rw [← quiver.hom.unop_op (F.map (quiver.hom.unop f.unop.right)), ← unop_comp, ← F.op_map, ← f.unop.w, functor.const_obj_map], erw category.id_comp, end } end structured_arrow namespace costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.obj c ⟶ d` to the category of structured arrows `op d ⟶ F.op.obj c`. -/ @[simps] def to_structured_arrow (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ⥤ structured_arrow (op d) F.op := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (op X.unop.left) F.op X.unop.hom.op, map := λ X Y f, structured_arrow.hom_mk f.unop.left.op begin dsimp, rw [← op_comp, f.unop.w, functor.const_obj_map], erw category.comp_id, end } /-- For a functor `F : C ⥤ D` and an object `d : D`, we obtain a contravariant functor from the category of costructured arrows `F.op.obj c ⟶ op d` to the category of structured arrows `d ⟶ F.obj c`. -/ @[simps] def to_structured_arrow' (F : C ⥤ D) (d : D) : (costructured_arrow F.op (op d))ᵒᵖ ⥤ structured_arrow d F := { obj := λ X, @structured_arrow.mk _ _ _ _ _ (unop X.unop.left) F X.unop.hom.unop, map := λ X Y f, structured_arrow.hom_mk (f.unop.left.unop) begin dsimp, rw [← quiver.hom.unop_op (F.map f.unop.left.unop), ← unop_comp, ← F.op_map, f.unop.w, functor.const_obj_map], erw category.comp_id, end } end costructured_arrow /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of structured arrows `d ⟶ F.obj c` is contravariantly equivalent to the category of costructured arrows `F.op.obj c ⟶ op d`. -/ def structured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (structured_arrow d F)ᵒᵖ ≌ costructured_arrow F.op (op d) := equivalence.mk (structured_arrow.to_costructured_arrow F d) (costructured_arrow.to_structured_arrow' F d).right_op (nat_iso.of_components (λ X, (@structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) /-- For a functor `F : C ⥤ D` and an object `d : D`, the category of costructured arrows `F.obj c ⟶ d` is contravariantly equivalent to the category of structured arrows `op d ⟶ F.op.obj c`. -/ def costructured_arrow_op_equivalence (F : C ⥤ D) (d : D) : (costructured_arrow F d)ᵒᵖ ≌ structured_arrow (op d) F.op := equivalence.mk (costructured_arrow.to_structured_arrow F d) (structured_arrow.to_costructured_arrow' F d).right_op (nat_iso.of_components (λ X, (@costructured_arrow.iso_mk _ _ _ _ _ _ (costructured_arrow.mk (unop X).hom) (unop X) (iso.refl _) (by tidy)).op) (λ X Y f, quiver.hom.unop_inj $ begin ext, dsimp, simp end)) (nat_iso.of_components (λ X, @structured_arrow.iso_mk _ _ _ _ _ _ (structured_arrow.mk X.hom) X (iso.refl _) (by tidy)) (λ X Y f, begin ext, dsimp, simp end)) end category_theory
af9d7aa61f3359971c3e9a5b0f5720b42d53b684
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/order/bounded_lattice.lean
5026a6bca355ff8adceb0ebfcf9330731a973203
[ "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
35,897
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances import tactic.norm_cast set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top section prio set_option default_priority 100 -- see Note [default priority] /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) end prio section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) end prio section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α end prio section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α end prio section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } private def bot_aux (s : set ℕ) [decidable_pred s] [h : nonempty s] : s := have ∃ x, x ∈ s, from nonempty.elim h (λ x, ⟨x.1, x.2⟩), ⟨nat.find this, nat.find_spec this⟩ instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := bot_aux s, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_decidable_linear_order } section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α end prio section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α end prio section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ section prio set_option default_priority 100 -- see Note [default priority] /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α end prio @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α end prio lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_lattice_Prop : bounded_lattice Prop := { bounded_lattice . le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic /- Function lattices -/ /- TODO: * build up the lattice hierarchy for `fun`-functor piecewise. semilattic_*, bounded_lattice, lattice ... * can this be generalized to the dependent function space? -/ instance pi.bounded_lattice {α : Type u} {β : Type v} [bounded_lattice β] : bounded_lattice (α → β) := by pi_instance /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, ..with_bot.partial_order } instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) := { decidable_le := λ a b, begin cases a with a, { exact is_true bot_le }, cases b with b, { exact is_false (mt (le_antisymm bot_le) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_bot.linear_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem none_le [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem none_lt_some [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := lt_of_le_of_ne le_top (λ h, option.no_confusion h) lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, ..with_top.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) := { decidable_le := λ a b, begin cases b with b, { exact is_true le_top }, cases a with a, { exact is_false (mt (le_antisymm le_top) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_top.linear_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice_of_decidable_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm {a b : α} : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end disjoint /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq
4dc2406915a67d35235bcb53bfd52c921613d95c
c1a29ca460720df88ab68dc42d9a1a02e029d505
/examples/logic/unnamed_510.lean
635ba594580fd9641eecc9afea436d1727f478f1
[]
no_license
agusakov/mathematics_in_lean
acb5b3d659e4522ae4b4836ea550527f03f6546c
2539562e4d91c858c73dbecb5b282ce1a7d38b6d
refs/heads/master
1,665,963,365,241
1,592,080,022,000
1,592,080,022,000
272,078,062
0
0
null
1,592,078,772,000
1,592,078,772,000
null
UTF-8
Lean
false
false
275
lean
open function -- BEGIN variables {α : Type*} {β : Type*} {γ : Type*} variables {g : β → γ} {f : α → β} example (injg : injective g) (injf : injective f) : injective (λ x, g (f x)) := begin intros x₁ x₂ h, apply injf, apply injg, apply h end -- END
3201d78869ccc9fcf497dbb02a9cbfbd0be4789d
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/name.lean
672658c79c7567acb4dc17f3a528d522528c3415
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,707
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.ordering init.coe /- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/ inductive name | anonymous : name | mk_string : string → name → name | mk_numeral : unsigned → name → name instance : inhabited name := ⟨name.anonymous⟩ def mk_str_name (n : name) (s : string) : name := name.mk_string s n def mk_num_name (n : name) (v : nat) : name := name.mk_numeral (unsigned.of_nat v) n def mk_simple_name (s : string) : name := mk_str_name name.anonymous s instance string_to_name : has_coe string name := ⟨mk_simple_name⟩ infix ` <.> `:65 := mk_str_name open name def name.get_prefix : name → name | anonymous := anonymous | (mk_string s p) := p | (mk_numeral s p) := p def name.update_prefix : name → name → name | anonymous new_p := anonymous | (mk_string s p) new_p := mk_string s new_p | (mk_numeral s p) new_p := mk_numeral s new_p definition name.to_string_with_sep (sep : string) : name → string | anonymous := "[anonymous]" | (mk_string s anonymous) := s | (mk_numeral v anonymous) := to_string v | (mk_string s n) := name.to_string_with_sep n ++ sep ++ s | (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ to_string v private def name.components' : name -> list name | anonymous := [] | (mk_string s n) := mk_string s anonymous :: name.components' n | (mk_numeral v n) := mk_numeral v anonymous :: name.components' n def name.components (n : name) : list name := list.reverse (name.components' n) definition name.to_string : name → string := name.to_string_with_sep "." instance : has_to_string name := ⟨name.to_string⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant name.has_decidable_eq : decidable_eq name /- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/ meta constant name.cmp : name → name → ordering meta constant name.lex_cmp : name → name → ordering meta constant name.append : name → name → name meta constant name.is_internal : name → bool attribute [instance] name.has_decidable_eq meta instance : has_ordering name := ⟨name.cmp⟩ meta instance : has_append name := ⟨name.append⟩ /- (name.append_after n i) return a name of the form n_i -/ meta constant name.append_after : name → nat → name meta def name.is_prefix_of : name → name → bool | p name.anonymous := ff | p n := if p = n then tt else name.is_prefix_of p n^.get_prefix
2a61fa2989ca4709a1d865af965540d934e64974
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/bin_tree.lean
a3b75d664b2c40596dd4fd1e67fea4cfa807922e
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
966
lean
def pairs_with_sum' : Π (m n) {d}, m + n = d → list {p : ℕ × ℕ // p.1 + p.2 = d} | 0 n d h := [⟨(0, n), h⟩] | (m+1) n d h := ⟨(m+1, n), h⟩ :: pairs_with_sum' m (n+1) (by simp at h; simp [h]) def pairs_with_sum (n) : list {p : ℕ × ℕ // p.1 + p.2 = n} := pairs_with_sum' n 0 rfl inductive bin_tree | leaf : bin_tree | branch : bin_tree → bin_tree → bin_tree open bin_tree def size : bin_tree → ℕ | leaf := 0 | (branch l r) := size l + size r + 1 def trees_of_size : Π s, list {bt : bin_tree // size bt = s} | 0 := [⟨leaf, rfl⟩] | (n+1) := do ⟨(s1, s2), (h : s1 + s2 = n)⟩ ← pairs_with_sum n, ⟨t1, sz1⟩ ← have s1 < n+1, by apply nat.lt_succ_of_le; rw -h; apply nat.le_add_right, trees_of_size s1, ⟨t2, sz2⟩ ← have s2 < n+1, by apply nat.lt_succ_of_le; rw -h; apply nat.le_add_left, trees_of_size s2, return ⟨branch t1 t2, by rw [-h, -sz1, -sz2]; refl⟩
551a25e6523f51b240518d6ca2c35e87c100b4cd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/forget.lean
eaee0d1cd251178a10d84e7ccf716f52362a4079
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,359
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.sheaves.sheaf import Mathlib.category_theory.limits.preserves.shapes.products import Mathlib.category_theory.limits.types import Mathlib.PostPort universes u₁ v u₂ namespace Mathlib /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ namespace Top namespace presheaf namespace sheaf_condition /-- When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is naturally isomorphic to the sheaf condition diagram for `F ⋙ G`. -/ def diagram_comp_preserves_limits {C : Type u₁} [category_theory.category C] [category_theory.limits.has_limits C] {D : Type u₂} [category_theory.category D] [category_theory.limits.has_limits D] (G : C ⥤ D) [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : sheaf_condition_equalizer_products.diagram F U ⋙ G ≅ sheaf_condition_equalizer_products.diagram (F ⋙ G) U := category_theory.nat_iso.of_components (fun (X_1 : category_theory.limits.walking_parallel_pair) => category_theory.limits.walking_parallel_pair.cases_on X_1 (category_theory.limits.preserves_product.iso G fun (i : ι) => category_theory.functor.obj F (opposite.op (U i))) (category_theory.limits.preserves_product.iso G fun (p : ι × ι) => category_theory.functor.obj F (opposite.op (U (prod.fst p) ⊓ U (prod.snd p))))) sorry /-- When `G` preserves limits, the image under `G` of the sheaf condition fork for `F` is the sheaf condition fork for `F ⋙ G`, postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`. -/ def map_cone_fork {C : Type u₁} [category_theory.category C] [category_theory.limits.has_limits C] {D : Type u₂} [category_theory.category D] [category_theory.limits.has_limits D] (G : C ⥤ D) [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : category_theory.functor.map_cone G (sheaf_condition_equalizer_products.fork F U) ≅ category_theory.functor.obj (category_theory.limits.cones.postcompose (category_theory.iso.inv (diagram_comp_preserves_limits G F U))) (sheaf_condition_equalizer_products.fork (F ⋙ G) U) := category_theory.limits.cones.ext (category_theory.iso.refl (category_theory.limits.cone.X (category_theory.functor.map_cone G (sheaf_condition_equalizer_products.fork F U)))) sorry end sheaf_condition /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRing ⥤ Top`. See https://stacks.math.columbia.edu/tag/0073. In fact we prove a stronger version with arbitrary complete target category. -/ def sheaf_condition_equiv_sheaf_condition_comp {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (G : C ⥤ D) [category_theory.reflects_isomorphisms G] [category_theory.limits.has_limits C] [category_theory.limits.has_limits D] [category_theory.limits.preserves_limits G] {X : Top} (F : presheaf C X) : sheaf_condition F ≃ sheaf_condition (F ⋙ G) := sorry
e1137dd6a85cff733c01eeeb77e3bfa2918ce83e
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/geometry/euclidean/oriented_angle.lean
495b2159f92fa9e481271f515bea63746677c3ef
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
59,778
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 analysis.inner_product_space.orientation import analysis.inner_product_space.pi_L2 import analysis.special_functions.complex.circle import geometry.euclidean.basic /-! # Oriented angles. This file defines oriented angles in real inner product spaces. ## Main definitions * `orientation.oangle` is the oriented angle between two vectors with respect to an orientation. * `orientation.rotation` is the rotation by an oriented angle with respect to an orientation. ## Implementation notes The definitions here use the `real.angle` type, angles modulo `2 * π`. For some purposes, angles modulo `π` are more convenient, because results are true for such angles with less configuration dependence. Results that are only equalities modulo `π` can be represented modulo `2 * π` as equalities of `(2 : ℤ) • θ`. Definitions and results in the `orthonormal` namespace, with respect to a particular choice of orthonormal basis, are mainly for use in setting up the API and proving that certain definitions do not depend on the choice of basis for a given orientation. Applications should generally use the definitions and results in the `orientation` namespace instead. ## References * Evan Chen, Euclidean Geometry in Mathematical Olympiads. -/ noncomputable theory open_locale real open_locale real_inner_product_space namespace orthonormal variables {V : Type*} [inner_product_space ℝ V] variables {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) include hb /-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0. -/ def oangle (x y : V) : real.angle := complex.arg ((complex.isometry_of_orthonormal hb).symm y / (complex.isometry_of_orthonormal hb).symm x) /-- Oriented angles are continuous when the vectors involved are nonzero. -/ lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, hb.oangle y.1 y.2) x := (complex.continuous_at_arg_coe_angle (by simp [hx1, hx2])).comp $ continuous_at.div ((complex.isometry_of_orthonormal hb).symm.continuous.comp continuous_snd).continuous_at ((complex.isometry_of_orthonormal hb).symm.continuous.comp continuous_fst).continuous_at (by simp [hx1]) /-- If the first vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_left (x : V) : hb.oangle 0 x = 0 := by simp [oangle] /-- If the second vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_right (x : V) : hb.oangle x 0 = 0 := by simp [oangle] /-- If the two vectors passed to `oangle` are the same, the result is 0. -/ @[simp] lemma oangle_self (x : V) : hb.oangle x x = 0 := begin by_cases h : x = 0; simp [oangle, h] end /-- Swapping the two vectors passed to `oangle` negates the angle. -/ lemma oangle_rev (x y : V) : hb.oangle y x = -hb.oangle x y := begin simp only [oangle], convert complex.arg_inv_coe_angle _, exact (inv_div _ _).symm end /-- Adding the angles between two vectors in each order results in 0. -/ @[simp] lemma oangle_add_oangle_rev (x y : V) : hb.oangle x y + hb.oangle y x = 0 := by simp [hb.oangle_rev y x] /-- Negating the first vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle (-x) y = hb.oangle x y + π := begin simp only [oangle, div_neg_eq_neg_div, map_neg], refine complex.arg_neg_coe_angle _, simp [hx, hy] end /-- Negating the second vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle x (-y) = hb.oangle x y + π := begin simp only [oangle, neg_div, map_neg], refine complex.arg_neg_coe_angle _, simp [hx, hy] end /-- Negating the first vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_left (x y : V) : (2 : ℤ) • hb.oangle (-x) y = (2 : ℤ) • hb.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hb.oangle_neg_left hx hy] } } end /-- Negating the second vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_right (x y : V) : (2 : ℤ) • hb.oangle x (-y) = (2 : ℤ) • hb.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hb.oangle_neg_right hx hy] } } end /-- Negating both vectors passed to `oangle` does not change the angle. -/ @[simp] lemma oangle_neg_neg (x y : V) : hb.oangle (-x) (-y) = hb.oangle x y := by simp [oangle, neg_div_neg_eq] /-- Negating the first vector produces the same angle as negating the second vector. -/ lemma oangle_neg_left_eq_neg_right (x y : V) : hb.oangle (-x) y = hb.oangle x (-y) := by rw [←neg_neg y, oangle_neg_neg, neg_neg] /-- The angle between the negation of a nonzero vector and that vector is `π`. -/ @[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : hb.oangle (-x) x = π := by simp [oangle_neg_left, hx] /-- The angle between a nonzero vector and its negation is `π`. -/ @[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : hb.oangle x (-x) = π := by simp [oangle_neg_right, hx] /-- Twice the angle between the negation of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • hb.oangle (-x) x = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Twice the angle between a vector and its negation is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • hb.oangle x (-x) = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Adding the angles between two vectors in each order, with the first vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) : hb.oangle (-x) y + hb.oangle (-y) x = 0 := by rw [oangle_neg_left_eq_neg_right, oangle_rev, add_left_neg] /-- Adding the angles between two vectors in each order, with the second vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) : hb.oangle x (-y) + hb.oangle y (-x) = 0 := by rw [hb.oangle_rev (-x), oangle_neg_left_eq_neg_right, add_neg_self] /-- Multiplying the first vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : hb.oangle (r • x) y = hb.oangle x y := begin simp only [oangle, linear_isometry_equiv.map_smul, complex.real_smul], rw [mul_comm, div_mul_eq_div_mul_one_div, one_div, mul_comm, ←complex.of_real_inv], congr' 1, exact complex.arg_real_mul _ (inv_pos.2 hr) end /-- Multiplying the second vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : hb.oangle x (r • y) = hb.oangle x y := begin simp only [oangle, linear_isometry_equiv.map_smul, complex.real_smul], congr' 1, rw mul_div_assoc, exact complex.arg_real_mul _ hr end /-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : hb.oangle (r • x) y = hb.oangle (-x) y := by rw [←neg_neg r, neg_smul, ←smul_neg, hb.oangle_smul_left_of_pos _ _ (neg_pos_of_neg hr)] /-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : hb.oangle x (r • y) = hb.oangle x (-y) := by rw [←neg_neg r, neg_smul, ←smul_neg, hb.oangle_smul_right_of_pos _ _ (neg_pos_of_neg hr)] /-- The angle between a nonnegative multiple of a vector and that vector is 0. -/ @[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : hb.oangle (r • x) x = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between a vector and a nonnegative multiple of that vector is 0. -/ @[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : hb.oangle x (r • x) = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between two nonnegative multiples of the same vector is 0. -/ @[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : hb.oangle (r₁ • x) (r₂ • x) = 0 := begin rcases hr₁.lt_or_eq with (h|h), { simp [h, hr₂] }, { simp [h.symm] } end /-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • hb.oangle (r • x) y = (2 : ℤ) • hb.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • hb.oangle x (r • y) = (2 : ℤ) • hb.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Twice the angle between a multiple of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} : (2 : ℤ) • hb.oangle (r • x) x = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between a vector and a multiple of that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} : (2 : ℤ) • hb.oangle x (r • x) = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between two multiples of a vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} : (2 : ℤ) • hb.oangle (r₁ • x) (r₂ • x) = 0 := begin by_cases h : r₁ = 0; simp [h] end /-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/ lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ∥x∥ = ∥y∥ ∧ hb.oangle x y = 0 := begin split, { intro h, simp [h] }, { rintro ⟨hn, ha⟩, rw [oangle] at ha, by_cases hy0 : y = 0, { simpa [hy0] using hn }, { have hx0 : x ≠ 0 := norm_ne_zero_iff.1 (hn.symm ▸ norm_ne_zero_iff.2 hy0), have hx0' : (complex.isometry_of_orthonormal hb).symm x ≠ 0, { simp [hx0] }, have hy0' : (complex.isometry_of_orthonormal hb).symm y ≠ 0, { simp [hy0] }, rw [complex.arg_div_coe_angle hy0' hx0', sub_eq_zero, complex.arg_coe_angle_eq_iff, complex.arg_eq_arg_iff hy0' hx0', ←complex.norm_eq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, linear_isometry_equiv.norm_map, hn, ←complex.of_real_div, div_self (norm_ne_zero_iff.2 hy0), complex.of_real_one, one_mul, linear_isometry_equiv.map_eq_iff] at ha, exact ha.symm } } end /-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/ lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : x = y ↔ hb.oangle x y = 0 := ⟨λ he, ((hb.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).2, λ ha, (hb.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨h, ha⟩⟩ /-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/ lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : hb.oangle x y = 0) : x = y ↔ ∥x∥ = ∥y∥ := ⟨λ he, ((hb.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).1, λ hn, (hb.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨hn, h⟩⟩ /-- Given three nonzero vectors, the angle between the first and the second plus the angle between the second and the third equals the angle between the first and the third. -/ @[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x y + hb.oangle y z = hb.oangle x z := begin simp_rw [oangle], rw ←complex.arg_mul_coe_angle, { rw [mul_comm, div_mul_div_cancel], simp [hy] }, { simp [hx, hy] }, { simp [hy, hz] } end /-- Given three nonzero vectors, the angle between the second and the third plus the angle between the first and the second equals the angle between the first and the third. -/ @[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle y z + hb.oangle x y = hb.oangle x z := by rw [add_comm, hb.oangle_add hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the first and the second equals the angle between the second and the third. -/ @[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x z - hb.oangle x y = hb.oangle y z := by rw [sub_eq_iff_eq_add, hb.oangle_add_swap hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the second and the third equals the angle between the first and the second. -/ @[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x z - hb.oangle y z = hb.oangle x y := by rw [sub_eq_iff_eq_add, hb.oangle_add hx hy hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/ @[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x y + hb.oangle y z + hb.oangle z x = 0 := by simp [hx, hy, hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle (-x) y + hb.oangle (-y) z + hb.oangle (-z) x = π := by rw [hb.oangle_neg_left hx hy, hb.oangle_neg_left hy hz, hb.oangle_neg_left hz hx, (show hb.oangle x y + π + (hb.oangle y z + π) + (hb.oangle z x + π) = hb.oangle x y + hb.oangle y z + hb.oangle z x + (π + π + π : real.angle), by abel), hb.oangle_add_cyc3 hx hy hz, real.angle.coe_pi_add_coe_pi, zero_add, zero_add] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x (-y) + hb.oangle y (-z) + hb.oangle z (-x) = π := by simp_rw [←oangle_neg_left_eq_neg_right, hb.oangle_add_cyc3_neg_left hx hy hz] /-- Pons asinorum, oriented vector angle form. -/ lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : hb.oangle x (x - y) = hb.oangle (y - x) y := begin by_cases hx : x = 0, { simp [hx] }, { have hy : y ≠ 0 := norm_ne_zero_iff.1 (h ▸ norm_ne_zero_iff.2 hx), simp_rw [hb.oangle_rev y, oangle, linear_isometry_equiv.map_sub, ←complex.arg_conj_coe_angle, sub_div, div_self (((complex.isometry_of_orthonormal hb).symm.map_eq_zero_iff).not.2 hx), div_self (((complex.isometry_of_orthonormal hb).symm.map_eq_zero_iff).not.2 hy), map_sub, map_one], rw ←inv_div, simp_rw [complex.inv_def, complex.norm_sq_div, ←complex.sq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, h], simp [hy] } end /-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented vector angle form. -/ lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ∥x∥ = ∥y∥) : hb.oangle y x = π - (2 : ℤ) • hb.oangle (y - x) y := begin rw two_zsmul, rw [←hb.oangle_sub_eq_oangle_sub_rev_of_norm_eq h] { occs := occurrences.pos [1] }, rw [eq_sub_iff_add_eq, ←oangle_neg_neg, ←add_assoc], have hy : y ≠ 0, { rintro rfl, rw [norm_zero, norm_eq_zero] at h, exact hn h }, have hx : x ≠ 0 := norm_ne_zero_iff.1 (h.symm ▸ norm_ne_zero_iff.2 hy), convert hb.oangle_add_cyc3_neg_right (neg_ne_zero.2 hy) hx (sub_ne_zero_of_ne hn.symm); simp end /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) (hxy : ∥x∥ = ∥y∥) (hxz : ∥x∥ = ∥z∥) : hb.oangle y z = (2 : ℤ) • hb.oangle (y - x) (z - x) := begin have hy : y ≠ 0, { rintro rfl, rw [norm_zero, norm_eq_zero] at hxy, exact hxyne hxy }, have hx : x ≠ 0 := norm_ne_zero_iff.1 (hxy.symm ▸ norm_ne_zero_iff.2 hy), have hz : z ≠ 0 := norm_ne_zero_iff.1 (hxz ▸ norm_ne_zero_iff.2 hx), calc hb.oangle y z = hb.oangle x z - hb.oangle x y : (hb.oangle_sub_left hx hy hz).symm ... = (π - (2 : ℤ) • hb.oangle (x - z) x) - (π - (2 : ℤ) • hb.oangle (x - y) x) : by rw [hb.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hxzne.symm hxz.symm, hb.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hxyne.symm hxy.symm] ... = (2 : ℤ) • (hb.oangle (x - y) x - hb.oangle (x - z) x) : by abel ... = (2 : ℤ) • hb.oangle (x - y) (x - z) : by rw hb.oangle_sub_right (sub_ne_zero_of_ne hxyne) (sub_ne_zero_of_ne hxzne) hx ... = (2 : ℤ) • hb.oangle (y - x) (z - x) : by rw [←oangle_neg_neg, neg_sub, neg_sub] end /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form with radius specified. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) {r : ℝ} (hx : ∥x∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : hb.oangle y z = (2 : ℤ) • hb.oangle (y - x) (z - x) := hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq hxyne hxzne (hy.symm ▸ hx) (hz.symm ▸ hx) /-- Oriented vector angle version of "angles in same segment are equal" and "opposite angles of a cyclic quadrilateral add to π", for oriented angles mod π (for which those are the same result), represented here as equality of twice the angles. -/ lemma two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq {x₁ x₂ y z : V} (hx₁yne : x₁ ≠ y) (hx₁zne : x₁ ≠ z) (hx₂yne : x₂ ≠ y) (hx₂zne : x₂ ≠ z) {r : ℝ} (hx₁ : ∥x₁∥ = r) (hx₂ : ∥x₂∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : (2 : ℤ) • hb.oangle (y - x₁) (z - x₁) = (2 : ℤ) • hb.oangle (y - x₂) (z - x₂) := hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hx₁yne hx₁zne hx₁ hy hz ▸ hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hx₂yne hx₂zne hx₂ hy hz /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := ((complex.isometry_of_orthonormal hb).symm.trans (rotation (real.angle.exp_map_circle θ))).trans (complex.isometry_of_orthonormal hb) /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : ((hb.rotation θ).to_linear_equiv : V →ₗ[ℝ] V).det = 1 := by simp [rotation, ←linear_isometry_equiv.to_linear_equiv_symm, ←linear_equiv.comp_coe] /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (hb.rotation θ).to_linear_equiv.det = 1 := by simp [rotation, ←linear_isometry_equiv.to_linear_equiv_symm] /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (hb.rotation θ).symm = hb.rotation (-θ) := by simp [rotation, linear_isometry_equiv.trans_assoc] /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : hb.rotation 0 = linear_isometry_equiv.refl ℝ V := by simp [rotation] /-- Rotation by π is negation. -/ lemma rotation_pi : hb.rotation π = linear_isometry_equiv.neg ℝ := begin ext x, simp [rotation] end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (hb.rotation θ₁).trans (hb.rotation θ₂) = hb.rotation (θ₂ + θ₁) := begin simp only [rotation, ←linear_isometry_equiv.trans_assoc], ext1 x, simp end /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle (hb.rotation θ x) y = hb.oangle x y - θ := begin simp [oangle, rotation, complex.arg_div_coe_angle, complex.arg_mul_coe_angle, hx, hy, ne_zero_of_mem_circle], abel end /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x (hb.rotation θ y) = hb.oangle x y + θ := begin simp [oangle, rotation, complex.arg_div_coe_angle, complex.arg_mul_coe_angle, hx, hy, ne_zero_of_mem_circle], abel end /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.oangle (hb.rotation θ x) x = -θ := by simp [hx] /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.oangle x (hb.rotation θ x) = θ := by simp [hx] /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : hb.oangle (hb.rotation (hb.oangle x y) x) y = 0 := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hx, hy] } } end /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : hb.oangle y (hb.rotation (hb.oangle x y) x) = 0 := begin rw [oangle_rev], simp end /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : hb.oangle (hb.rotation θ x) (hb.rotation θ y) = hb.oangle x y := begin by_cases hx : x = 0; by_cases hy : y = 0; simp [hx, hy] end /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.rotation θ x = x ↔ θ = 0 := begin split, { intro h, rw eq_comm, simpa [hx, h] using hb.oangle_rotation_right hx hx θ }, { intro h, simp [h] } end /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = hb.rotation θ x ↔ θ = 0 := by rw [←hb.rotation_eq_self_iff_angle_eq_zero hx, eq_comm] /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : hb.rotation θ x = x ↔ x = 0 ∨ θ = 0 := begin by_cases h : x = 0; simp [h] end /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = hb.rotation θ x ↔ x = 0 ∨ θ = 0 := by rw [←rotation_eq_self_iff, eq_comm] /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : hb.rotation (hb.oangle x y) x = y ↔ ∥x∥ = ∥y∥ := begin split, { intro h, rw [←h, linear_isometry_equiv.norm_map] }, { intro h, rw hb.eq_iff_oangle_eq_zero_of_norm_eq; simp [h] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x y = θ ↔ y = (∥y∥ / ∥x∥) • hb.rotation θ x := begin have hp := div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), split, { rintro rfl, rw [←linear_isometry_equiv.map_smul, ←hb.oangle_smul_left_of_pos x y hp, eq_comm, rotation_oangle_eq_iff_norm_eq, norm_smul, real.norm_of_nonneg hp.le, div_mul_cancel _ (norm_ne_zero_iff.2 hx)] }, { intro hye, rw [hye, hb.oangle_smul_right_of_pos _ _ hp, hb.oangle_rotation_self_right hx] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • hb.rotation θ x := begin split, { intro h, rw hb.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy at h, exact ⟨∥y∥ / ∥x∥, div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), h⟩ }, { rintro ⟨r, hr, rfl⟩, rw [hb.oangle_smul_right_of_pos _ _ hr, hb.oangle_rotation_self_right hx] } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : hb.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (∥y∥ / ∥x∥) • hb.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw hb.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : hb.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • hb.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw hb.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- Complex conjugation as a linear isometric equivalence in `V`. Note that this definition depends on the choice of basis, not just on its orientation; for most geometrical purposes, the `reflection` definitions should be preferred instead. -/ def conj_lie : V ≃ₗᵢ[ℝ] V := ((complex.isometry_of_orthonormal hb).symm.trans complex.conj_lie).trans (complex.isometry_of_orthonormal hb) /-- The determinant of `conj_lie` (as a linear map) is equal to `-1`. -/ @[simp] lemma det_conj_lie : (hb.conj_lie.to_linear_equiv : V →ₗ[ℝ] V).det = -1 := by simp [conj_lie, ←linear_isometry_equiv.to_linear_equiv_symm, ←linear_equiv.comp_coe] /-- The determinant of `conj_lie` (as a linear equiv) is equal to `-1`. -/ @[simp] lemma linear_equiv_det_conj_lie : hb.conj_lie.to_linear_equiv.det = -1 := by simp [conj_lie, ←linear_isometry_equiv.to_linear_equiv_symm] /-- `conj_lie` is its own inverse. -/ @[simp] lemma conj_lie_symm : hb.conj_lie.symm = hb.conj_lie := rfl /-- Applying `conj_lie` to both vectors negates the angle between those vectors. -/ @[simp] lemma oangle_conj_lie (x y : V) : hb.oangle (hb.conj_lie x) (hb.conj_lie y) = -hb.oangle x y := by simp only [orthonormal.conj_lie, linear_isometry_equiv.symm_apply_apply, orthonormal.oangle, eq_self_iff_true, function.comp_app, complex.arg_coe_angle_eq_iff, linear_isometry_equiv.coe_trans, neg_inj, complex.conj_lie_apply, complex.arg_conj_coe_angle, ← map_div₀ (star_ring_end ℂ)] /-- Any linear isometric equivalence in `V` is `rotation` or `conj_lie` composed with `rotation`. -/ lemma exists_linear_isometry_equiv_eq (f : V ≃ₗᵢ[ℝ] V) : ∃ θ : real.angle, f = hb.rotation θ ∨ f = hb.conj_lie.trans (hb.rotation θ) := begin cases linear_isometry_complex (((complex.isometry_of_orthonormal hb).trans f).trans (complex.isometry_of_orthonormal hb).symm) with a ha, use complex.arg a, rcases ha with (ha|ha), { left, simp only [rotation, ←ha, linear_isometry_equiv.trans_assoc, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans_self, real.angle.exp_map_circle_coe, exp_map_circle_arg], simp [←linear_isometry_equiv.trans_assoc] }, { right, simp only [rotation, conj_lie, linear_isometry_equiv.trans_assoc, real.angle.exp_map_circle_coe, exp_map_circle_arg], simp only [←linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.trans_refl], simp_rw [linear_isometry_equiv.trans_assoc complex.conj_lie, ←ha], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans_self], simp [←linear_isometry_equiv.trans_assoc] } end /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = hb.rotation θ := begin rcases hb.exists_linear_isometry_equiv_eq f with ⟨θ, (hf|hf)⟩, { exact ⟨θ, hf⟩ }, { simp [hf, ←linear_equiv.coe_det] at hd, norm_num at hd } end /-- Any linear isometric equivalence in `V` with negative determinant is `conj_lie` composed with `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_neg {f : V ≃ₗᵢ[ℝ] V} (hd : (f.to_linear_equiv : V →ₗ[ℝ] V).det < 0) : ∃ θ : real.angle, f = hb.conj_lie.trans (hb.rotation θ) := begin rcases hb.exists_linear_isometry_equiv_eq f with ⟨θ, (hf|hf)⟩, { simp [hf, ←linear_equiv.coe_det] at hd, norm_num at hd }, { exact ⟨θ, hf⟩ } end /-- Two bases with the same orientation are related by a `rotation`. -/ lemma exists_linear_isometry_equiv_map_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) : ∃ θ : real.angle, b₂ = b.map (hb.rotation θ).to_linear_equiv := begin have h : b₂ = b.map (hb.equiv hb₂ (equiv.refl _)).to_linear_equiv, { rw hb.map_equiv, simp }, rw [eq_comm, h, b.orientation_comp_linear_equiv_eq_iff_det_pos] at ho, cases hb.exists_linear_isometry_equiv_eq_of_det_pos ho with θ hθ, rw hθ at h, exact ⟨θ, h⟩ end /-- Two bases with opposite orientations are related by `conj_lie` composed with a `rotation`. -/ lemma exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) : ∃ θ : real.angle, b₂ = b.map (hb.conj_lie.trans (hb.rotation θ)).to_linear_equiv := begin have h : b₂ = b.map (hb.equiv hb₂ (equiv.refl _)).to_linear_equiv, { rw hb.map_equiv, simp }, rw [eq_neg_iff_eq_neg, h, b.orientation_comp_linear_equiv_eq_neg_iff_det_neg] at ho, cases hb.exists_linear_isometry_equiv_eq_of_det_neg ho with θ hθ, rw hθ at h, exact ⟨θ, h⟩ end /-- The angle between two vectors, with respect to a basis given by `basis.map` with a linear isometric equivalence, equals the angle between those two vectors, transformed by the inverse of that equivalence, with respect to the original basis. -/ @[simp] lemma oangle_map (x y : V) (f : V ≃ₗᵢ[ℝ] V) : (hb.map_linear_isometry_equiv f).oangle x y = hb.oangle (f.symm x) (f.symm y) := by simp [oangle] /-- The value of `oangle` does not depend on the choice of basis for a given orientation. -/ lemma oangle_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) (x y : V) : hb.oangle x y = hb₂.oangle x y := begin obtain ⟨θ, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq hb₂ ho, simp [hb] end /-- Negating the orientation negates the value of `oangle`. -/ lemma oangle_eq_neg_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) (x y : V) : hb.oangle x y = -hb₂.oangle x y := begin obtain ⟨θ, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg hb₂ ho, rw hb.oangle_map, simp [hb] end /-- `rotation` does not depend on the choice of basis for a given orientation. -/ lemma rotation_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) (θ : real.angle) : hb.rotation θ = hb₂.rotation θ := begin obtain ⟨θ₂, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq hb₂ ho, simp_rw [rotation, complex.map_isometry_of_orthonormal hb], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans], simp only [←linear_isometry_equiv.trans_assoc, _root_.rotation_symm, _root_.rotation_trans, mul_comm (real.angle.exp_map_circle θ), ←mul_assoc, mul_right_inv, one_mul] end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_eq_rotation_neg_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) (θ : real.angle) : hb.rotation θ = hb₂.rotation (-θ) := begin obtain ⟨θ₂, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg hb₂ ho, simp_rw [rotation, complex.map_isometry_of_orthonormal hb, conj_lie], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans], congr' 1, simp only [←linear_isometry_equiv.trans_assoc, _root_.rotation_symm, linear_isometry_equiv.symm_symm, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.trans_refl, complex.conj_lie_symm], congr' 1, ext1 x, simp only [linear_isometry_equiv.coe_trans, function.comp_app, rotation_apply, complex.conj_lie_apply, map_mul, star_ring_end_self_apply, ←coe_inv_circle_eq_conj, inv_inv, real.angle.exp_map_circle_neg, ←mul_assoc], congr' 1, simp only [mul_comm (real.angle.exp_map_circle θ₂ : ℂ), mul_assoc], rw [←submonoid.coe_mul, mul_left_inv, submonoid.coe_one, mul_one] end /-- The inner product of two vectors is the product of the norms and the cosine of the oriented angle between the vectors. -/ lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) : ⟪x, y⟫ = ∥x∥ * ∥y∥ * real.angle.cos (hb.oangle x y) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [oangle, real.angle.cos_coe, complex.cos_arg], swap, { simp [hx, hy] }, simp_rw [complex.abs_div, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, complex.div_re, ←complex.sq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, complex.isometry_of_orthonormal_symm_apply, complex.add_re, complex.add_im, is_R_or_C.I, complex.mul_I_re, complex.mul_I_im, complex.of_real_re, complex.of_real_im, basis.coord_apply, neg_zero, zero_add, add_zero], conv_lhs { rw [←b.sum_repr x, ←b.sum_repr y] }, simp_rw [hb.inner_sum, (dec_trivial : (finset.univ : finset (fin 2)) = {0, 1}), star_ring_end_apply, star_trivial], rw [finset.sum_insert (dec_trivial : (0 : fin 2) ∉ ({1} : finset (fin 2))), finset.sum_singleton], field_simp [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy], ring end /-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by the product of the norms. -/ lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (hb.oangle x y) = ⟪x, y⟫ / (∥x∥ * ∥y∥) := begin rw hb.inner_eq_norm_mul_norm_mul_cos_oangle, field_simp [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy], ring end /-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented angle. -/ lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (hb.oangle x y) = real.cos (inner_product_geometry.angle x y) := by rw [hb.cos_oangle_eq_inner_div_norm_mul_norm hx hy, inner_product_geometry.cos_angle] /-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/ lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle x y = inner_product_geometry.angle x y ∨ hb.oangle x y = -inner_product_geometry.angle x y := real.angle.cos_eq_real_cos_iff_eq_or_eq_neg.1 $ hb.cos_oangle_eq_cos_angle hx hy end orthonormal namespace orientation open finite_dimensional variables {V : Type*} [inner_product_space ℝ V] variables [hd2 : fact (finrank ℝ V = 2)] (o : orientation ℝ V (fin 2)) include hd2 o local notation `ob` := o.fin_orthonormal_basis_orthonormal dec_trivial hd2.out /-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0. See `inner_product_geometry.angle` for the corresponding unoriented angle definition. -/ def oangle (x y : V) : real.angle := (ob).oangle x y /-- Oriented angles are continuous when the vectors involved are nonzero. -/ lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, o.oangle y.1 y.2) x := (ob).continuous_at_oangle hx1 hx2 /-- If the first vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_left (x : V) : o.oangle 0 x = 0 := (ob).oangle_zero_left x /-- If the second vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_right (x : V) : o.oangle x 0 = 0 := (ob).oangle_zero_right x /-- If the two vectors passed to `oangle` are the same, the result is 0. -/ @[simp] lemma oangle_self (x : V) : o.oangle x x = 0 := (ob).oangle_self x /-- Swapping the two vectors passed to `oangle` negates the angle. -/ lemma oangle_rev (x y : V) : o.oangle y x = -o.oangle x y := (ob).oangle_rev x y /-- Adding the angles between two vectors in each order results in 0. -/ @[simp] lemma oangle_add_oangle_rev (x y : V) : o.oangle x y + o.oangle y x = 0 := (ob).oangle_add_oangle_rev x y /-- Negating the first vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle (-x) y = o.oangle x y + π := (ob).oangle_neg_left hx hy /-- Negating the second vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x (-y) = o.oangle x y + π := (ob).oangle_neg_right hx hy /-- Negating the first vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_left (x y : V) : (2 : ℤ) • o.oangle (-x) y = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_neg_left x y /-- Negating the second vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_right (x y : V) : (2 : ℤ) • o.oangle x (-y) = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_neg_right x y /-- Negating both vectors passed to `oangle` does not change the angle. -/ @[simp] lemma oangle_neg_neg (x y : V) : o.oangle (-x) (-y) = o.oangle x y := (ob).oangle_neg_neg x y /-- Negating the first vector produces the same angle as negating the second vector. -/ lemma oangle_neg_left_eq_neg_right (x y : V) : o.oangle (-x) y = o.oangle x (-y) := (ob).oangle_neg_left_eq_neg_right x y /-- The angle between the negation of a nonzero vector and that vector is `π`. -/ @[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : o.oangle (-x) x = π := (ob).oangle_neg_self_left hx /-- The angle between a nonzero vector and its negation is `π`. -/ @[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : o.oangle x (-x) = π := (ob).oangle_neg_self_right hx /-- Twice the angle between the negation of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • o.oangle (-x) x = 0 := (ob).two_zsmul_oangle_neg_self_left x /-- Twice the angle between a vector and its negation is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • o.oangle x (-x) = 0 := (ob).two_zsmul_oangle_neg_self_right x /-- Adding the angles between two vectors in each order, with the first vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) : o.oangle (-x) y + o.oangle (-y) x = 0 := (ob).oangle_add_oangle_rev_neg_left x y /-- Adding the angles between two vectors in each order, with the second vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) : o.oangle x (-y) + o.oangle y (-x) = 0 := (ob).oangle_add_oangle_rev_neg_right x y /-- Multiplying the first vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle (r • x) y = o.oangle x y := (ob).oangle_smul_left_of_pos x y hr /-- Multiplying the second vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle x (r • y) = o.oangle x y := (ob).oangle_smul_right_of_pos x y hr /-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle (r • x) y = o.oangle (-x) y := (ob).oangle_smul_left_of_neg x y hr /-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle x (r • y) = o.oangle x (-y) := (ob).oangle_smul_right_of_neg x y hr /-- The angle between a nonnegative multiple of a vector and that vector is 0. -/ @[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle (r • x) x = 0 := (ob).oangle_smul_left_self_of_nonneg x hr /-- The angle between a vector and a nonnegative multiple of that vector is 0. -/ @[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle x (r • x) = 0 := (ob).oangle_smul_right_self_of_nonneg x hr /-- The angle between two nonnegative multiples of the same vector is 0. -/ @[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : o.oangle (r₁ • x) (r₂ • x) = 0 := (ob).oangle_smul_smul_self_of_nonneg x hr₁ hr₂ /-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle (r • x) y = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_smul_left_of_ne_zero x y hr /-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle x (r • y) = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_smul_right_of_ne_zero x y hr /-- Twice the angle between a multiple of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle (r • x) x = 0 := (ob).two_zsmul_oangle_smul_left_self x /-- Twice the angle between a vector and a multiple of that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle x (r • x) = 0 := (ob).two_zsmul_oangle_smul_right_self x /-- Twice the angle between two multiples of a vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} : (2 : ℤ) • o.oangle (r₁ • x) (r₂ • x) = 0 := (ob).two_zsmul_oangle_smul_smul_self x /-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/ lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ∥x∥ = ∥y∥ ∧ o.oangle x y = 0 := (ob).eq_iff_norm_eq_and_oangle_eq_zero x y /-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/ lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : x = y ↔ o.oangle x y = 0 := (ob).eq_iff_oangle_eq_zero_of_norm_eq h /-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/ lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : o.oangle x y = 0) : x = y ↔ ∥x∥ = ∥y∥ := (ob).eq_iff_norm_eq_of_oangle_eq_zero h /-- Given three nonzero vectors, the angle between the first and the second plus the angle between the second and the third equals the angle between the first and the third. -/ @[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z = o.oangle x z := (ob).oangle_add hx hy hz /-- Given three nonzero vectors, the angle between the second and the third plus the angle between the first and the second equals the angle between the first and the third. -/ @[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle y z + o.oangle x y = o.oangle x z := (ob).oangle_add_swap hx hy hz /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the first and the second equals the angle between the second and the third. -/ @[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle x y = o.oangle y z := (ob).oangle_sub_left hx hy hz /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the second and the third equals the angle between the first and the second. -/ @[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle y z = o.oangle x y := (ob).oangle_sub_right hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/ @[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z + o.oangle z x = 0 := (ob).oangle_add_cyc3 hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle (-x) y + o.oangle (-y) z + o.oangle (-z) x = π := (ob).oangle_add_cyc3_neg_left hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x (-y) + o.oangle y (-z) + o.oangle z (-x) = π := (ob).oangle_add_cyc3_neg_right hx hy hz /-- Pons asinorum, oriented vector angle form. -/ lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : o.oangle x (x - y) = o.oangle (y - x) y := (ob).oangle_sub_eq_oangle_sub_rev_of_norm_eq h /-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented vector angle form. -/ lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ∥x∥ = ∥y∥) : o.oangle y x = π - (2 : ℤ) • o.oangle (y - x) y := (ob).oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hn h /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) (hxy : ∥x∥ = ∥y∥) (hxz : ∥x∥ = ∥z∥) : o.oangle y z = (2 : ℤ) • o.oangle (y - x) (z - x) := (ob).oangle_eq_two_zsmul_oangle_sub_of_norm_eq hxyne hxzne hxy hxz /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form with radius specified. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) {r : ℝ} (hx : ∥x∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : o.oangle y z = (2 : ℤ) • o.oangle (y - x) (z - x) := (ob).oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hxyne hxzne hx hy hz /-- Oriented vector angle version of "angles in same segment are equal" and "opposite angles of a cyclic quadrilateral add to π", for oriented angles mod π (for which those are the same result), represented here as equality of twice the angles. -/ lemma two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq {x₁ x₂ y z : V} (hx₁yne : x₁ ≠ y) (hx₁zne : x₁ ≠ z) (hx₂yne : x₂ ≠ y) (hx₂zne : x₂ ≠ z) {r : ℝ} (hx₁ : ∥x₁∥ = r) (hx₂ : ∥x₂∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : (2 : ℤ) • o.oangle (y - x₁) (z - x₁) = (2 : ℤ) • o.oangle (y - x₂) (z - x₂) := (ob).two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq hx₁yne hx₁zne hx₂yne hx₂zne hx₁ hx₂ hy hz /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := (ob).rotation θ /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : ((o.rotation θ).to_linear_equiv : V →ₗ[ℝ] V).det = 1 := (ob).det_rotation θ /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (o.rotation θ).to_linear_equiv.det = 1 := (ob).linear_equiv_det_rotation θ /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (o.rotation θ).symm = o.rotation (-θ) := (ob).rotation_symm θ /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : o.rotation 0 = linear_isometry_equiv.refl ℝ V := (ob).rotation_zero /-- Rotation by π is negation. -/ lemma rotation_pi : o.rotation π = linear_isometry_equiv.neg ℝ := (ob).rotation_pi /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (o.rotation θ₁).trans (o.rotation θ₂) = o.rotation (θ₂ + θ₁) := (ob).rotation_trans θ₁ θ₂ /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) y = o.oangle x y - θ := (ob).oangle_rotation_left hx hy θ /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ y) = o.oangle x y + θ := (ob).oangle_rotation_right hx hy θ /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) x = -θ := (ob).oangle_rotation_self_left hx θ /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ x) = θ := (ob).oangle_rotation_self_right hx θ /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : o.oangle (o.rotation (o.oangle x y) x) y = 0 := (ob).oangle_rotation_oangle_left x y /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : o.oangle y (o.rotation (o.oangle x y) x) = 0 := (ob).oangle_rotation_oangle_right x y /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : o.oangle (o.rotation θ x) (o.rotation θ y) = o.oangle x y := (ob).oangle_rotation x y θ /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : o.rotation θ x = x ↔ θ = 0 := (ob).rotation_eq_self_iff_angle_eq_zero hx θ /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = o.rotation θ x ↔ θ = 0 := (ob).eq_rotation_self_iff_angle_eq_zero hx θ /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : o.rotation θ x = x ↔ x = 0 ∨ θ = 0 := (ob).rotation_eq_self_iff x θ /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = o.rotation θ x ↔ x = 0 ∨ θ = 0 := (ob).eq_rotation_self_iff x θ /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : o.rotation (o.oangle x y) x = y ↔ ∥x∥ = ∥y∥ := (ob).rotation_oangle_eq_iff_norm_eq x y /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ y = (∥y∥ / ∥x∥) • o.rotation θ x := (ob).oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy θ /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x := (ob).oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy θ /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (∥y∥ / ∥x∥) • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := (ob).oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero θ /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := (ob).oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero θ /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = o.rotation θ := (ob).exists_linear_isometry_equiv_eq_of_det_pos hd /-- The angle between two vectors, with respect to an orientation given by `orientation.map` with a linear isometric equivalence, equals the angle between those two vectors, transformed by the inverse of that equivalence, with respect to the original orientation. -/ @[simp] lemma oangle_map (x y : V) (f : V ≃ₗᵢ[ℝ] V) : (orientation.map (fin 2) f.to_linear_equiv o).oangle x y = o.oangle (f.symm x) (f.symm y) := begin convert (ob).oangle_map x y f using 1, refine orthonormal.oangle_eq_of_orientation_eq _ _ _ _ _, simp_rw [basis.orientation_map, orientation.fin_orthonormal_basis_orientation] end /-- `orientation.oangle` equals `orthonormal.oangle` for any orthonormal basis with that orientation. -/ lemma oangle_eq_basis_oangle {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) (h : b.orientation = o) (x y : V) : o.oangle x y = hb.oangle x y := begin rw oangle, refine orthonormal.oangle_eq_of_orientation_eq _ _ _ _ _, simp [h] end /-- Negating the orientation negates the value of `oangle`. -/ lemma oangle_neg_orientation_eq_neg (x y : V) : (-o).oangle x y = -(o.oangle x y) := begin simp_rw oangle, refine orthonormal.oangle_eq_neg_of_orientation_eq_neg _ _ _ _ _, simp_rw orientation.fin_orthonormal_basis_orientation end /-- `orientation.rotation` equals `orthonormal.rotation` for any orthonormal basis with that orientation. -/ lemma rotation_eq_basis_rotation {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) (h : b.orientation = o) (θ : ℝ) : o.rotation θ = hb.rotation θ := begin rw rotation, refine orthonormal.rotation_eq_of_orientation_eq _ _ _ _, simp [h] end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_neg_orientation_eq_neg (θ : real.angle) : (-o).rotation θ = o.rotation (-θ) := begin simp_rw rotation, refine orthonormal.rotation_eq_rotation_neg_of_orientation_eq_neg _ _ _ _, simp_rw orientation.fin_orthonormal_basis_orientation end /-- The inner product of two vectors is the product of the norms and the cosine of the oriented angle between the vectors. -/ lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) : ⟪x, y⟫ = ∥x∥ * ∥y∥ * real.angle.cos (o.oangle x y) := (ob).inner_eq_norm_mul_norm_mul_cos_oangle x y /-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by the product of the norms. -/ lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = ⟪x, y⟫ / (∥x∥ * ∥y∥) := (ob).cos_oangle_eq_inner_div_norm_mul_norm hx hy /-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented angle. -/ lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = real.cos (inner_product_geometry.angle x y) := (ob).cos_oangle_eq_cos_angle hx hy /-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/ lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x y = inner_product_geometry.angle x y ∨ o.oangle x y = -inner_product_geometry.angle x y := (ob).oangle_eq_angle_or_eq_neg_angle hx hy end orientation
734dd45f49bf57a3f03998c4d03d06f8edfff4d3
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic16.lean
9afd251038746d2096f4668d7538e02938f78f32
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
317
lean
import standard using tactic variable A : Type.{1} variable f : A → A → A theorem tst {a b c : A} (H1 : a = b) (H2 : b = c) : f a (f b b) = f b (f c c) := by discard (apply (subst H1)) 3; -- discard the first 3 solutions produced by apply trace "after subst H1"; apply (subst H2); apply refl
5014555580bad0c11c1f81bf37e3bb59d16b62fd
076f5040b63237c6dd928c6401329ed5adcb0e44
/assignments/hw9_extra_credit_exam_prep.lean
21aa6aea14cc8871fb5f0ec52ef9f3f746855560
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
5,434
lean
namespace hidden -- you can ignore this /- 1a. Define a polymorphic tree type. A tree of objects of type α is either empty or it is a value of type α along with two smaller trees of the same kind. You can call them left and right respectively. -/ /- 1b. Define a polymorphic function, is_empty, that takes a value of type, tree α, and that returns Boolean tt if it is empty and ff otherwise. -/ /- 1b. Define a polymorphic function, num_nodes, that takes a value of type, tree α, and that returns the number of nodes in the tree. -/ /- 2. A bit has one of two values. Imagine a type, let's call it trit, with three values (e.g., true, false, and dont-know). How many binary functions are there, taking two values of tihs type and returning a value of the same type? -/ /- 3. Define a function, sum_squares, that takes a natural number, n, as an argument, and that returns the sum of the squaress of all of the natural numbers from 0 to n, inclusive. -/ /- 4a. We represent a binary relation, R, on a set of values of some type, α, as a predicate with two arguments. In Lean such a predicate is of type α → α → Prop. A property of such a relation is a predicate on a relation, and so is of type (α → α → Prop) → Prop. Here is the definition of a property of binary relations called asymmetry. A relation is said to be asymmetric if whenever (x, y) is in the relation, (y, x) is not. For example, the less-than relation on natural numbers is asymmetric. -/ def asymmetric {α : Type} (R : α → α → Prop) : Prop := ∀ (x y : α), R x y → ¬ R y x /- Similarly, a relation is said to be irreflexive if for all x, (x, x) is not in the relation. For example, an "is-unequal-to" relation on the natural numbers would include (3, 4) because 3 is unequal to 4, but it would not include (3, 3) because 3 is not unqual to 3. Write a formal definition of irreflexive in the style of the definition of asymmetric above. Start the actual definition (after the :=) with ∀ (x : α). -/ def irreflexive {α : Type} (R : α → α → Prop) : Prop := ∀ (x : α), ¬ R x x /- 4b. Prove that if a relation is asymmetric then it is irreflexive by completing the following proof. -/ theorem asy_imp_irr : ∀ (α : Type) (F : α → α → Prop), asymmetric F → irreflexive F := begin unfold asymmetric irreflexive, -- expand defs _ end /- 5. Prove the following. You may use a tactic script, as indicated here, or switch to another format for your proof. Whatever you are most comfortable with is fine. -/ example : ∀ (P Q R : Prop), (∀ (p : P), Q) → (∀ (q :Q), R) → (P ∨ Q) → R := begin _ end /- 6. Prove that every natural number, n, has a successor. Formalize this statement using universal and existential quantifiers: for every natural number n there exists a natural number m such that m is the successor of n. Then complete the proof. Finish what we've started for you. -/ example : ∀ (n : ℕ), _ := _ /- 7. Consider a binary relation, squares, on the natural numbers. A pair, (x, y), is in this relation if and only if y=x^2. Formalize this relation in Lean as a predicate, squares, with two natural number arguments and one proof constructor called intro. Then state and prove the simple proposition that the pair, (7, 49), is in this relation. -/ -- Answer here /- 8. This question asks you to model a little world. The world has people in it (a type) and there is a binary relation, parent_of, on people. What is means for a pair (x, y) to be in this relation is that x is a parent of y. -/ axiom Person : Type axiom ParentOf : Person → Person → Prop /- Define a GrandParentOf relation, such that (x, y) is in this relation if and only if x is a grand parent of y. What this means, of course, is that there is some z such that x is the parent of z and z is the parent of y. Define the GrandParentOf relation using an inductive type definition in the usual way. It needs only one constructor, which must enforce the condition that defines what it means "to be a grandparent of". -/ /- 9. In simple English explain what it means for a binary relation on a set to be * reflexive: * transitive: * symmetric: Give an example of an everyday mathematical relation other than equality that is transitive. Is the greater-than relation reflexive? Explain. Is it symmetric? Explain. -/ /- 10. Give a natural language proof, in your own words, showing that the square root of two is irrational. You may find the details of this proof easily by searching online. -/ /- 11. Prove formally that 0 ≠ 1, then translate your formal proof, step by step, into an English language proof, citing the reasoning principles that you use. What fundamental proof strategy is centrally involved in this proof? -/ /- 12. Lean includes the law of the excluded middle in a closed namespace called classical. The axiom goes by the name, classical.em. You may apply it to any proposition, P, to obtain a proof of P ∨ ¬ P. Use the law of the excluded middle to show that proof by contradiction is valid, as long as you accept em as an axiom. Hint: We covered this in class. -/ /- 13. Let's define a natural number to be cool if it's either 2 or 5 or the sum or the product of two cool numbers. Formalize this definition in Lean and then state and prove the proposition that 35 is cool. -/ end hidden
751638288482d93485846425873129b46c705367
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/projective.lean
9c6098ab570f83dd4fed9790385e1d97248380da
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,568
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import algebra.homology.exact import category_theory.limits.shapes.biproducts import category_theory.adjunction.limits import category_theory.limits.preserves.finite /-! # Projective objects and categories with enough projectives > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An object `P` is called projective if every morphism out of `P` factors through every epimorphism. A category `C` has enough projectives if every object admits an epimorphism from some projective object. `projective.over X` picks an arbitrary such projective object, and `projective.π X : projective.over X ⟶ X` is the corresponding epimorphism. Given a morphism `f : X ⟶ Y`, `projective.left f` is a projective object over `kernel f`, and `projective.d f : projective.left f ⟶ X` is the morphism `π (kernel f) ≫ kernel.ι f`. -/ noncomputable theory open category_theory open category_theory.limits open opposite universes v u namespace category_theory variables {C : Type u} [category.{v} C] /-- An object `P` is called projective if every morphism out of `P` factors through every epimorphism. -/ class projective (P : C) : Prop := (factors : ∀ {E X : C} (f : P ⟶ X) (e : E ⟶ X) [epi e], ∃ f', f' ≫ e = f) section /-- A projective presentation of an object `X` consists of an epimorphism `f : P ⟶ X` from some projective object `P`. -/ @[nolint has_nonempty_instance] structure projective_presentation (X : C) := (P : C) (projective : projective P . tactic.apply_instance) (f : P ⟶ X) (epi : epi f . tactic.apply_instance) attribute [instance] projective_presentation.projective projective_presentation.epi variables (C) /-- A category "has enough projectives" if for every object `X` there is a projective object `P` and an epimorphism `P ↠ X`. -/ class enough_projectives : Prop := (presentation : ∀ (X : C), nonempty (projective_presentation X)) end namespace projective /-- An arbitrarily chosen factorisation of a morphism out of a projective object through an epimorphism. -/ def factor_thru {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : P ⟶ E := (projective.factors f e).some @[simp] lemma factor_thru_comp {P X E : C} [projective P] (f : P ⟶ X) (e : E ⟶ X) [epi e] : factor_thru f e ≫ e = f := (projective.factors f e).some_spec section open_locale zero_object instance zero_projective [has_zero_object C] [has_zero_morphisms C] : projective (0 : C) := { factors := λ E X f e epi, by { use 0, ext, }} end lemma of_iso {P Q : C} (i : P ≅ Q) (hP : projective P) : projective Q := begin fsplit, introsI E X f e e_epi, obtain ⟨f', hf'⟩ := projective.factors (i.hom ≫ f) e, exact ⟨i.inv ≫ f', by simp [hf']⟩ end lemma iso_iff {P Q : C} (i : P ≅ Q) : projective P ↔ projective Q := ⟨of_iso i, of_iso i.symm⟩ /-- The axiom of choice says that every type is a projective object in `Type`. -/ instance (X : Type u) : projective X := { factors := λ E X' f e epi, ⟨λ x, ((epi_iff_surjective _).mp epi (f x)).some, by { ext x, exact ((epi_iff_surjective _).mp epi (f x)).some_spec, }⟩ } instance Type.enough_projectives : enough_projectives (Type u) := { presentation := λ X, ⟨{ P := X, f := 𝟙 X, }⟩, } instance {P Q : C} [has_binary_coproduct P Q] [projective P] [projective Q] : projective (P ⨿ Q) := { factors := λ E X' f e epi, by exactI ⟨coprod.desc (factor_thru (coprod.inl ≫ f) e) (factor_thru (coprod.inr ≫ f) e), by tidy⟩, } section local attribute [tidy] tactic.discrete_cases instance {β : Type v} (g : β → C) [has_coproduct g] [∀ b, projective (g b)] : projective (∐ g) := { factors := λ E X' f e epi, by exactI ⟨sigma.desc (λ b, factor_thru (sigma.ι g b ≫ f) e), by tidy⟩, } end instance {P Q : C} [has_zero_morphisms C] [has_binary_biproduct P Q] [projective P] [projective Q] : projective (P ⊞ Q) := { factors := λ E X' f e epi, by exactI ⟨biprod.desc (factor_thru (biprod.inl ≫ f) e) (factor_thru (biprod.inr ≫ f) e), by tidy⟩, } instance {β : Type v} (g : β → C) [has_zero_morphisms C] [has_biproduct g] [∀ b, projective (g b)] : projective (⨁ g) := { factors := λ E X' f e epi, by exactI ⟨biproduct.desc (λ b, factor_thru (biproduct.ι g b ≫ f) e), by tidy⟩, } lemma projective_iff_preserves_epimorphisms_coyoneda_obj (P : C) : projective P ↔ (coyoneda.obj (op P)).preserves_epimorphisms := ⟨λ hP, ⟨λ X Y f hf, (epi_iff_surjective _).2 $ λ g, have projective (unop (op P)), from hP, by exactI ⟨factor_thru g f, factor_thru_comp _ _⟩⟩, λ h, ⟨λ E X f e he, by exactI (epi_iff_surjective _).1 (infer_instance : epi ((coyoneda.obj (op P)).map e)) f⟩⟩ section enough_projectives variables [enough_projectives C] /-- `projective.over X` provides an arbitrarily chosen projective object equipped with an epimorphism `projective.π : projective.over X ⟶ X`. -/ def over (X : C) : C := (enough_projectives.presentation X).some.P instance projective_over (X : C) : projective (over X) := (enough_projectives.presentation X).some.projective /-- The epimorphism `projective.π : projective.over X ⟶ X` from the arbitrarily chosen projective object over `X`. -/ def π (X : C) : over X ⟶ X := (enough_projectives.presentation X).some.f instance π_epi (X : C) : epi (π X) := (enough_projectives.presentation X).some.epi section variables [has_zero_morphisms C] {X Y : C} (f : X ⟶ Y) [has_kernel f] /-- When `C` has enough projectives, the object `projective.syzygies f` is an arbitrarily chosen projective object over `kernel f`. -/ @[derive projective] def syzygies : C := over (kernel f) /-- When `C` has enough projectives, `projective.d f : projective.syzygies f ⟶ X` is the composition `π (kernel f) ≫ kernel.ι f`. (When `C` is abelian, we have `exact (projective.d f) f`.) -/ abbreviation d : syzygies f ⟶ X := π (kernel f) ≫ kernel.ι f end end enough_projectives end projective namespace adjunction variables {D : Type*} [category D] {F : C ⥤ D} {G : D ⥤ C} lemma map_projective (adj : F ⊣ G) [G.preserves_epimorphisms] (P : C) (hP : projective P) : projective (F.obj P) := ⟨λ X Y f g, begin introI, rcases hP.factors (adj.unit.app P ≫ G.map f) (G.map g), use F.map w ≫ adj.counit.app X, rw [category.assoc, ←adjunction.counit_naturality, ←category.assoc, ←F.map_comp, h], simp, end⟩ lemma projective_of_map_projective (adj : F ⊣ G) [full F] [faithful F] (P : C) (hP : projective (F.obj P)) : projective P := ⟨λ X Y f g, begin introI, haveI : preserves_colimits_of_size.{0 0} F := adj.left_adjoint_preserves_colimits, rcases @hP.1 (F.map f) (F.map g), use adj.unit.app _ ≫ G.map w ≫ (inv $ adj.unit.app _), refine faithful.map_injective F _, simpa end⟩ /-- Given an adjunction `F ⊣ G` such that `G` preserves epis, `F` maps a projective presentation of `X` to a projective presentation of `F(X)`. -/ def map_projective_presentation (adj : F ⊣ G) [G.preserves_epimorphisms] (X : C) (Y : projective_presentation X) : projective_presentation (F.obj X) := { P := F.obj Y.P, projective := adj.map_projective _ Y.projective, f := F.map Y.f, epi := by haveI : preserves_colimits_of_size.{0 0} F := adj.left_adjoint_preserves_colimits; apply_instance } end adjunction namespace equivalence variables {D : Type*} [category D] (F : C ≌ D) /-- Given an equivalence of categories `F`, a projective presentation of `F(X)` induces a projective presentation of `X.` -/ def projective_presentation_of_map_projective_presentation (X : C) (Y : projective_presentation (F.functor.obj X)) : projective_presentation X := { P := F.inverse.obj Y.P, projective := adjunction.map_projective F.symm.to_adjunction Y.P Y.projective, f := F.inverse.map Y.f ≫ F.unit_inv.app _, epi := epi_comp _ _ } lemma enough_projectives_iff (F : C ≌ D) : enough_projectives C ↔ enough_projectives D := begin split, all_goals { intro H, constructor, intro X, constructor }, { exact F.symm.projective_presentation_of_map_projective_presentation _ (nonempty.some (H.presentation (F.inverse.obj X))) }, { exact F.projective_presentation_of_map_projective_presentation X (nonempty.some (H.presentation (F.functor.obj X))) }, end end equivalence open projective section variables [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- Given a projective object `P` mapping via `h` into the middle object `R` of a pair of exact morphisms `f : Q ⟶ R` and `g : R ⟶ S`, such that `h ≫ g = 0`, there is a lift of `h` to `Q`. -/ def exact.lift {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) (hfg : exact f g) (w : h ≫ g = 0) : P ⟶ Q := factor_thru (factor_thru (factor_thru_kernel_subobject g h w) (image_to_kernel f g hfg.w)) (factor_thru_image_subobject f) @[simp] lemma exact.lift_comp {P Q R S : C} [projective P] (h : P ⟶ R) (f : Q ⟶ R) (g : R ⟶ S) (hfg : exact f g) (w : h ≫ g = 0) : exact.lift h f g hfg w ≫ f = h := begin simp [exact.lift], conv_lhs { congr, skip, rw ← image_subobject_arrow_comp f, }, rw [←category.assoc, factor_thru_comp, ←image_to_kernel_arrow, ←category.assoc, category_theory.projective.factor_thru_comp, factor_thru_kernel_subobject_comp_arrow], end end end category_theory
fe5fa967f6c27d67b070ba64c37b97a7d3470b05
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/uniform_ring.lean
bcda3bbbc3c498c122364cd4ffd558a00c6b5305
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
7,685
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings with uniform structure. -/ import topology.algebra.group_completion import topology.algebra.ring open classical set filter topological_space add_comm_group open_locale classical noncomputable theory namespace uniform_space.completion open dense_inducing uniform_space function variables (α : Type*) [ring α] [uniform_space α] instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩ @[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl variables {α} [topological_ring α] @[norm_cast] lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := ((dense_inducing_coe.prod dense_inducing_coe).extend_eq ((continuous_coe α).comp continuous_mul) (a, b)).symm variables [uniform_add_group α] lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) := begin haveI : is_Z_bilin ((coe ∘ uncurry (*)) : α × α → completion α) := { add_left := begin introv, change coe ((a + a')*b) = coe (a*b) + coe (a'*b), rw_mod_cast add_mul end, add_right := begin introv, change coe (a*(b + b')) = coe (a*b) + coe (a*b'), rw_mod_cast mul_add end }, have : continuous ((coe ∘ uncurry (*)) : α × α → completion α), from (continuous_coe α).comp continuous_mul, convert dense_inducing_coe.extend_Z_bilin dense_inducing_coe this, simp only [(*), curry, prod.mk.eta] end lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := continuous_mul.comp (continuous.prod_mk hf hg) instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.mul continuous_fst (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul continuous_fst (continuous.add (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))) (continuous.add (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.add continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.add (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } /-- The map from a uniform ring to its completion, as a ring homomorphism. -/ def coe_ring_hom : α →+* completion α := ⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩ universes u variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous f) /-- The completion extension as a ring morphism. -/ def extension_hom [complete_space β] [separated_space β] : completion α →+* β := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { to_fun := completion.extension f, map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero], map_add' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, f.map_add]), map_one' := by rw [← coe_one, extension_coe hf, f.map_one], map_mul' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_mul) ((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) } instance top_ring_compl : topological_ring (completion α) := { continuous_add := continuous_add, continuous_mul := continuous_mul, continuous_neg := continuous_neg } /-- The completion map as a ring morphism. -/ def map_ring_hom : completion α →+* completion β := extension_hom (coe_ring_hom.comp f) ((continuous_coe β).comp hf) variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] instance : comm_ring (completion R) := { mul_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_fst.mul continuous_snd) (continuous_snd.mul continuous_fst)) (assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]), ..completion.ring } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ assume x y, group_separation_rel x y lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient := by rw [@ring_sep_rel α r]; refl /-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly continuous, get an equivalence between the separated quotient of `α` and the quotient ring corresponding to the closure of zero. -/ def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient := quotient.congr_right $ assume x y, group_separation_rel x y /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance topological_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel}, simp [uniform_space.comm_ring] end end uniform_space
bf033d9d96a46fe9d5d8fa03724eed71b01b49c2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/char_p/algebra.lean
fa243cb834192a1b0f73588d2c15a2f7e7bd8d1f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
3,440
lean
/- Copyright (c) 2021 Jon Eugster. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jon Eugster, Eric Wieser -/ import algebra.char_p.basic import ring_theory.localization import algebra.free_algebra /-! # Characteristics of algebras In this file we describe the characteristic of `R`-algebras. In particular we are interested in the characteristic of free algebras over `R` and the fraction field `fraction_ring R`. ## Main results - `char_p_of_injective_algebra_map` If `R →+* A` is an injective algebra map then `A` has the same characteristic as `R`. Instances constructed from this result: - Any `free_algebra R X` has the same characteristic as `R`. - The `fraction_ring R` of an integral domain `R` has the same characteristic as `R`. -/ /-- If the algebra map `R →+* A` is injective then `A` has the same characteristic as `R`. -/ lemma char_p_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) (p : ℕ) [char_p R p] : char_p A p := { cast_eq_zero_iff := λx, begin rw ←char_p.cast_eq_zero_iff R p x, change algebra_map ℕ A x = 0 ↔ algebra_map ℕ R x = 0, rw is_scalar_tower.algebra_map_apply ℕ R A x, refine iff.trans _ h.eq_iff, rw ring_hom.map_zero, end } /-- If the algebra map `R →+* A` is injective and `R` has characteristic zero then so does `A`. -/ lemma char_zero_of_injective_algebra_map {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (h : function.injective (algebra_map R A)) [char_zero R] : char_zero A := { cast_injective := λ x y hxy, begin change algebra_map ℕ A x = algebra_map ℕ A y at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A x at hxy, rw is_scalar_tower.algebra_map_apply ℕ R A y at hxy, exact char_zero.cast_injective (h hxy), end } -- `char_p.char_p_to_char_zero A _ (char_p_of_injective_algebra_map h 0)` does not work -- here as it would require `ring A`. namespace free_algebra variables {R X : Type*} [comm_semiring R] (p : ℕ) /-- If `R` has characteristic `p`, then so does `free_algebra R X`. -/ instance char_p [char_p R p] : char_p (free_algebra R X) p := char_p_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective p /-- If `R` has characteristic `0`, then so does `free_algebra R X`. -/ instance char_zero [char_zero R] : char_zero (free_algebra R X) := char_zero_of_injective_algebra_map free_algebra.algebra_map_left_inverse.injective end free_algebra namespace is_fraction_ring variables (R : Type*) {K : Type*} [integral_domain R] [field K] [algebra R K] [is_fraction_ring R K] variables (p : ℕ) /-- If `R` has characteristic `p`, then so does Frac(R). -/ lemma char_p_of_is_fraction_ring [char_p R p] : char_p K p := char_p_of_injective_algebra_map (is_fraction_ring.injective R K) p /-- If `R` has characteristic `p`, then so does `fraction_ring R`. -/ instance char_p [char_p R p] : char_p (fraction_ring R) p := char_p_of_is_fraction_ring R p /-- If `R` has characteristic `0`, then so does Frac(R). -/ lemma char_zero_of_is_fraction_ring [char_zero R] : char_zero K := @char_p.char_p_to_char_zero K _ (char_p_of_is_fraction_ring R 0) /-- If `R` has characteristic `0`, then so does `fraction_ring R`. -/ instance char_zero [char_zero R] : char_zero (fraction_ring R) := char_zero_of_is_fraction_ring R end is_fraction_ring
088e6925208c154df6775dd4770756a667777a2a
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/continued_fractions/computation/translations.lean
eb859444ed2841ae324ef075e9f4b95aff9e87c3
[ "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
10,521
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.basic import algebra.continued_fractions.translations /-! # Basic Translation Lemmas Between Structures Defined for Computing Continued Fractions ## Summary This is a collection of simple lemmas between the different structures used for the computation of continued fractions defined in `algebra.continued_fractions.computation.basic`. The file consists of three sections: 1. Recurrences and inversion lemmas for `int_fract_pair.stream`: these lemmas give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. 2. Translation lemmas for the head term: these lemmas show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. 3. Translation lemmas for the sequence: these lemmas show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and the termination of one sequence implies the termination of another sequence. ## Main Theorems - `succ_nth_stream_eq_some_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. - `succ_nth_stream_eq_none_iff` gives as a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. - `nth_of_eq_some_of_succ_nth_int_fract_pair_stream` and `nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero` show how the entries of the sequence of the computed continued fraction can be obtained from the stream of integer and fractional parts. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf /- Fix a discrete linear ordered floor field and a value `v`. -/ variables {K : Type*} [linear_ordered_field K] [floor_ring K] {v : K} namespace int_fract_pair /-! ### Recurrences and Inversion Lemmas for `int_fract_pair.stream` Here we state some lemmas that give us inversion rules and recurrences for the computation of the stream of integer and fractional parts of a value. -/ variable {n : ℕ} lemma stream_eq_none_of_fr_eq_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_eq_zero : ifp_n.fr = 0) : int_fract_pair.stream v (n + 1) = none := begin cases ifp_n with _ fr, change fr = 0 at nth_fr_eq_zero, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_eq_zero] end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of termination. -/ lemma succ_nth_stream_eq_none_iff : int_fract_pair.stream v (n + 1) = none ↔ (int_fract_pair.stream v n = none ∨ ∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0) := begin cases stream_nth_eq : (int_fract_pair.stream v n) with ifp, case option.none : { simp [stream_nth_eq, int_fract_pair.stream] }, case option.some : { cases ifp with _ fr, cases decidable.em (fr = 0); finish [int_fract_pair.stream] } end /-- Gives a recurrence to compute the `n + 1`th value of the sequence of integer and fractional parts of a value in case of non-termination. -/ lemma succ_nth_stream_eq_some_iff {ifp_succ_n : int_fract_pair K} : int_fract_pair.stream v (n + 1) = some ifp_succ_n ↔ ∃ (ifp_n : int_fract_pair K), int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n := begin split, { assume stream_succ_nth_eq, have : int_fract_pair.stream v (n + 1) ≠ none, by simp [stream_succ_nth_eq], have : ¬int_fract_pair.stream v n = none ∧ ¬(∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0), by { have not_none_not_fract_zero, from (not_iff_not_of_iff succ_nth_stream_eq_none_iff).elim_left this, exact (not_or_distrib.elim_left not_none_not_fract_zero) }, cases this with stream_nth_ne_none nth_fr_ne_zero, replace nth_fr_ne_zero : ∀ ifp, int_fract_pair.stream v n = some ifp → ifp.fr ≠ 0, by simpa using nth_fr_ne_zero, obtain ⟨ifp_n, stream_nth_eq⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n, from option.ne_none_iff_exists'.mp stream_nth_ne_none, existsi ifp_n, have ifp_n_fr_ne_zero : ifp_n.fr ≠ 0, from nth_fr_ne_zero ifp_n stream_nth_eq, cases ifp_n with _ ifp_n_fr, suffices : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by simpa [stream_nth_eq, ifp_n_fr_ne_zero], simp only [int_fract_pair.stream, stream_nth_eq, ifp_n_fr_ne_zero, option.some_bind, if_false] at stream_succ_nth_eq, injection stream_succ_nth_eq }, { rintro ⟨⟨_⟩, ifp_n_props⟩, finish [int_fract_pair.stream, ifp_n_props] } end lemma exists_succ_nth_stream_of_fr_zero {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) (succ_nth_fr_eq_zero : ifp_succ_n.fr = 0) : ∃ ifp_n : int_fract_pair K, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ := begin -- get the witness from `succ_nth_stream_eq_some_iff` and prove that it has the additional -- properties rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, nth_fr_ne_zero, _⟩, existsi ifp_n, cases ifp_n with _ ifp_n_fr, suffices : ifp_n_fr⁻¹ = ⌊ifp_n_fr⁻¹⌋, by simpa [stream_nth_eq], have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by finish, cases ifp_succ_n with _ ifp_succ_n_fr, change ifp_succ_n_fr = 0 at succ_nth_fr_eq_zero, have : int.fract ifp_n_fr⁻¹ = ifp_succ_n_fr, by injection this, have : int.fract ifp_n_fr⁻¹ = 0, by rwa [succ_nth_fr_eq_zero] at this, calc ifp_n_fr⁻¹ = int.fract ifp_n_fr⁻¹ + ⌊ifp_n_fr⁻¹⌋ : by rw (int.fract_add_floor ifp_n_fr⁻¹) ... = ⌊ifp_n_fr⁻¹⌋ : by simp [‹int.fract ifp_n_fr⁻¹ = 0›] end end int_fract_pair section head /-! ### Translation of the Head Term Here we state some lemmas that show us that the head term of the computed continued fraction of a value `v` is `⌊v⌋` and how this head term is moved along the structures used in the computation process. -/ /-- The head term of the sequence with head of `v` is just the integer part of `v`. -/ @[simp] lemma int_fract_pair.seq1_fst_eq_of : (int_fract_pair.seq1 v).fst = int_fract_pair.of v := rfl lemma of_h_eq_int_fract_pair_seq1_fst_b : (gcf.of v).h = (int_fract_pair.seq1 v).fst.b := by { cases aux_seq_eq : (int_fract_pair.seq1 v), simp [gcf.of, aux_seq_eq] } /-- The head term of the gcf of `v` is `⌊v⌋`. -/ @[simp] lemma of_h_eq_floor : (gcf.of v).h = ⌊v⌋ := by simp [of_h_eq_int_fract_pair_seq1_fst_b, int_fract_pair.of] end head section sequence /-! ### Translation of the Sequences Here we state some lemmas that show how the sequences of the involved structures (`int_fract_pair.stream`, `int_fract_pair.seq1`, and `generalized_continued_fraction.of`) are connected, i.e. how the values are moved along the structures and how the termination of one sequence implies the termination of another sequence. -/ variable {n : ℕ} lemma int_fract_pair.nth_seq1_eq_succ_nth_stream : (int_fract_pair.seq1 v).snd.nth n = (int_fract_pair.stream v) (n + 1) := rfl section termination /-! #### Translation of the Termination of the Sequences Let's first show how the termination of one sequence implies the termination of another sequence. -/ lemma of_terminated_at_iff_int_fract_pair_seq1_terminated_at : (gcf.of v).terminated_at n ↔ (int_fract_pair.seq1 v).snd.terminated_at n := begin rw [gcf.terminated_at_iff_s_none, gcf.of], rcases (int_fract_pair.seq1 v) with ⟨head, ⟨st⟩⟩, cases st_n_eq : st n; simp [gcf.of, st_n_eq, seq.map, seq.nth, stream.map, seq.terminated_at, stream.nth] end lemma of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none : (gcf.of v).terminated_at n ↔ int_fract_pair.stream v (n + 1) = none := by rw [of_terminated_at_iff_int_fract_pair_seq1_terminated_at, seq.terminated_at, int_fract_pair.nth_seq1_eq_succ_nth_stream] end termination section values /-! #### Translation of the Values of the Sequence Now let's show how the values of the sequences correspond to one another. -/ lemma int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some {gp_n : gcf.pair K} (s_nth_eq : (gcf.of v).s.nth n = some gp_n) : ∃ (ifp : int_fract_pair K), int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b := begin obtain ⟨ifp, stream_succ_nth_eq, gp_n_eq⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ gcf.pair.mk 1 (ifp.b : K) = gp_n, by { unfold gcf.of int_fract_pair.seq1 at s_nth_eq, rwa [seq.map_tail, seq.nth_tail, seq.map_nth, option.map_eq_some'] at s_nth_eq }, cases gp_n_eq, injection gp_n_eq with _ ifp_b_eq_gp_n_b, existsi ifp, exact ⟨stream_succ_nth_eq, ifp_b_eq_gp_n_b⟩ end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the integer parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_succ_nth_int_fract_pair_stream {ifp_succ_n : int_fract_pair K} (stream_succ_nth_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (gcf.of v).s.nth n = some ⟨1, ifp_succ_n.b⟩ := begin unfold gcf.of int_fract_pair.seq1, rw [seq.map_tail, seq.nth_tail, seq.map_nth], simp [seq.nth, stream_succ_nth_eq] end /-- Shows how the entries of the sequence of the computed continued fraction can be obtained by the fractional parts of the stream of integer and fractional parts. -/ lemma nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero {ifp_n : int_fract_pair K} (stream_nth_eq : int_fract_pair.stream v n = some ifp_n) (nth_fr_ne_zero : ifp_n.fr ≠ 0) : (gcf.of v).s.nth n = some ⟨1, (int_fract_pair.of ifp_n.fr⁻¹).b⟩ := have int_fract_pair.stream v (n + 1) = some (int_fract_pair.of ifp_n.fr⁻¹), by { cases ifp_n, simp [int_fract_pair.stream, stream_nth_eq, nth_fr_ne_zero], refl }, nth_of_eq_some_of_succ_nth_int_fract_pair_stream this end values end sequence end generalized_continued_fraction
7f872153aaf652f9540d1a1888d35e2832cb299a
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/rigid/of_equivalence.lean
567fa184962d70623557e2d54272e0f1da6e6a0b
[ "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,302
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.rigid.basic /-! # Transport rigid structures over a monoidal equivalence. -/ noncomputable theory namespace category_theory variables {C D : Type*} [category C] [category D] [monoidal_category C] [monoidal_category D] variables (F : monoidal_functor C D) /-- Given candidate data for an exact pairing, which is sent by a faithful monoidal functor to an exact pairing, the equations holds automatically. -/ def exact_pairing_of_faithful [faithful F.to_functor] {X Y : C} (eval : Y ⊗ X ⟶ 𝟙_ C) (coeval : 𝟙_ C ⟶ X ⊗ Y) [exact_pairing (F.obj X) (F.obj Y)] (map_eval : F.map eval = inv (F.μ _ _) ≫ ε_ _ _ ≫ F.ε) (map_coeval : F.map coeval = inv F.ε ≫ η_ _ _ ≫ F.μ _ _) : exact_pairing X Y := { evaluation := eval, coevaluation := coeval, evaluation_coevaluation' := F.to_functor.map_injective (by simp [map_eval, map_coeval, monoidal_functor.map_tensor]), coevaluation_evaluation' := F.to_functor.map_injective (by simp [map_eval, map_coeval, monoidal_functor.map_tensor]), } /-- Given a pair of objects which are sent by a fully faithful functor to a pair of objects with an exact pairing, we get an exact pairing. -/ def exact_pairing_of_fully_faithful [full F.to_functor] [faithful F.to_functor] (X Y : C) [exact_pairing (F.obj X) (F.obj Y)] : exact_pairing X Y := exact_pairing_of_faithful F (F.to_functor.preimage (inv (F.μ _ _) ≫ ε_ _ _ ≫ F.ε)) (F.to_functor.preimage (inv F.ε ≫ η_ _ _ ≫ F.μ _ _)) (by simp) (by simp) /-- Pull back a left dual along an equivalence. -/ def has_left_dual_of_equivalence [is_equivalence F.to_functor] (X : C) [has_left_dual (F.obj X)] : has_left_dual X := { left_dual := F.to_functor.inv.obj (ᘁ(F.obj X)), exact := begin apply exact_pairing_of_fully_faithful F _ _, apply exact_pairing_congr_left (F.to_functor.as_equivalence.counit_iso.app _), dsimp, apply_instance, end } /-- Pull back a right dual along an equivalence. -/ def has_right_dual_of_equivalence [is_equivalence F.to_functor] (X : C) [has_right_dual (F.obj X)] : has_right_dual X := { right_dual := F.to_functor.inv.obj (F.obj X)ᘁ, exact := begin apply exact_pairing_of_fully_faithful F _ _, apply exact_pairing_congr_right (F.to_functor.as_equivalence.counit_iso.app _), dsimp, apply_instance, end } /-- Pull back a left rigid structure along an equivalence. -/ def left_rigid_category_of_equivalence [is_equivalence F.to_functor] [left_rigid_category D] : left_rigid_category C := { left_dual := λ X, has_left_dual_of_equivalence F X, } /-- Pull back a right rigid structure along an equivalence. -/ def right_rigid_category_of_equivalence [is_equivalence F.to_functor] [right_rigid_category D] : right_rigid_category C := { right_dual := λ X, has_right_dual_of_equivalence F X, } /-- Pull back a rigid structure along an equivalence. -/ def rigid_category_of_equivalence [is_equivalence F.to_functor] [rigid_category D] : rigid_category C := { left_dual := λ X, has_left_dual_of_equivalence F X, right_dual := λ X, has_right_dual_of_equivalence F X, } end category_theory
1b3960aba203348194f70cc204e9431ed442486a
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/meta/expr.lean
487ad61557cde5a30eb7843946c6db544bb471e0
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
27,674
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
2eacb46e2167b9fe9896fbe126f6d8f27b4f7b46
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/model_theory/types.lean
bcc49d9b00d113a00d805fdce1bf1b9ddb714037
[ "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
7,745
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.satisfiability /-! # Type Spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the space of complete types over a first-order theory. (Note that types in model theory are different from types in type theory.) ## Main Definitions * `first_order.language.Theory.complete_type`: `T.complete_type α` consists of complete types over the theory `T` with variables `α`. * `first_order.language.Theory.type_of` is the type of a given tuple. * `first_order.language.Theory.realized_types`: `T.realized_types M α` is the set of types in `T.complete_type α` that are realized in `M` - that is, the type of some tuple in `M`. ## Main Results * `first_order.language.Theory.complete_type.nonempty_iff`: The space `T.complete_type α` is nonempty exactly when `T` is satisfiable. * `first_order.language.Theory.complete_type.exists_Model_is_realized_in`: Every type is realized in some model. ## Implementation Notes * Complete types are implemented as maximal consistent theories in an expanded language. More frequently they are described as maximal consistent sets of formulas, but this is equivalent. ## TODO * Connect `T.complete_type α` to sets of formulas `L.formula α`. -/ universes u v w w' open cardinal set open_locale cardinal first_order classical namespace first_order namespace language namespace Theory variables {L : language.{u v}} (T : L.Theory) (α : Type w) /-- A complete type over a given theory in a certain type of variables is a maximally consistent (with the theory) set of formulas in that type. -/ structure complete_type := (to_Theory : L[[α]].Theory) (subset' : (L.Lhom_with_constants α).on_Theory T ⊆ to_Theory) (is_maximal' : to_Theory.is_maximal) variables {T α} namespace complete_type instance : set_like (T.complete_type α) (L[[α]].sentence) := ⟨λ p, p.to_Theory, λ p q h, begin cases p, cases q, congr', end⟩ lemma is_maximal (p : T.complete_type α) : is_maximal (p : L[[α]].Theory) := p.is_maximal' lemma subset (p : T.complete_type α) : (L.Lhom_with_constants α).on_Theory T ⊆ (p : L[[α]].Theory) := p.subset' lemma mem_or_not_mem (p : T.complete_type α) (φ : L[[α]].sentence) : φ ∈ p ∨ φ.not ∈ p := p.is_maximal.mem_or_not_mem φ lemma mem_of_models (p : T.complete_type α) {φ : L[[α]].sentence} (h : (L.Lhom_with_constants α).on_Theory T ⊨ φ) : φ ∈ p := (p.mem_or_not_mem φ).resolve_right (λ con, ((models_iff_not_satisfiable _).1 h) (p.is_maximal.1.mono (union_subset p.subset (singleton_subset_iff.2 con)))) lemma not_mem_iff (p : T.complete_type α) (φ : L[[α]].sentence) : φ.not ∈ p ↔ ¬ φ ∈ p := ⟨λ hf ht, begin have h : ¬ is_satisfiable ({φ, φ.not} : L[[α]].Theory), { rintro ⟨@⟨_, _, h, _⟩⟩, simp only [model_iff, mem_insert_iff, mem_singleton_iff, forall_eq_or_imp, forall_eq] at h, exact h.2 h.1 }, refine h (p.is_maximal.1.mono _), rw [insert_subset, singleton_subset_iff], exact ⟨ht, hf⟩, end, (p.mem_or_not_mem φ).resolve_left⟩ @[simp] lemma compl_set_of_mem {φ : L[[α]].sentence} : {p : T.complete_type α | φ ∈ p}ᶜ = {p : T.complete_type α | φ.not ∈ p} := ext (λ _, (not_mem_iff _ _).symm) lemma set_of_subset_eq_empty_iff (S : L[[α]].Theory) : {p : T.complete_type α | S ⊆ ↑p} = ∅ ↔ ¬ ((L.Lhom_with_constants α).on_Theory T ∪ S).is_satisfiable := begin rw [iff_not_comm, ← not_nonempty_iff_eq_empty, not_not, set.nonempty], refine ⟨λ h, ⟨⟨L[[α]].complete_theory h.some, (subset_union_left _ S).trans complete_theory.subset, complete_theory.is_maximal _ _⟩, (subset_union_right ((L.Lhom_with_constants α).on_Theory T) _).trans complete_theory.subset⟩, _⟩, rintro ⟨p, hp⟩, exact p.is_maximal.1.mono (union_subset p.subset hp), end lemma set_of_mem_eq_univ_iff (φ : L[[α]].sentence) : {p : T.complete_type α | φ ∈ p} = univ ↔ (L.Lhom_with_constants α).on_Theory T ⊨ φ := begin rw [models_iff_not_satisfiable, ← compl_empty_iff, compl_set_of_mem, ← set_of_subset_eq_empty_iff], simp, end lemma set_of_subset_eq_univ_iff (S : L[[α]].Theory) : {p : T.complete_type α | S ⊆ ↑p} = univ ↔ (∀ φ, φ ∈ S → (L.Lhom_with_constants α).on_Theory T ⊨ φ) := begin have h : {p : T.complete_type α | S ⊆ ↑p} = ⋂₀ ((λ φ, {p | φ ∈ p}) '' S), { ext, simp [subset_def] }, simp_rw [h, sInter_eq_univ, ← set_of_mem_eq_univ_iff], refine ⟨λ h φ φS, h _ ⟨_, φS, rfl⟩, _⟩, rintro h _ ⟨φ, h1, rfl⟩, exact h _ h1, end lemma nonempty_iff : nonempty (T.complete_type α) ↔ T.is_satisfiable := begin rw ← is_satisfiable_on_Theory_iff (Lhom_with_constants_injective L α), rw [nonempty_iff_univ_nonempty, nonempty_iff_ne_empty, ne.def, not_iff_comm, ← union_empty ((L.Lhom_with_constants α).on_Theory T), ← set_of_subset_eq_empty_iff], simp, end instance : nonempty (complete_type ∅ α) := nonempty_iff.2 (is_satisfiable_empty L) lemma Inter_set_of_subset {ι : Type*} (S : ι → L[[α]].Theory) : (⋂ (i : ι), {p : T.complete_type α | S i ⊆ p}) = {p | (⋃ (i : ι), S i) ⊆ p} := begin ext, simp only [mem_Inter, mem_set_of_eq, Union_subset_iff], end lemma to_list_foldr_inf_mem {p : T.complete_type α} {t : finset (L[[α]]).sentence} : t.to_list.foldr (⊓) ⊤ ∈ p ↔ (t : L[[α]].Theory) ⊆ ↑p := begin simp_rw [subset_def, ← set_like.mem_coe, p.is_maximal.mem_iff_models, models_sentence_iff, sentence.realize, formula.realize, bounded_formula.realize_foldr_inf, finset.mem_to_list], exact ⟨λ h φ hφ M, h _ _ hφ, λ h M φ hφ, h _ hφ _⟩, end end complete_type variables {M : Type w'} [L.Structure M] [nonempty M] [M ⊨ T] (T) /-- The set of all formulas true at a tuple in a structure forms a complete type. -/ def type_of (v : α → M) : T.complete_type α := begin haveI : (constants_on α).Structure M := constants_on.Structure v, exact { to_Theory := L[[α]].complete_theory M, subset' := model_iff_subset_complete_theory.1 ((Lhom.on_Theory_model _ T).2 infer_instance), is_maximal' := complete_theory.is_maximal _ _ }, end namespace complete_type variables {T} {v : α → M} @[simp] lemma mem_type_of {φ : L[[α]].sentence} : φ ∈ T.type_of v ↔ (formula.equiv_sentence.symm φ).realize v := begin letI : (constants_on α).Structure M := constants_on.Structure v, exact mem_complete_theory.trans (formula.realize_equiv_sentence_symm _ _ _).symm, end lemma formula_mem_type_of {φ : L.formula α} : formula.equiv_sentence φ ∈ T.type_of v ↔ φ.realize v := by simp end complete_type variable (M) /-- A complete type `p` is realized in a particular structure when there is some tuple `v` whose type is `p`. -/ @[simp] def realized_types (α : Type w) : set (T.complete_type α) := set.range (T.type_of : (α → M) → T.complete_type α) theorem exists_Model_is_realized_in (p : T.complete_type α) : ∃ (M : Theory.Model.{u v (max u v w)} T), p ∈ T.realized_types M α := begin obtain ⟨M⟩ := p.is_maximal.1, refine ⟨(M.subtheory_Model p.subset).reduct (L.Lhom_with_constants α), (λ a, (L.con a : M)), _⟩, refine set_like.ext (λ φ, _), simp only [complete_type.mem_type_of], refine (formula.realize_equiv_sentence_symm_con _ _).trans (trans (trans _ (p.is_maximal.is_complete.realize_sentence_iff φ M)) (p.is_maximal.mem_iff_models φ).symm), refl, end end Theory end language end first_order
d37c27de50852e39dd5c7bdcd0ad31b1cfa51c93
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/wfrecUnary.lean
a6c49a9bbe25080dd32b2539cfeb6884689db7ba
[ "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
192
lean
def f (n : Nat) : Nat := if h : n = 0 then 1 else 2 * f (n-1) termination_by' measure id decreasing_by simp [measure, id, invImage, InvImage, Nat.lt_wfRel] apply Nat.pred_lt h
5425f32b90e72f79b938d95211a8ba189fafb8cb
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/fun.lean
bc27d5df658010eb2c70a54634da87f5e91d0d33
[ "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
import logic open function bool constant f : num → bool constant g : num → num check f ∘ g ∘ g check (id : num → num) constant h : num → bool → num check swap h check swap h ff num.zero check (swap h ff num.zero : num) constant f1 : num → num → bool constant f2 : bool → num check (f1 on f2) ff tt
b024ce061d396bbb8e0901b66c81e042b3d7a561
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/matrix/dual.lean
46fc198a3949838d3af7fd97158c3044237dc425
[ "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,593
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, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.dual import linear_algebra.matrix.to_lin /-! # Dual space, linear maps and matrices. This file contains some results on the matrix corresponding to the transpose of a linear map (in the dual space). ## Tags matrix, linear_map, transpose, dual -/ open_locale matrix section transpose variables {K V₁ V₂ ι₁ ι₂ : Type*} [field K] [add_comm_group V₁] [module K V₁] [add_comm_group V₂] [module K V₂] [fintype ι₁] [fintype ι₂] [decidable_eq ι₁] [decidable_eq ι₂] {B₁ : basis ι₁ K V₁} {B₂ : basis ι₂ K V₂} @[simp] lemma linear_map.to_matrix_transpose (u : V₁ →ₗ[K] V₂) : linear_map.to_matrix B₂.dual_basis B₁.dual_basis (module.dual.transpose u) = (linear_map.to_matrix B₁ B₂ u)ᵀ := begin ext i j, simp only [linear_map.to_matrix_apply, module.dual.transpose_apply, B₁.dual_basis_repr, B₂.dual_basis_apply, matrix.transpose_apply, linear_map.comp_apply] end @[simp] lemma matrix.to_lin_transpose (M : matrix ι₁ ι₂ K) : matrix.to_lin B₁.dual_basis B₂.dual_basis Mᵀ = module.dual.transpose (matrix.to_lin B₂ B₁ M) := begin apply (linear_map.to_matrix B₁.dual_basis B₂.dual_basis).injective, rw [linear_map.to_matrix_to_lin, linear_map.to_matrix_transpose, linear_map.to_matrix_to_lin] end end transpose
29f26cdea307124ca6c50d265e5484774223ca46
e5169dbb8b1bea3ec2a32737442bc91a4a94b46a
/hott/cubical/cube.hlean
16e6824e324f034758cb6f6084f1a7faa491d42e
[ "Apache-2.0" ]
permissive
pazthor/lean
733b775e3123f6bbd2c4f7ccb5b560b467b76800
c923120db54276a22a75b12c69765765608a8e76
refs/heads/master
1,610,703,744,289
1,448,419,395,000
1,448,419,703,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,977
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Cubes -/ import .square open equiv is_equiv namespace eq inductive cube {A : Type} {a₀₀₀ : A} : Π{a₂₀₀ a₀₂₀ a₂₂₀ a₀₀₂ a₂₀₂ a₀₂₂ a₂₂₂ : A} {p₁₀₀ : a₀₀₀ = a₂₀₀} {p₀₁₀ : a₀₀₀ = a₀₂₀} {p₀₀₁ : a₀₀₀ = a₀₀₂} {p₁₂₀ : a₀₂₀ = a₂₂₀} {p₂₁₀ : a₂₀₀ = a₂₂₀} {p₂₀₁ : a₂₀₀ = a₂₀₂} {p₁₀₂ : a₀₀₂ = a₂₀₂} {p₀₁₂ : a₀₀₂ = a₀₂₂} {p₀₂₁ : a₀₂₀ = a₀₂₂} {p₁₂₂ : a₀₂₂ = a₂₂₂} {p₂₁₂ : a₂₀₂ = a₂₂₂} {p₂₂₁ : a₂₂₀ = a₂₂₂} (s₁₁₀ : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀) (s₁₁₂ : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂) (s₀₁₁ : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁) (s₂₁₁ : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁) (s₁₀₁ : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁) (s₁₂₁ : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁), Type := idc : cube ids ids ids ids ids ids variables {A B : Type} {a₀₀₀ a₂₀₀ a₀₂₀ a₂₂₀ a₀₀₂ a₂₀₂ a₀₂₂ a₂₂₂ a a' : A} {p₁₀₀ : a₀₀₀ = a₂₀₀} {p₀₁₀ : a₀₀₀ = a₀₂₀} {p₀₀₁ : a₀₀₀ = a₀₀₂} {p₁₂₀ : a₀₂₀ = a₂₂₀} {p₂₁₀ : a₂₀₀ = a₂₂₀} {p₂₀₁ : a₂₀₀ = a₂₀₂} {p₁₀₂ : a₀₀₂ = a₂₀₂} {p₀₁₂ : a₀₀₂ = a₀₂₂} {p₀₂₁ : a₀₂₀ = a₀₂₂} {p₁₂₂ : a₀₂₂ = a₂₂₂} {p₂₁₂ : a₂₀₂ = a₂₂₂} {p₂₂₁ : a₂₂₀ = a₂₂₂} {s₁₁₀ : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} {s₁₁₂ : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂} {s₀₁₁ : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁} {s₂₁₁ : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁} {s₁₀₁ : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁} {s₁₂₁ : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁} {b₁ b₂ b₃ b₄ : B} definition idc [reducible] [constructor] := @cube.idc definition idcube [reducible] [constructor] (a : A) := @cube.idc A a definition rfl1 : cube s₁₁₀ s₁₁₀ vrfl vrfl vrfl vrfl := by induction s₁₁₀; exact idc definition rfl2 : cube vrfl vrfl s₁₁₀ s₁₁₀ hrfl hrfl := by induction s₁₁₀; exact idc definition rfl3 : cube hrfl hrfl hrfl hrfl s₁₀₁ s₁₀₁ := by induction s₁₀₁; exact idc definition eq_of_cube (c : cube s₁₁₀ s₁₁₂ s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁) : transpose s₁₀₁⁻¹ᵛ ⬝h s₁₁₀ ⬝h transpose s₁₂₁ = whisker_square (eq_bot_of_square s₀₁₁) (eq_bot_of_square s₂₁₁) idp idp s₁₁₂ := by induction c; reflexivity --set_option pp.implicit true definition eq_of_vdeg_cube {s s' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (c : cube s s' vrfl vrfl vrfl vrfl) : s = s' := begin induction s, exact eq_of_cube c end definition square_pathover [unfold 7] {f₁ : A → b₁ = b₂} {f₂ : A → b₃ = b₄} {f₃ : A → b₁ = b₃} {f₄ : A → b₂ = b₄} {p : a = a'} {q : square (f₁ a) (f₂ a) (f₃ a) (f₄ a)} {r : square (f₁ a') (f₂ a') (f₃ a') (f₄ a')} (s : cube q r (vdeg_square (ap f₁ p)) (vdeg_square (ap f₂ p)) (vdeg_square (ap f₃ p)) (vdeg_square (ap f₄ p))) : q =[p] r := by induction p;apply pathover_idp_of_eq;exact eq_of_vdeg_cube s end eq
cfb2d9f382695a9bf352ff679851afb0018a02de
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/ShareCommon.lean
7754d07f87cabfb8c6fe38e5f779caffe0ecdb0d
[ "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
4,416
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, Mario Carneiro -/ prelude import Init.Util namespace ShareCommon /- The max sharing primitives are implemented internally. They use maps and sets of Lean objects. We have two versions: one using `HashMap` and `HashSet`, and another using `PersistentHashMap` and `PersistentHashSet`. These maps and sets are "instantiated here using the "unsafe" primitives `Object.eq`, `Object.hash`, and `ptrAddrUnsafe`. -/ abbrev Object : Type := NonScalar unsafe def Object.ptrEq (a b : Object) : Bool := ptrAddrUnsafe a == ptrAddrUnsafe b unsafe abbrev Object.ptrHash (a : Object) : UInt64 := ptrAddrUnsafe a |>.toUInt64 structure StateFactoryImpl where (Map Set : Type) mkState : Unit → Map × Set mapFind? (m : Map) (k : Object) : Option Object mapInsert (m : Map) (k v : Object) : Map setFind? (m : Set) (k : Object) : Option Object setInsert (m : Set) (o : Object) : Set opaque StateFactoryPointed : NonemptyType abbrev StateFactory : Type := StateFactoryPointed.type instance : Nonempty StateFactory := StateFactoryPointed.property @[extern "lean_sharecommon_eq"] unsafe opaque Object.eq (a b : @& Object) : Bool @[extern "lean_sharecommon_hash"] unsafe opaque Object.hash (a : @& Object) : UInt64 structure StateFactoryBuilder where Map (α _β : Type) [BEq α] [Hashable α] : Type mkMap {α β : Type} [BEq α] [Hashable α] (capacity : Nat) : Map α β mapFind? {α β : Type} [BEq α] [Hashable α] : Map α β → α → Option β mapInsert {α β : Type} [BEq α] [Hashable α] : Map α β → α → β → Map α β Set (α : Type) [BEq α] [Hashable α] : Type mkSet {α : Type} [BEq α] [Hashable α] (capacity : Nat) : Set α setFind? {α : Type} [BEq α] [Hashable α] : Set α → α → Option α setInsert {α : Type} [BEq α] [Hashable α] : Set α → α → Set α unsafe def StateFactory.mkImpl : StateFactoryBuilder → StateFactory | { Map, mkMap, mapFind?, mapInsert, Set, mkSet, setFind?, setInsert } => unsafeCast { Map := @Map Object Object ⟨Object.ptrEq⟩ ⟨Object.ptrHash⟩ Set := @Set Object ⟨Object.eq⟩ ⟨Object.hash⟩ mkState := fun _ => ( @mkMap Object Object ⟨Object.ptrEq⟩ ⟨Object.ptrHash⟩ 1024, @mkSet Object ⟨Object.eq⟩ ⟨Object.hash⟩ 1024) mapFind? := @mapFind? Object Object ⟨Object.ptrEq⟩ ⟨Object.ptrHash⟩ mapInsert := @mapInsert Object Object ⟨Object.ptrEq⟩ ⟨Object.ptrHash⟩ setFind? := @setFind? Object ⟨Object.eq⟩ ⟨Object.hash⟩ setInsert := @setInsert Object ⟨Object.eq⟩ ⟨Object.hash⟩ : StateFactoryImpl } @[implemented_by StateFactory.mkImpl] opaque StateFactory.mk : StateFactoryBuilder → StateFactory unsafe def StateFactory.get : StateFactory → StateFactoryImpl := unsafeCast /-- Internally `State` is implemented as a pair `ObjectMap` and `ObjectSet` -/ opaque StatePointed (σ : StateFactory) : NonemptyType abbrev State (σ : StateFactory) : Type u := (StatePointed σ).type instance : Nonempty (State σ) := (StatePointed σ).property unsafe def mkStateImpl (σ : StateFactory) : State σ := unsafeCast (σ.get.mkState ()) @[implemented_by mkStateImpl] opaque State.mk (σ : StateFactory) : State σ instance : Inhabited (State σ) := ⟨.mk σ⟩ @[extern "lean_state_sharecommon"] def State.shareCommon {σ : @& StateFactory} (s : State σ) (a : α) : α × State σ := (a, s) end ShareCommon class MonadShareCommon (m : Type u → Type v) where withShareCommon {α : Type u} : α → m α abbrev withShareCommon := @MonadShareCommon.withShareCommon abbrev shareCommonM [MonadShareCommon m] (a : α) : m α := withShareCommon a abbrev ShareCommonT (σ) (m : Type u → Type v) := StateT (ShareCommon.State σ) m abbrev ShareCommonM (σ) := ShareCommonT σ Id @[specialize] def ShareCommonT.withShareCommon [Monad m] (a : α) : ShareCommonT σ m α := modifyGet fun s => s.shareCommon a instance ShareCommonT.monadShareCommon [Monad m] : MonadShareCommon (ShareCommonT σ m) where withShareCommon := ShareCommonT.withShareCommon @[inline] def ShareCommonT.run [Monad m] (x : ShareCommonT σ m α) : m α := x.run' default @[inline] def ShareCommonM.run (x : ShareCommonM σ α) : α := ShareCommonT.run x
9aca107f4685cc6384186050de0a752e01f732b1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/backward_auto.lean
8b74a8164cab142ec1bbedcd5bc9f566ee2aa61a
[]
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
335
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.set_get_option_tactics namespace Mathlib namespace tactic end Mathlib
8e0cf5f9ef9403c236893f85636657c9aef23b89
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/Elab/SyntheticMVars.lean
9b1367ecc7486ca2da6a7b1486c60eedee3fd1c9
[ "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
15,493
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.ForEachExpr import Lean.Elab.Term import Lean.Elab.Tactic.Basic namespace Lean.Elab.Term open Tactic (TacticM evalTactic getUnsolvedGoals) open Meta def liftTacticElabM {α} (mvarId : MVarId) (x : TacticM α) : TermElabM α := withMVarContext mvarId do let s ← get let savedSyntheticMVars := s.syntheticMVars modify fun s => { s with syntheticMVars := [] } try x.run' { main := mvarId } { goals := [mvarId] } finally modify fun s => { s with syntheticMVars := savedSyntheticMVars } def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do /- Recall, `tacticCode` is the whole `by ...` expression. We store the `by` because in the future we want to save the initial state information at the `by` position. -/ let code := tacticCode[1] modifyThe Meta.State fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId } let remainingGoals ← withInfoHole mvarId do liftTacticElabM mvarId do evalTactic code; getUnsolvedGoals unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (macroStack : MacroStack) (declName? : Option Name) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx $ withMVarContext mvarId do let s ← get try withReader (fun ctx => { ctx with macroStack := macroStack, declName? := declName? }) do let mvarDecl ← getMVarDecl mvarId let expectedType ← instantiateMVars mvarDecl.type withInfoHole mvarId do let result ← resumeElabTerm stx expectedType (!postponeOnError) /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ let result ← withRef stx $ ensureHasType expectedType result assignExprMVar mvarId result pure true catch | ex@(Exception.internal id _) => if id == postponeExceptionId then set s pure false else throw ex | ex@(Exception.error _ _) => if postponeOnError then set s; pure false else logException ex pure true /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool := withMVarContext instMVar do try synthesizeInstMVarCore instMVar catch | ex@(Exception.error _ _) => logException ex; pure true | _ => unreachable! /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. -/ private def synthesizePendingCoeInstMVar (instMVar : MVarId) (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := withMVarContext instMVar do try synthesizeCoeInstMVarCore instMVar catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => unreachable! /-- Try to synthesize the given pending synthetic metavariable. -/ private def synthesizeSyntheticMVar (mvarSyntheticDecl : SyntheticMVarDecl) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => synthesizePendingInstMVar mvarSyntheticDecl.mvarId | SyntheticMVarKind.coe header? expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.mvarId header? expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | SyntheticMVarKind.postponed macroStack declName? => resumePostponed macroStack declName? mvarSyntheticDecl.stx mvarSyntheticDecl.mvarId postponeOnError | SyntheticMVarKind.tactic declName? tacticCode => withReader (fun ctx => { ctx with declName? := declName? }) do if runTactics then runTactic mvarSyntheticDecl.mvarId tacticCode pure true else pure false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let ctx ← read traceAtCmdPos `Elab.resuming fun _ => m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}" let s ← get let syntheticMVars := s.syntheticMVars let numSyntheticMVars := syntheticMVars.length -- We reset `syntheticMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify fun s => { s with syntheticMVars := [] } -- Recall that `syntheticMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. let remainingSyntheticMVars ← syntheticMVars.filterRevM fun mvarDecl => do -- We use `traceM` because we want to make sure the metavar local context is used to trace the message traceM `Elab.postpone (withMVarContext mvarDecl.mvarId do addMessageContext m!"resuming {mkMVar mvarDecl.mvarId}") let succeeded ← synthesizeSyntheticMVar mvarDecl postponeOnError runTactics trace[Elab.postpone]! if succeeded then fmt "succeeded" else fmt "not ready yet" pure !succeeded -- Merge new synthetic metavariables with `remainingSyntheticMVars`, i.e., metavariables that still couldn't be synthesized modify fun s => { s with syntheticMVars := s.syntheticMVars ++ remainingSyntheticMVars } pure $ numSyntheticMVars != remainingSyntheticMVars.length private def tryToSynthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : MetaM (Option (List SyntheticMVarDecl)) := commitWhenSome? do let constInfo ← getConstInfo defaultInstance let candidate := Lean.mkConst defaultInstance (← mkFreshLevelMVars constInfo.lparams.length) let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate) let candidate := mkAppN candidate mvars trace[Elab.resume]! "trying default instance for {mkMVar mvarId} := {candidate}" if (← isDefEqGuarded (mkMVar mvarId) candidate) then -- Succeeded. Collect new TC problems let mut result := [] for i in [:bis.size] do if bis[i] == BinderInfo.instImplicit then result := { mvarId := mvars[i].mvarId!, stx := (← getRef), kind := SyntheticMVarKind.typeClass } :: result trace[Elab.resume]! "worked" return some result else return none private def tryToSynthesizeUsingDefaultInstances (mvarId : MVarId) (prio : Nat) : MetaM (Option (List SyntheticMVarDecl)) := withMVarContext mvarId do let mvarType := (← Meta.getMVarDecl mvarId).type match (← isClass? mvarType) with | none => return none | some className => match (← getDefaultInstances className) with | [] => return none | defaultInstances => for (defaultInstance, instPrio) in defaultInstances do if instPrio == prio then match (← tryToSynthesizeUsingDefaultInstance mvarId defaultInstance) with | some newMVarDecls => return some newMVarDecls | none => continue return none /- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/ private def synthesizeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do let rec visit (syntheticMVars : List SyntheticMVarDecl) (syntheticMVarsNew : List SyntheticMVarDecl) : TermElabM Bool := do match syntheticMVars with | [] => return false | mvarDecl :: mvarDecls => match mvarDecl.kind with | SyntheticMVarKind.typeClass => match (← withRef mvarDecl.stx <| tryToSynthesizeUsingDefaultInstances mvarDecl.mvarId prio) with | none => visit mvarDecls (mvarDecl :: syntheticMVarsNew) | some newMVarDecls => let syntheticMVarsNew := newMVarDecls ++ syntheticMVarsNew let syntheticMVarsNew := mvarDecls.reverse ++ syntheticMVarsNew modify fun s => { s with syntheticMVars := syntheticMVarsNew } return true | _ => visit mvarDecls (mvarDecl :: syntheticMVarsNew) /- Recall that s.syntheticMVars is essentially a stack. The first metavariable was the last one created. We want to apply the default instance in reverse creation order. Otherwise, `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/ visit (← get).syntheticMVars.reverse [] /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` Return true if something was synthesized. -/ private def synthesizeUsingDefault : TermElabM Bool := do let prioSet ← getDefaultInstancesPriorities /- Recall that `prioSet` is stored in descending order -/ for prio in prioSet do if (← synthesizeUsingDefaultPrio prio) then return true return false /-- Report an error for each synthetic metavariable that could not be resolved. -/ private def reportStuckSyntheticMVars : TermElabM Unit := do let s ← get for mvarSyntheticDecl in s.syntheticMVars do withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => withMVarContext mvarSyntheticDecl.mvarId do let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId unless (← get).messages.hasErrors do logError <| "typeclass instance problem contains metavariables" ++ indentExpr mvarDecl.type | SyntheticMVarKind.coe header expectedType eType e f? => withMVarContext mvarSyntheticDecl.mvarId do let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId throwTypeMismatchError header expectedType eType e f? (some ("failed to create type class instance for " ++ indentExpr mvarDecl.type)) | _ => unreachable! -- TODO handle other cases. private def getSomeSynthethicMVarsRef : TermElabM Syntax := do let s ← get match s.syntheticMVars.find? $ fun (mvarDecl : SyntheticMVarDecl) => !mvarDecl.stx.getPos.isNone with | some mvarDecl => pure mvarDecl.stx | none => pure Syntax.missing /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `syntheticMVars` is `[]` after executing this method. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available) metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) : TermElabM Unit := let rec loop (u : Unit) : TermElabM Unit := do let ref ← getSomeSynthethicMVarsRef withRef ref <| withIncRecDepth do let s ← get unless s.syntheticMVars.isEmpty do if ← synthesizeSyntheticMVarsStep false false then loop () else if !mayPostpone then /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?α ?β`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ if ← withoutPostponing (synthesizeSyntheticMVarsStep true false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing (synthesizeSyntheticMVarsStep false false) then loop () else if ← synthesizeSyntheticMVarsStep false true then loop () else reportStuckSyntheticMVars loop () def synthesizeSyntheticMVarsNoPostponing : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) /- Keep invoking `synthesizeUsingDefault` until it returns false. -/ private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do if (← synthesizeUsingDefault) then synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop /-- Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved. If `mayPostpone == false`, then all of them must be synthesized. Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/ partial def withSynthesize {α} (k : TermElabM α) (mayPostpone := false) : TermElabM α := do let s ← get let syntheticMVarsSaved := s.syntheticMVars modify fun s => { s with syntheticMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone then synthesizeUsingDefaultLoop pure a finally modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved } /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := withRef stx do let v ← withSynthesize $ elabTerm stx expectedType? instantiateMVars v end Lean.Elab.Term
81930e491a4750b176ff9a77c80ec0cbedcd9a12
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/topological_groups.lean
f1505ec5f1988c280a9707acd85795ecf765bf53
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
11,622
lean
import tactic.abel import topology.algebra.group --import topology.algebra.uniform_ring import for_mathlib.uniform_space.ring import ring_theory.subring import for_mathlib.topology import for_mathlib.filter universes u v open filter set section variables {G : Type u} [add_comm_group G] def prod_map {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ := λ p, (f p.1, g p.2) infix `⨯`:90 := prod_map def add_group_with_zero_nhd.of_open_add_subgroup (H : set G) [is_add_subgroup H] (t : topological_space H) (h : @topological_add_group H t _) : add_group_with_zero_nhd G := { Z := (nhds (0 : H)).map $ (subtype.val : H → G), zero_Z := calc pure ((0 : H) : G) = map subtype.val (pure 0) : (filter.map_pure _ _).symm ... ≤ _ : map_mono (pure_le_nhds _), sub_Z := begin let δ_G := λ (p : G × G), p.1 - p.2, let δ_H := λ (p : H × H), p.1 - p.2, let ι : H → G := subtype.val, let N := nhds (0 : H), let Z := map subtype.val N, change map δ_G (filter.prod Z Z) ≤ Z, have key₁: map δ_H (nhds (0, 0)) ≤ N, { rw [show N = nhds (δ_H (0, 0)), by simp [*]], exact continuous_sub'.tendsto _ }, have key₂ : δ_G ∘ ι⨯ι = ι ∘ δ_H, { ext p, change (p.1 : G) - (p.2 : G) = (p.1 - p.2 : G), simp [is_add_subgroup.coe_neg, is_add_submonoid.coe_add] }, calc map δ_G (filter.prod Z Z) = map δ_G (map (ι ⨯ ι) $ filter.prod N N) : by rw prod_map_map_eq;refl ... = map ι (map δ_H $ filter.prod N N) : map_comm key₂ _ ... = map ι (map δ_H $ nhds (0, 0)) : by rw ← nhds_prod_eq ... ≤ map ι N : map_mono key₁ end, ..‹add_comm_group G› } def of_open_add_subgroup {G : Type u} [str : add_comm_group G] (H : set G) [is_add_subgroup H] (t : topological_space H) (h : @topological_add_group H t _) : topological_space G := @add_group_with_zero_nhd.topological_space G (add_group_with_zero_nhd.of_open_add_subgroup H t h) end namespace add_group_with_zero_nhd local attribute [instance] add_group_with_zero_nhd.topological_space local notation `Z` := add_group_with_zero_nhd.Z variables {α : Type*} variables {G : Type*} [add_group_with_zero_nhd G] lemma nhds_eq_comap (g : G) : nhds g = comap (λ g', g' + -g) (Z G) := by rw [← nhds_zero_eq_Z, nhds_translation_add_neg g] end add_group_with_zero_nhd namespace topological_group variables {G : Type*} {H : Type*} variables [group G] [topological_space G] [topological_group G] variables [group H] [topological_space H] [topological_group H] variables (f : G → H) [is_group_hom f] -- TODO when PR'ing to mathlib, make sure to include _right in the name -- of this and nhds_translation_mul_inv @[to_additive nhds_translation_add] lemma nhds_translation_mul (g : G) : map (λ h, h*g) (nhds 1) = nhds g := begin rw ← nhds_translation_mul_inv g, apply map_eq_comap_of_inverse ; ext ; simp end @[to_additive nhds_translation_add_neg_left] lemma nhds_translation_mul_inv_left (g : G) : comap (λ h, g⁻¹*h) (nhds 1) = nhds g := begin refine comap_eq_of_inverse (λ h, g*h) _ _ _, { funext x; simp }, { suffices : tendsto (λ h,g⁻¹*h) (nhds g) (nhds (g⁻¹ * g)), { simpa }, exact tendsto_mul tendsto_const_nhds tendsto_id }, { suffices : tendsto (λ h, g*h) (nhds 1) (nhds (g*1)), { simpa }, exact tendsto_mul tendsto_const_nhds tendsto_id } end @[to_additive nhds_translation_add_left] lemma nhds_translation_mul_left (g : G) : map (λ h, g*h) (nhds 1) = nhds g := begin rw ← nhds_translation_mul_inv_left g, apply map_eq_comap_of_inverse ; ext ; simp end @[to_additive topological_add_group.continuous_of_continuous_at_zero] lemma continuous_of_continuous_at_one (h : continuous_at f 1) : continuous f := begin replace h : map f (nhds 1) ≤ nhds 1, by rw ← is_group_hom.one f ; exact h, rw continuous_iff_continuous_at, intro g, have key : (f ∘ λ (h : G), g * h) = (λ (h : H), (f g) * h) ∘ f, by ext ; simp [is_group_hom.mul f], change map f (nhds g) ≤ nhds (f g), rw [← nhds_translation_mul_left g, ← nhds_translation_mul_left (f g), filter.map_comm key], exact map_mono h end @[to_additive topological_add_group.tendsto_nhds_iff'] lemma tendsto_nhds_iff {α : Type*} (f : α → H) (F : filter α) (h : H) : tendsto f F (nhds h) ↔ ∀ V ∈ nhds (1 : H), {a | f a * h⁻¹ ∈ V} ∈ F := let R := λ h', h' * h⁻¹, N := nhds (1 : H) in calc tendsto f F (nhds h) ↔ map f F ≤ (nhds h) : iff.rfl ... ↔ map f F ≤ comap R N : by rw nhds_translation_mul_inv ... ↔ map R (map f F) ≤ N : map_le_iff_le_comap.symm ... ↔ map (λ a, f a * h⁻¹) F ≤ N : by rw filter.map_map @[to_additive topological_add_group.tendsto_nhds_nhds_iff'] lemma tendsto_nhds_nhds_iff (f : G → H) (g : G) (h : H) : tendsto f (nhds g) (nhds h) ↔ ∀ V ∈ nhds (1 : H), ∃ U ∈ nhds (1 : G), ∀ g', g'*g⁻¹ ∈ U → f g' * h⁻¹ ∈ V := by rw [tendsto_nhds_iff f, ← nhds_translation_mul_inv g] ; exact iff.rfl end topological_group namespace topological_add_group -- `to_additive` generates statements using `g + -h` instead of `g-h`, let's fix that variables {G : Type*} [add_group G] [topological_space G] [topological_add_group G] variables {H : Type*} [add_group H] [topological_space H] [topological_add_group H] lemma tendsto_nhds_iff {α : Type*} (f : α → H) (F : filter α) (h : H) : tendsto f F (nhds h) ↔ ∀ (V : set H), V ∈ nhds (0 : H) → {a : α | f a - h ∈ V} ∈ F := topological_add_group.tendsto_nhds_iff' _ _ _ lemma tendsto_nhds_nhds_iff (f : G → H) (g : G) (h : H) : tendsto f (nhds g) (nhds h) ↔ ∀ V ∈ nhds (0 : H), ∃ U ∈ nhds (0 : G), ∀ g', g' - g ∈ U → f g' - h ∈ V := topological_add_group.tendsto_nhds_nhds_iff' _ _ _ end topological_add_group section variables (G : Type u) [add_comm_group G] [topological_space G] [topological_add_group G] local attribute [instance] topological_add_group.to_uniform_space -- Wedhorn Definition 5.31 page 38 definition is_complete_hausdorff : Prop := is_complete (univ : set G) ∧ is_hausdorff G end -- I used to think I would need the next section soon, but I no longer do. -- I keep it because we'll want some form of this in mathlib at some point section top_group_equiv variables (G : Type*) [group G] [topological_space G] [topological_group G] variables (H : Type*) [group H] [topological_space H] [topological_group H] structure top_group_equiv extends homeomorph G H := (hom : is_group_hom to_fun) infix ` ≃*ₜ `:50 := top_group_equiv instance top_group_equiv.is_group_hom (h : G ≃*ₜ H) : is_group_hom h.to_homeomorph := h.hom end top_group_equiv namespace top_group_equiv variables (G : Type*) [group G] [topological_space G] [topological_group G] variables (H : Type*) [group H] [topological_space H] [topological_group H] variables (K : Type*) [group K] [topological_space K] [topological_group K] @[refl] def refl : G ≃*ₜ G := { hom := is_group_hom.id, continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, ..equiv.refl _} @[symm] def symm (h : G ≃*ₜ H) : H ≃*ₜ G := { hom := ⟨λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin rw h.hom.mul, unfold equiv.symm, rw [h.right_inv, h.right_inv, h.right_inv], end⟩, continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, ..h.to_equiv.symm} @[trans] def trans (h1 : G ≃*ₜ H) (h2 : H ≃*ₜ K) : (G ≃*ₜ K) := { hom := is_group_hom.comp h1.to_homeomorph.to_equiv.to_fun h2.to_homeomorph.to_equiv.to_fun, continuous_to_fun := continuous.comp h1.continuous_to_fun h2.continuous_to_fun, continuous_inv_fun := continuous.comp h2.continuous_inv_fun h1.continuous_inv_fun, ..equiv.trans h1.to_equiv h2.to_equiv } end top_group_equiv -- Next secton will move to topology/basic.lean section variables {α : Type*} {β : Type*} [topological_space β] /-- If a function is constant on some set of a proper filter then it converges along this filter -/ lemma exists_limit_of_ultimately_const {φ : α → β} {f : filter α} (hf : f ≠ ⊥) {U : set α} (hU : U ∈ f) (h : ∀ x y ∈ U, φ x = φ y) : ∃ b, tendsto φ f (nhds b) := begin have U_ne : U ≠ ∅, { intro U_empty, rw U_empty at hU, exact mt empty_in_sets_eq_bot.1 hf hU }, cases exists_mem_of_ne_empty U_ne with x₀ x₀_in, use φ x₀, have : U ⊆ φ ⁻¹' {φ x₀}, { intros x x_in, simp [h x x₀ x_in x₀_in] }, have : tendsto φ f (pure $ φ x₀), { rw tendsto_pure, exact mem_sets_of_superset hU this}, exact le_trans this (pure_le_nhds _) end end -- The next section will be used to extend a valuation to the completion of a field (for the -- valuation induced topology). The group Γ will be the value group, G = K^* and H = \hat{K}^* -- (units of the completed field). φ will be the valuation restricted to K^* section open is_group_hom variables {G : Type*} [group G] [topological_space G] [topological_group G] variables {H : Type*} [group H] [topological_space H] [topological_group H] variables {Γ : Type*} [group Γ] [topological_space Γ] [topological_group Γ] [regular_space Γ] variables {ι : G → H} [is_group_hom ι] (de : dense_embedding ι) variables {φ : G → Γ} [is_group_hom φ] -- misc missing lemma, nothing to do with extensions of stuff lemma mul_right_nhds_one {U : set G} (U_in : U ∈ nhds (1 : G)) (g : G) : (λ x, x*g) '' U ∈ nhds g := begin have l : function.left_inverse (λ (x : G), x * g⁻¹) (λ (x : G), x * g), from λ x, by simp, have r : function.right_inverse (λ (x : G), x * g⁻¹) (λ (x : G), x * g), from λ x, by simp, rw image_eq_preimage_of_inverse l r, have : continuous (λ (x : G), x * g⁻¹), from continuous_mul continuous_id continuous_const, apply this.tendsto g, simpa, end -- in Lean the "extension by continuity" of φ always exists, and extends φ. example : ∀ g, (de.extend φ) (ι g) = φ g := de.extend_e_eq -- But, without additional assumption, it gives junk outside the range of ι. -- Here we explain how to make sure it's continuous, under the crucial assumption -- is_open (ker φ) which will be true in our case because Γ is discrete lemma continuous_extend_of_open_kernel (op_ker : is_open (ker φ)) : continuous (de.extend φ) := begin have : ∃ V, V ∈ nhds (1 : H) ∧ ker φ = ι ⁻¹' V, { have : ker φ ∈ nhds (1 : G), from mem_nhds_sets op_ker (is_submonoid.one_mem (ker φ)), rw [← de.induced, mem_comap_sets_of_inj de.inj] at this, rcases this with ⟨V, V_in, hV⟩, rw one ι at V_in, use [V, V_in, hV] }, rcases this with ⟨V, V_in, hV⟩, have : ∃ V' ∈ nhds (1 : H), ∀ x y ∈ V', x*y⁻¹ ∈ V, from exists_nhds_split_inv V_in, rcases this with ⟨V', V'_in, hV'⟩, apply dense_embedding.continuous_extend, intro h, have : ι ⁻¹' ((λ x, x*h) '' V') ∈ comap ι (nhds h), { rw mem_comap_sets_of_inj de.inj, exact ⟨(λ (x : H), x * h) '' V', mul_right_nhds_one V'_in h, rfl⟩ }, apply exists_limit_of_ultimately_const de.comap_nhds_neq_bot this, clear this, intros x y x_in y_in, rw mem_preimage_eq at x_in y_in, rcases x_in with ⟨vₓ, vₓ_in, hx⟩, rcases y_in with ⟨vy, vy_in, hy⟩, change vₓ * h = ι x at hx, change vy * h = ι y at hy, rw [inv_iff_ker φ, hV, mem_preimage_eq, mul ι, inv ι, ← hx, ← hy], simp [mul_assoc], simp [hV', *], end end
aaa582a0ff0d440540b0d91861c258d75aa343a7
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/616a.hlean
0f6869261b740dc6913c7c23e3743d8c15bd3850
[ "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
34
hlean
attribute quotient.rec [recursor]
509235bd5c844261636c70fd740530e0cea5ebc0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/complex/basic.lean
315c45b7e0a8812c8a9db317680fea468eb91918
[ "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
25,902
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.sqrt /-! # The complex numbers The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. The result that the complex numbers are algebraically closed, see `field_theory.algebraic_closure`. -/ open_locale big_operators /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex open_locale complex_conjugate noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem equiv_real_prod_apply (z : ℂ) : equiv_real_prod z = (z.re, z.im) := rfl theorem equiv_real_prod_symm_re (x y : ℝ) : (equiv_real_prod.symm (x, y)).re = x := rfl theorem equiv_real_prod_symm_im (x y : ℝ) : (equiv_real_prod.symm (x, y)).im = y := rfl @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : can_lift ℂ ℝ := { cond := λ z, z.im = 0, coe := coe, prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ } instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩ instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (of_real_mul_re _ _) (of_real_mul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity defined in `data.complex.module.lean`. -/ instance : comm_ring ℂ := by refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, sub := has_sub.sub, one := 1, mul := (*), zero_add := λ z, by { apply ext_iff.2, simp }, add_zero := λ z, by { apply ext_iff.2, simp }, nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩, npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩, zsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} /-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field` instance. -/ instance : ring ℂ := by apply_instance /-- The "real part" map, considered as an additive group homomorphism. -/ def re_add_group_hom : ℂ →+ ℝ := { to_fun := re, map_zero' := zero_re, map_add' := add_re } @[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def im_add_group_hom : ℂ →+ ℝ := { to_fun := im, map_zero' := zero_im, map_add' := add_im } @[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl @[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n := by rw [pow_bit0', I_mul_I] @[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [pow_bit1', I_mul_I] /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It is recommended to use the ring automorphism version `star_ring_aut`, available under the notation `conj` in the locale `complex_conjugate`. -/ instance : star_ring ℂ := { star := λ z, ⟨z.re, -z.im⟩, star_involutive := λ x, by simp only [eta, neg_neg], star_mul := λ a b, by ext; simp [add_comm]; ring, star_add := λ a b, by ext; simp [add_comm] } @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ lemma eq_conj_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 := ⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ @[simp] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq : monoid_with_zero_hom ℂ ℝ := { to_fun := λ z, z.re * z.re + z.im * z.im, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { dsimp, ring } } lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_mk (x y : ℝ) : norm_sq ⟨x, y⟩ = x * x + y * y := rfl lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z := by { ext; simp [norm_sq, mul_comm], } @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero @[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := (norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero) @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by { rw [sub_eq_add_neg, norm_sq_add], simp only [ring_equiv.map_neg, mul_neg_eq_neg_mul_symm, neg_re, tactic.ring.add_neg_eq_sub, norm_sq_neg] } /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ by simp protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } @[simp] lemma I_zpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n := by rw [zpow_bit0', I_mul_I] @[simp] lemma I_zpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [zpow_bit1', I_mul_I] lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := of_real.map_div r s @[simp, norm_cast] lemma of_real_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := of_real.map_zpow r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := norm_sq.map_inv z @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := norm_sq.map_div z w /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := of_real.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := of_real.map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0, mul_div_cancel_left (z.re:ℂ) two_ne_zero'] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) := by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm, mul_div_cancel_left _ (mul_ne_zero two_ne_zero' I_ne_zero : 2 * I ≠ 0)] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := has_abs.abs @[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : ℂ} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : 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 : ℂ) : |z.re| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 /-- The **triangle inequality** for complex numbers. -/ lemma abs_add (z w : ℂ) : 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 abs := { 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 : ℂ) : |(abs z)| = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub_comm : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, |abs z - abs w| ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] @[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n := by rw [← of_real_int_cast, abs_of_real, int.cast_abs] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)] /-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative. Complex numbers with different imaginary parts are incomparable. -/ protected def partial_order : partial_order ℂ := { le := λ z w, z.re ≤ w.re ∧ z.im = w.im, lt := λ z w, z.re < w.re ∧ z.im = w.im, lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto }, le_refl := λ x, ⟨le_rfl, rfl⟩, le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩, le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 } section complex_order localized "attribute [instance] complex.partial_order" in complex_order lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl @[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def] @[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def] @[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real @[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im := by rw [le_def, not_and_distrib, not_le] lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is an ordered ring. -/ protected def ordered_comm_ring : ordered_comm_ring ℂ := { zero_le_one := ⟨zero_le_one, rfl⟩, add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩, mul_pos := λ z w hz hw, by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1], .. complex.partial_order, .. complex.comm_ring } localized "attribute [instance] complex.ordered_comm_ring" in complex_order /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring. (That is, an ordered ring in which every element of the form `star z * z` is nonnegative.) In fact, the nonnegative elements are precisely those of this form. This hold in any `C^*`-algebra, e.g. `ℂ`, but we don't yet have `C^*`-algebras in mathlib. -/ protected def star_ordered_ring : star_ordered_ring ℂ := { star_mul_self_nonneg := λ z, ⟨by simp [add_nonneg, mul_self_nonneg], by simp [mul_comm]⟩ } localized "attribute [instance] complex.star_ordered_ring" in complex_order end complex_order /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε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 ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε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 complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (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)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← ring_equiv.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) @[simp, norm_cast] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ end complex
59eeb06b74a29e9583c67434d5d3c3f4fde1ec49
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/big_operators/ring.lean
6fee335bcd610654b6883ac19354535391b4d177
[ "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
11,153
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.basic import data.finset.pi import data.finset.powerset /-! # Results about big operators with values in a (semi)ring We prove results about big operators that involve some interaction between multiplicative and additive structures on the values being combined. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {b : β} {f g : α → β} section comm_monoid variables [comm_monoid β] open_locale classical lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} : ∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) := begin apply finset.induction, { simp }, { assume a s has H, rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] } end end comm_monoid section semiring variables [non_unital_non_assoc_semiring β] lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b := add_monoid_hom.map_sum (add_monoid_hom.mul_right b) _ s lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x := add_monoid_hom.map_sum (add_monoid_hom.mul_left b) _ s lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂) (f₁ : ι₁ → β) (f₂ : ι₂ → β) : (∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁.product s₂, f₁ p.1 * f₂ p.2 := by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum } end semiring section semiring variables [non_assoc_semiring β] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := by simp lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := by simp end semiring lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} : (∑ x in s, f x) / b = ∑ x in s, f x / b := by simp only [div_eq_mul_inv, sum_mul] section comm_semiring variables [comm_semiring β] /-- The product over a sum can be written as a sum over the product of sets, `finset.pi`. `finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/ lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : (∏ a in s, ∑ b in (t a), f a b) = ∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bUnion h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, pi_cons_injective ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr' with ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end open_locale classical /-- The product of `f a + g a` over all of `s` is the sum over the powerset of `s` of the product of `f` over a subset `t` times the product of `g` over the complement of `t` -/ lemma prod_add (f g : α → β) (s : finset α) : ∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) := calc ∏ a in s, (f a + g a) = ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp ... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)), ∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum ... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _), { simp [subset_iff]; tauto }, { intros t ht, erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)], refine congr_arg2 _ (prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩) _ _ _ (λ b hb, ⟨b, by cases b; simpa only [true_and, exists_prop, mem_filter, and_true, mem_attach, eq_self_iff_true, subtype.coe_mk] using hb⟩)) (prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩) _ _ _ (λ b hb, ⟨b, by cases b; begin simp only [true_and, mem_filter, mem_attach, subtype.coe_mk] at hb, simpa only [true_and, exists_prop, and_true, mem_sdiff, eq_self_iff_true, subtype.coe_mk, b_property], end⟩)); intros; simp * at *; simp * at * }, { assume a₁ a₂ h₁ h₂ H, ext x, simp only [function.funext_iff, subset_iff, mem_powerset, eq_iff_iff] at h₁ h₂ H, exact ⟨λ hx, (H x (h₁ hx)).1 hx, λ hx, (H x (h₂ hx)).2 hx⟩ }, { assume f hf, exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h), by simp, by funext; intros; simp *⟩ } end /-- `∏ i, (f i + g i) = (∏ i, f i) + ∑ i, g i * (∏ j < i, f j + g j) * (∏ j > i, f j)`. -/ lemma prod_add_ordered {ι R : Type*} [comm_semiring R] [linear_order ι] (s : finset ι) (f g : ι → R) : (∏ i in s, (f i + g i)) = (∏ i in s, f i) + ∑ i in s, g i * (∏ j in s.filter (< i), (f j + g j)) * ∏ j in s.filter (λ j, i < j), f j := begin refine finset.induction_on_max s (by simp) _, clear s, intros a s ha ihs, have ha' : a ∉ s, from λ ha', (ha a ha').false, rw [prod_insert ha', prod_insert ha', sum_insert ha', filter_insert, if_neg (lt_irrefl a), filter_true_of_mem ha, ihs, add_mul, mul_add, mul_add, add_assoc], congr' 1, rw add_comm, congr' 1, { rw [filter_false_of_mem, prod_empty, mul_one], exact (forall_mem_insert _ _ _).2 ⟨lt_irrefl a, λ i hi, (ha i hi).not_lt⟩ }, { rw mul_sum, refine sum_congr rfl (λ i hi, _), rw [filter_insert, if_neg (ha i hi).not_lt, filter_insert, if_pos (ha i hi), prod_insert, mul_left_comm], exact mt (λ ha, (mem_filter.1 ha).1) ha' } end /-- `∏ i, (f i - g i) = (∏ i, f i) - ∑ i, g i * (∏ j < i, f j - g j) * (∏ j > i, f j)`. -/ lemma prod_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f g : ι → R) : (∏ i in s, (f i - g i)) = (∏ i in s, f i) - ∑ i in s, g i * (∏ j in s.filter (< i), (f j - g j)) * ∏ j in s.filter (λ j, i < j), f j := begin simp only [sub_eq_add_neg], convert prod_add_ordered s f (λ i, -g i), simp, end /-- `∏ i, (1 - f i) = 1 - ∑ i, f i * (∏ j < i, 1 - f j)`. This formula is useful in construction of a partition of unity from a collection of “bump” functions. -/ lemma prod_one_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f : ι → R) : (∏ i in s, (1 - f i)) = 1 - ∑ i in s, f i * ∏ j in s.filter (< i), (1 - f j) := by { rw prod_sub_ordered, simp } /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset` gives `(a + b)^s.card`.-/ lemma sum_pow_mul_eq_add_pow {α R : Type*} [comm_semiring R] (a b : R) (s : finset α) : (∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card := begin rw [← prod_const, prod_add], refine finset.sum_congr rfl (λ t ht, _), rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)] end theorem dvd_sum {b : β} {s : finset α} {f : α → β} (h : ∀ x ∈ s, b ∣ f x) : b ∣ ∑ x in s, f x := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) @[norm_cast] lemma prod_nat_cast (s : finset α) (f : α → ℕ) : ↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) := (nat.cast_ring_hom β).map_prod f s end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] lemma prod_range_cast_nat_sub (n k : ℕ) : ∏ i in range k, (n - i : R) = (∏ i in range k, (n - i) : ℕ) := begin rw prod_nat_cast, cases le_or_lt k n with hkn hnk, { exact prod_congr rfl (λ i hi, (nat.cast_sub $ (mem_range.1 hi).le.trans hkn).symm) }, { rw ← mem_range at hnk, rw [prod_eq_zero hnk, prod_eq_zero hnk]; simp } end end comm_ring /-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets of `s`, and over all subsets of `s` to which one adds `x`. -/ @[to_additive "A sum over all subsets of `s ∪ {x}` is obtained by summing the sum over all subsets of `s`, and over all subsets of `s` to which one adds `x`."] lemma prod_powerset_insert [decidable_eq α] [comm_monoid β] {s : finset α} {x : α} (h : x ∉ s) (f : finset α → β) : (∏ a in (insert x s).powerset, f a) = (∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) := begin rw [powerset_insert, finset.prod_union, finset.prod_image], { assume t₁ h₁ t₂ h₂ heq, rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h), ← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] }, { rw finset.disjoint_iff_ne, assume t₁ h₁ t₂ h₂, rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩, rw ← H₃₂, exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) } end /-- A product over `powerset s` is equal to the double product over sets of subsets of `s` with `card s = k`, for `k = 1, ..., card s`. -/ @[to_additive "A sum over `powerset s` is equal to the double sum over sets of subsets of `s` with `card s = k`, for `k = 1, ..., card s`"] lemma prod_powerset [comm_monoid β] (s : finset α) (f : finset α → β) : ∏ t in powerset s, f t = ∏ j in range (card s + 1), ∏ t in powerset_len j s, f t := begin classical, rw [powerset_card_bUnion, prod_bUnion], intros i hi j hj hij, rw [function.on_fun, powerset_len_eq_filter, powerset_len_eq_filter, disjoint_filter], intros x hx hc hnc, apply hij, rwa ← hc, end lemma sum_range_succ_mul_sum_range_succ [non_unital_non_assoc_semiring β] (n k : ℕ) (f g : ℕ → β) : (∑ i in range (n+1), f i) * (∑ i in range (k+1), g i) = (∑ i in range n, f i) * (∑ i in range k, g i) + f n * (∑ i in range k, g i) + (∑ i in range n, f i) * g k + f n * g k := by simp only [add_mul, mul_add, add_assoc, sum_range_succ] end finset
1799cc250e7241aa1b65e418cfcf475d0ec5b348
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Data/Position.lean
f351dcd5c1f31cd2d387cc00e27aa0c7925465a9
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,233
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.Format namespace Lean structure Position where line : Nat column : Nat deriving Inhabited, DecidableEq namespace Position protected def lt : Position → Position → Bool | ⟨l₁, c₁⟩, ⟨l₂, c₂⟩ => (l₁, c₁) < (l₂, c₂) instance : ToFormat Position := ⟨fun ⟨l, c⟩ => "⟨" ++ fmt l ++ ", " ++ fmt c ++ "⟩"⟩ instance : ToString Position := ⟨fun ⟨l, c⟩ => "⟨" ++ toString l ++ ", " ++ toString c ++ "⟩"⟩ end Position structure FileMap where source : String positions : Array String.Pos lines : Array Nat deriving Inhabited namespace FileMap partial def ofString (s : String) : FileMap := let rec loop (i : String.Pos) (line : Nat) (ps : Array String.Pos) (lines : Array Nat) : FileMap := if s.atEnd i then { source := s, positions := ps.push i, lines := lines.push line } else let c := s.get i; let i := s.next i; if c == '\n' then loop i (line+1) (ps.push i) (lines.push (line+1)) else loop i line ps lines loop 0 1 (#[0]) (#[1]) partial def toPosition (fmap : FileMap) (pos : String.Pos) : Position := match fmap with | { source := str, positions := ps, lines := lines } => if ps.size >= 2 && pos <= ps.back then let rec toColumn (i : String.Pos) (c : Nat) : Nat := if i == pos || str.atEnd i then c else toColumn (str.next i) (c+1) let rec loop (b e : Nat) := let posB := ps[b] if e == b + 1 then { line := lines.get! b, column := toColumn posB 0 } else let m := (b + e) / 2; let posM := ps.get! m; if pos == posM then { line := lines.get! m, column := 0 } else if pos > posM then loop m e else loop b m loop 0 (ps.size -1) else -- Some systems like the delaborator use synthetic positions without an input file, -- which would violate `toPositionAux`'s invariant ⟨1, pos⟩ end FileMap end Lean def String.toFileMap (s : String) : Lean.FileMap := Lean.FileMap.ofString s
c29ff701135000baa4ede83ef84655432297d76a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/kdepends_on.lean
6e77ab20a8378dd245658b44d3e9490c231ed72f
[ "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
301
lean
open tactic example (f : nat → nat) (a : nat) : f (f (a + 0)) = a → true := by do t ← target, s ← to_expr ```(f a), b ← kdepends_on t s, guard ¬b, b ← kdepends_on t s semireducible, guard b, s ← to_expr ```(f (a + 0)), b ← kdepends_on t s, guard b, intros, constructor
8303ed670f7ac588020d0f0accbae8c0b1f4ee76
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/nat/interval.lean
d6ffe65ca9d05dffc6520a698cfaec01e0e32bdf
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,279
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.interval /-! # Finite intervals of naturals This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. ## TODO Add all the `finset.Ico` stuff. -/ open finset nat instance : locally_finite_order ℕ := { finset_Icc := λ a b, (list.range' a (b + 1 - a)).to_finset, finset_Ico := λ a b, (list.range' a (b - a)).to_finset, finset_Ioc := λ a b, (list.range' (a + 1) (b - a)).to_finset, finset_Ioo := λ a b, (list.range' (a + 1) (b - a - 1)).to_finset, finset_mem_Icc := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [nat.add_sub_cancel' (nat.lt_succ_of_le h).le, nat.lt_succ_iff] }, { rw [nat.sub_eq_zero_iff_le.2 h, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end, finset_mem_Ico := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [nat.add_sub_cancel' h] }, { rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2.le)) } end, finset_mem_Ioc := λ a b x, begin rw [list.mem_to_finset, list.mem_range'], cases le_or_lt a b, { rw [←succ_sub_succ, nat.add_sub_cancel' (succ_le_succ h), nat.lt_succ_iff, nat.succ_le_iff] }, { rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.le.trans hx.2)) } end, finset_mem_Ioo := λ a b x, begin rw [list.mem_to_finset, list.mem_range', nat.sub_sub], cases le_or_lt (a + 1) b, { rw [nat.add_sub_cancel' h, nat.succ_le_iff] }, { rw [nat.sub_eq_zero_iff_le.2 h.le, add_zero], exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) } end } namespace nat variables (a b c : ℕ) lemma Icc_eq_range' : Icc a b = (list.range' a (b + 1 - a)).to_finset := rfl lemma Ioc_eq_range' : Ioc a b = (list.range' (a + 1) (b - a)).to_finset := rfl lemma Ioo_eq_range' : Ioo a b = (list.range' (a + 1) (b - a - 1)).to_finset := rfl @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [Icc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [Ioc_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [Ioo_eq_range', list.card_to_finset, (list.nodup_range' _ _).erase_dup, list.length_range'] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] -- TODO@Yaël: Generalize all the following lemmas to `succ_order` lemma Icc_succ_left : Icc a.succ b = Ioc a b := by { ext x, rw [mem_Icc, mem_Ioc, succ_le_iff] } end nat
7d34a347776ebd6ed0f82496b633326571e43310
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/field_division.lean
ee0ea3672e9e1fac115ac7d52c10eaa5da0d165c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
21,153
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import algebra.gcd_monoid.basic import data.polynomial.derivative import data.polynomial.ring_division import data.set.pairwise import ring_theory.coprime.lemmas import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section is_domain variables [comm_ring R] [is_domain R] section normalization_monoid variables [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp lemma monic.normalize_eq_self {p : polynomial R} (hp : p.monic) : normalize p = p := by simp only [polynomial.coe_norm_unit, normalize_apply, hp.leading_coeff, norm_unit_one, units.coe_one, polynomial.C.map_one, mul_one] end normalization_monoid lemma prod_multiset_root_eq_finset_root {p : polynomial R} : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in p.roots.to_finset, (X - C a) ^ root_multiplicity a p := by simp only [count_roots, finset.prod_multiset_map_count] lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots, count_roots, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end lemma roots_normalize [normalization_monoid R] {p : polynomial R} : (normalize p).roots = p.roots := by rw [normalize_apply, mul_comm, coe_norm_unit, roots_C_mul _ (norm_unit (leading_coeff p)).ne_zero] end is_domain section division_ring variables [division_ring R] {p q : polynomial R} lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map (C.to_monoid_hom : R →* _) (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] end division_ring section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.is_unit_or_is_unit hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv₀, ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← euclidean_domain.gcd_is_unit_iff, ← euclidean_domain.gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma mem_root_set [field k] [algebra R k] {x : k} (hp : p ≠ 0) : x ∈ p.root_set k ↔ aeval x p = 0 := iff.trans multiset.mem_to_finset (mem_roots_map hp) lemma root_set_C_mul_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := begin ext x, rw [set.mem_singleton_iff, mem_root_set, aeval_mul, aeval_C, aeval_X_pow, mul_eq_zero], { simp_rw [ring_hom.map_eq_zero, pow_eq_zero_iff (nat.pos_of_ne_zero hn), or_iff_right_iff_imp], exact λ ha', (ha ha').elim }, { exact mul_ne_zero (mt C_eq_zero.mp ha) (pow_ne_zero n X_ne_zero) }, end lemma root_set_monomial {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [←C_mul_X_pow_eq_monomial, root_set_C_mul_X_pow hn ha] lemma root_set_X_pow {R S : Type*} [field R] [field S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : polynomial R).root_set S = {0} := by { rw [←one_mul (X ^ n : polynomial R), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_rfl)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : (polynomial R)ˣ) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma leading_coeff_div (hpq : q.degree ≤ p.degree) : (p / q).leading_coeff = p.leading_coeff / q.leading_coeff := begin by_cases hq : q = 0, { simp [hq] }, rw [div_def, leading_coeff_mul, leading_coeff_C, leading_coeff_div_by_monic_of_monic (monic_mul_leading_coeff_inv hq) _, mul_comm, div_eq_mul_inv], rwa [degree_mul_leading_coeff_inv q hq] end lemma div_C_mul : p / (C a * q) = C a⁻¹ * (p / q) := begin by_cases ha : a = 0, { simp [ha] }, simp only [div_def, leading_coeff_mul, mul_inv₀, leading_coeff_C, C.map_mul, mul_assoc], congr' 3, rw [mul_left_comm q, ← mul_assoc, ← C.map_mul, mul_inv_cancel ha, C.map_one, one_mul] end lemma C_mul_dvd (ha : a ≠ 0) : C a * p ∣ q ↔ p ∣ q := ⟨λ h, dvd_trans (dvd_mul_left _ _) h, λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_assoc, mul_left_comm p, ← mul_assoc, ← C.map_mul, _root_.mul_inv_cancel ha, C.map_one, one_mul, hr]⟩⟩ lemma dvd_C_mul (ha : a ≠ 0) : p ∣ polynomial.C a * q ↔ p ∣ q := ⟨λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_left_comm p, ← hr, ← mul_assoc, ← C.map_mul, _root_.inv_mul_cancel ha, C.map_one, one_mul]⟩, λ h, dvd_trans h (dvd_mul_left _ _)⟩ lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := have p.leading_coeff ≠ 0 := mt leading_coeff_eq_zero.mp hp, by simp [comm_group_with_zero.coe_norm_unit _ this] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (euclidean_domain.dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin rw prod_multiset_root_eq_finset_root, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (H.set_pairwise (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end end field end polynomial
638fdb9c2818e29a4fc64904d2a26688ccab3c9f
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/topology/basic.lean
01c8e68f017c4a293acf16fea0505e94a95d362c
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,167
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial noncomputable theory /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open sᶜ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by unfold is_closed; rw compl_empty; exact is_open_univ @[simp] lemma is_closed_univ : is_closed (univ : set α) := by unfold is_closed; rw compl_univ; exact is_open_empty lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂ lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ lemma set.nonempty.closure {s : set α} (h : s.nonempty) : set.nonempty (closure s) := let ⟨x, hx⟩ := h in ⟨x, subset_closure hx⟩ @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin unfold interior closure is_closed, rw [compl_sUnion, compl_image_set_of], simp only [compl_subset_compl] end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁ nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := rfl /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open_inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_sets_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi attribute [irreducible] nhds lemma mem_of_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_nhds h lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := mem_nhds_sets hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨mem_nhds_sets s_op a_in, s_op⟩ }, end /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure_sets.2 $ mem_of_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ne_bot_of_le_ne_bot H $ inf_le_inf_left _ h lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_sets_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed_union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := mem_closure_iff_nhds.trans ⟨λ H i hi, let ⟨x, hx⟩ := (H _ $ h.mem_of_mem hi) in ⟨x, hx.2, hx.1⟩, λ H t' ht', let ⟨i, hi, hit⟩ := h.mem_iff.1 ht', ⟨x, xt, hx⟩ := H i hi in ⟨x, hit hx, xt⟩⟩ /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ 𝓝 a, from mem_nhds_sets h hs, have 𝓝 a ⊓ 𝓟 s = 𝓝 a, by rwa [inf_eq_left, le_principal_iff], have cluster_pt a (𝓟 (s ∩ t)), from calc 𝓝 a ⊓ 𝓟 (s ∩ t) = 𝓝 a ⊓ (𝓟 s ⊓ 𝓟 t) : by rw inf_principal ... = 𝓝 a ⊓ 𝓟 t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_cluster_pts] at ht; assumption, by rwa [closure_eq_cluster_pts] /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, h.subset $ subset_univ _⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ (f i)ᶜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, (f i)ᶜ ∈ (𝓝 a), by simp only [mem_nhds_sets_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets, apply @filter.Inter_mem_sets _ (𝓝 a) _ _ _ h_fin, exact assume i h, this i end ... ≤ 𝓟 (⋃i, f i)ᶜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H) $ hfc.tendsto.inf hf lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, mem_nhds_sets hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := continuous_const.continuous_at lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, continuous_def.1 hf sᶜ hs, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g` are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/ lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)} (hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λa, @ite (p a) (h a) β (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (λa, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | ¬ p a}, from have a ∈ (interior {a | p a})ᶜ, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ (frontier {a | p a})ᶜ, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a ∉ closure {a | ¬ p a}, by show a ∉ closure {a | p a}ᶜ; rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : ¬ p a, have hc : a ∈ closure {a | ¬ p a}, from subset_closure this, have hnc : a ∉ closure {a | p a}, begin have hc : a ∈ closure {a | p a}ᶜ, from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_sets_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ end dense_range end continuous
f27ffa972edf8a6a292e8c7ab9272f9bf19e8273
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/standard/unit.lean
46ecfc63f9c0fa89fbebadde020d122bf6e46dc3
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
545
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic decidable using decidable namespace unit inductive unit : Type := | star : unit notation `⋆`:max := star theorem unit_eq (a b : unit) : a = b := unit_rec (unit_rec (refl ⋆) b) a theorem inhabited_unit [instance] : inhabited unit := inhabited_intro ⋆ using decidable theorem decidable_eq [instance] (a b : unit) : decidable (a = b) := inl (unit_eq a b) end
0f846d41f4609eb581d4c1f547b3f4e297a8018e
88892181780ff536a81e794003fe058062f06758
/src/advent_of_code_2019/day1.lean
066cc36101d4bdcb25c2939f57b32ea53bc5e9ac
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
2,003
lean
import advent_of_code_2019.common import tactic.norm_num import tactic.suggest import tactic.linarith namespace day1 def fuel_required (mass : ℤ) : ℤ := (mass / 3) - 2 example : fuel_required 12 = 2 := by refl example : fuel_required 14 = 2 := by refl --example : fuel_required 1969 = 654 := by norm_num --example : fuel_required 100756 = 335830 := by norm_num def part_one : list ℤ → ℤ := list.sum ∘ list.map fuel_required -- set_option trace.class_instances true def nat_of_int (a : ℤ) : ℕ := begin cases a, exact a, exact 0 end lemma nat_of_int_of_nat {x} : nat_of_int (int.of_nat x) = x := by refl -- lemma le_nat_of_int : a < 0 → lemma coe_nat_of_int {x : ℤ} (h : x ≥ 0) : ↑(nat_of_int x) = x := begin cases x, rw nat_of_int_of_nat, refl, cases h, end lemma additional_fuel_wf (m : ℤ) (h : 0 < m) : nat_of_int (fuel_required m + 2) < nat_of_int (m + 2) := begin dunfold fuel_required, apply int.lt_of_coe_nat_lt_coe_nat, rw coe_nat_of_int, rw coe_nat_of_int, calc m / 3 - 2 + 2 = m / 3 : by simp ... ≤ m : by { apply int.div_le_self, apply int.le_of_lt, assumption } ... < m + 2 : by simp, linarith, have rr : m / 3 - 2 + 2 = m / 3 := by simp, rw rr, norm_num, apply int.div_nonneg, exact le_of_lt h, norm_num, end @[reducible] def additional_fuel : ℤ → ℤ | m := if h : 0 < m then have _ := additional_fuel_wf, m + additional_fuel (fuel_required m) else 0 using_well_founded { dec_tac := `[apply this, assumption], rel_tac := λ _ _, `[exact ⟨_, measure_wf (nat_of_int ∘ (+2))⟩] } example : additional_fuel 14 = 16 := begin unfold1 additional_fuel, rw if_pos, unfold1 fuel_required additional_fuel, rw if_pos, unfold1 fuel_required additional_fuel, rw if_neg, repeat {norm_num}, end #eval additional_fuel 1969 def part_two : list ℤ → ℤ := list.sum ∘ list.map (additional_fuel ∘ fuel_required) end day1 def main : io unit := batch (both day1.part_one day1.part_two ∘ lines.list)
c4a692d946b9254cb2e0ee11a2f39e6e8890e19f
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Util.lean
3584dba2118a9a06bc47bf6aad641e073b9577f6
[ "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
3,125
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.String.Basic import Init.Data.ToString universes u v /- debugging helper functions -/ @[neverExtract, extern "lean_dbg_trace"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () /- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[neverExtract, extern "lean_dbg_trace_if_shared"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a @[extern "lean_dbg_sleep"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α := arbitrary _ @[noinline] private def mkPanicMessage (modName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPos {α : Type u} [Inhabited α] (modName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessage modName line col msg) -- TODO: should be a macro @[neverExtract, noinline, nospecialize] def unreachable! {α : Type u} [Inhabited α] : α := panic! "unreachable" @[extern "lean_ptr_addr"] unsafe def ptrAddrUnsafe {α : Type u} (a : @& α) : USize := 0 @[inline] unsafe def withPtrAddrUnsafe {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k (ptrAddrUnsafe a) @[inline] unsafe def withPtrEqUnsafe {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := if ptrAddrUnsafe a == ptrAddrUnsafe b then true else k () inductive PtrEqResult {α : Type u} (x y : α) : Type | unknown {} : PtrEqResult | yesEqual (h : x = y) : PtrEqResult @[inline] unsafe def withPtrEqResultUnsafe {α : Type u} {β : Type v} [Subsingleton β] (a b : α) (k : PtrEqResult a b → β) : β := if ptrAddrUnsafe a == ptrAddrUnsafe b then k (PtrEqResult.yesEqual lcProof) else k PtrEqResult.unknown @[implementedBy withPtrEqUnsafe] def withPtrEq {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := k () /-- `withPtrEq` for `DecidableEq` -/ @[inline] def withPtrEqDecEq {α : Type u} (a b : α) (k : Unit → Decidable (a = b)) : Decidable (a = b) := let b := withPtrEq a b (fun _ => toBoolUsing (k ())) (toBoolUsingEqTrue (k ())); condEq b (fun h => isTrue (ofBoolUsingEqTrue h)) (fun h => isFalse (ofBoolUsingEqFalse h)) /-- Similar to `withPtrEq`, but executes the continuation `k` with the "result" of the pointer equality test. -/ @[implementedBy withPtrEqResultUnsafe] def withPtrEqResult {α : Type u} {β : Type v} [Subsingleton β] (a b : α) (k : PtrEqResult a b → β) : β := k PtrEqResult.unknown @[implementedBy withPtrAddrUnsafe] def withPtrAddr {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k 0
f26df0b279cbdbc5cb3598d43e63e70c1c6def13
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/finset.lean
9b6e4383b86e4d559019d2dcf0494a7f7ef50617
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
87,057
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /- set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[extensionality] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /- subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /- empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem exists_mem_iff_ne_empty {s : finset α} : (∃ a : α, a ∈ s) ↔ ¬s = ∅ := ⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, exists_mem_of_ne_empty⟩ @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl lemma nonempty_iff_ne_empty (s : finset α) : nonempty (↑s : set α) ↔ s ≠ ∅ := begin rw [set.coe_nonempty_iff_ne_empty, ←coe_empty], apply not_congr, apply function.injective.eq_iff, exact to_set_injective end /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl /- insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /- union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /- inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /- lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /- erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /- sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff end decidable_eq /- attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /- filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) := by {ext, simp [and_assoc], rw [and.left_comm] } theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end end filter /- range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩, ⟨max (a + 1) n, insert_subset.2 ⟨by simpa only [mem_range] using le_max_left (a+1) n, subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /- erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] [decidable_eq β] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /- card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have card s > 0, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end end card section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := by { ext x, simp, exact ⟨λ ⟨xt, y, ys, xf⟩, ⟨y, ys, xt, xf⟩, λ ⟨y, ys, xt, xf⟩, ⟨xt, y, ys, xf⟩⟩ } theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi section powerset def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map [decidable_eq α] {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] end fold section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) lemma sup_lt [is_total α (≤)] {a : α} : (⊥ < a) → (∀b ∈ s, f b < a) → s.sup f < a := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /- max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption lemma exists_min (s : finset β) (f : β → α) (h : nonempty ↥(↑s : set β)) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := begin have : s.image f ≠ ∅, rwa [ne, image_eq_empty, ← ne.def, ← nonempty_iff_ne_empty], cases min_of_ne_empty this with y hy, rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩ end end max_min section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.min $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.max $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S ≠ ∅) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /- Ico (a closed openinterval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty {n : ℕ} : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive {n m l : ℕ} : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = insert n (Ico (n + 1) m) := by rw [← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := eq_of_veq $ multiset.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := eq_of_veq $ multiset.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := eq_of_veq $ multiset.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_ge n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := (multiset.nat.antidiagonal n).to_finset /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n) /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl } end nat end finset
ba03e709ae69b6daf392203c470164113d0c3b2e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/infinite.lean
2851bcffdf423b0899b6da50aa970e3021be4ca8
[ "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,664
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import data.set.finite /-! # Infinitude of intervals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Bounded intervals in dense orders are infinite, as are unbounded intervals in orders that are unbounded on the appropriate side. We also prove that an unbounded preorder is an infinite type. -/ variables {α : Type*} [preorder α] /-- A nonempty preorder with no maximal element is infinite. This is not an instance to avoid a cycle with `infinite α → nontrivial α → nonempty α`. -/ lemma no_max_order.infinite [nonempty α] [no_max_order α] : infinite α := let ⟨f, hf⟩ := nat.exists_strict_mono α in infinite.of_injective f hf.injective /-- A nonempty preorder with no minimal element is infinite. This is not an instance to avoid a cycle with `infinite α → nontrivial α → nonempty α`. -/ lemma no_min_order.infinite [nonempty α] [no_min_order α] : infinite α := @no_max_order.infinite αᵒᵈ _ _ _ namespace set section densely_ordered variables [densely_ordered α] {a b : α} (h : a < b) lemma Ioo.infinite : infinite (Ioo a b) := @no_max_order.infinite _ _ (nonempty_Ioo_subtype h) _ lemma Ioo_infinite : (Ioo a b).infinite := infinite_coe_iff.1 $ Ioo.infinite h lemma Ico_infinite : (Ico a b).infinite := (Ioo_infinite h).mono Ioo_subset_Ico_self lemma Ico.infinite : infinite (Ico a b) := infinite_coe_iff.2 $ Ico_infinite h lemma Ioc_infinite : (Ioc a b).infinite := (Ioo_infinite h).mono Ioo_subset_Ioc_self lemma Ioc.infinite : infinite (Ioc a b) := infinite_coe_iff.2 $ Ioc_infinite h lemma Icc_infinite : (Icc a b).infinite := (Ioo_infinite h).mono Ioo_subset_Icc_self lemma Icc.infinite : infinite (Icc a b) := infinite_coe_iff.2 $ Icc_infinite h end densely_ordered instance [no_min_order α] {a : α} : infinite (Iio a) := no_min_order.infinite lemma Iio_infinite [no_min_order α] (a : α) : (Iio a).infinite := infinite_coe_iff.1 Iio.infinite instance [no_min_order α] {a : α} : infinite (Iic a) := no_min_order.infinite lemma Iic_infinite [no_min_order α] (a : α) : (Iic a).infinite := infinite_coe_iff.1 Iic.infinite instance [no_max_order α] {a : α} : infinite (Ioi a) := no_max_order.infinite lemma Ioi_infinite [no_max_order α] (a : α) : (Ioi a).infinite := infinite_coe_iff.1 Ioi.infinite instance [no_max_order α] {a : α} : infinite (Ici a) := no_max_order.infinite lemma Ici_infinite [no_max_order α] (a : α) : (Ici a).infinite := infinite_coe_iff.1 Ici.infinite end set
3bfd59569976eab1661cea0e2c29f8abc6d41117
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/limits.lean
65b02fb46843c7135fa4f8f3ceeeb4980da394b4
[ "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
64,548
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.adjunction.basic import category_theory.limits.cones import category_theory.reflects_isomorphisms /-! # Limits and colimits We set up the general theory of limits and colimits in a category. In this introduction we only describe the setup for limits; it is repeated, with slightly different names, for colimits. The three main structures involved are * `is_limit c`, for `c : cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). Typically there are two different ways one can use the limits library: 1. working with particular cones, and terms of type `is_limit` 2. working solely with `has_limit`. While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. See https://stacks.math.columbia.edu/tag/002E. -/ @[nolint has_inhabited_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ @[simps] def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ @[simps] def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Any cone morphism between limit cones is an isomorphism. -/ def hom_is_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) (f : s ⟶ t) : is_iso f := { inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism, } /-- Limits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma cone_point_unique_up_to_iso_hom_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).hom ≫ t.π.app j = s.π.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma cone_point_unique_up_to_iso_inv_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).inv ≫ s.π.app j = t.π.app j := (unique_up_to_iso P Q).inv.w _ /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) /-- If the canonical morphism from a cone point to a limiting cone point is an iso, then the first cone was limiting also. -/ def of_point_iso {r t : cone F} (P : is_limit r) [i : is_iso (P.lift t)] : is_limit t := of_iso_limit P begin haveI : is_iso (P.lift_cone_morphism t).hom := i, haveI : is_iso (P.lift_cone_morphism t) := cones.cone_iso_of_hom_iso _, symmetry, apply as_iso (P.lift_cone_morphism t), end variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- Given a right adjoint functor between categories of cones, the image of a limit cone is a limit cone. -/ def of_right_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (h.obj c) := mk_cone_morphism (λ s, (adjunction.of_right_adjoint h).hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_apply _ _ _).2 t.uniq_cone_morphism) /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} : is_limit (h.functor.obj c) ≃ is_limit c := { to_fun := λ P, of_iso_limit (of_right_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_right_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } /-- A cone postcomposed with a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone F) : is_limit ((cones.postcompose α.hom).obj c) ≃ is_limit c := of_cone_equiv (cones.postcompose_equivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone G) : is_limit ((cones.postcompose α.inv).obj c) ≃ is_limit c := postcompose_hom_equiv α.symm c /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : s.X ≅ t.X := { hom := Q.lift ((limits.cones.postcompose w.hom).obj s), inv := P.lift ((limits.cones.postcompose w.inv).obj t), hom_inv_id' := by { apply hom_ext P, tidy, }, inv_hom_id' := by { apply hom_ext Q, tidy, }, } section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cone F} (P : is_limit s) (e : K ≌ J) : is_limit (s.whisker e.functor) := of_right_adjoint (cones.whiskering_equivalence e).functor P /-- We can prove two cone points `(s : cone F).X` and `(t.cone F).X` are isomorphic if * both cones are limit cones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cone_points_iso_of_equivalence {F : J ⥤ C} {s : cone F} {G : K ⥤ C} {t : cone G} (P : is_limit s) (Q : is_limit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := Q.lift ((cones.equivalence_of_reindexing e.symm w').functor.obj s), inv := P.lift ((cones.equivalence_of_reindexing e w).functor.obj t), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cone.whisker_π, limits.cones.postcompose_obj_π, fac, whisker_left_app, assoc, id_comp, inv_fun_id_assoc_hom_app, fac_assoc, nat_trans.comp_app], rw [counit_functor, ←functor.comp_map, w.hom.naturality], simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := { lift := λ s, t.lift ((cones.postcompose (iso_whisker_left K h).inv).obj s) ≫ h.hom.app c.X, fac' := λ s j, begin slice_lhs 2 3 {erw ← h.hom.naturality (c.π.app j)}, slice_lhs 1 2 {erw t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j}, dsimp, slice_lhs 2 3 {rw iso.inv_hom_id_app}, rw category.comp_id, end, uniq' := λ s m J, begin rw ← cancel_mono (h.inv.app c.X), apply t.hom_ext, intro j, dsimp, slice_lhs 2 3 {erw ← h.inv.naturality (c.π.app j)}, slice_lhs 1 2 {erw J j}, conv_rhs {congr, rw [category.assoc, iso.hom_inv_id_app, comp_id]}, apply (t.fac ((cones.postcompose (iso_whisker_left K h).inv).obj s) j).symm end } /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr' with j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. See https://stacks.math.columbia.edu/tag/002F. -/ @[nolint has_inhabited_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp,reassoc] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /- Repackaging the definition in terms of cocone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cocone. -/ @[simps] def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ @[simps] def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Any cocone morphism between colimit cocones is an isomorphism. -/ def hom_is_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (f : s ⟶ t) : is_iso f := { inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism, } /-- Colimits of `F` are unique up to isomorphism. -/ -- We may later want to prove the coherence of these isomorphisms. def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_hom {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : s.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).hom = t.ι.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_inv {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : t.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).inv = s.ι.app j := (unique_up_to_iso P Q).inv.w _ /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) /-- If the canonical morphism to a cocone point from a colimiting cocone point is an iso, then the first cocone was colimiting also. -/ def of_point_iso {r t : cocone F} (P : is_colimit r) [i : is_iso (P.desc t)] : is_colimit t := of_iso_colimit P begin haveI : is_iso (P.desc_cocone_morphism t).hom := i, haveI : is_iso (P.desc_cocone_morphism t) := cocones.cocone_iso_of_hom_iso _, apply as_iso (P.desc_cocone_morphism t), end variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- Given a left adjoint functor between categories of cocones, the image of a colimit cocone is a colimit cocone. -/ def of_left_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (h.obj c) := mk_cocone_morphism (λ s, ((adjunction.of_left_adjoint h).hom_equiv c s).symm (t.desc_cocone_morphism _)) (λ s m, (adjunction.hom_equiv_apply_eq _ _ _).1 t.uniq_cocone_morphism) /-- Given two functors which have equivalent categories of cocones, we can transport a colimiting cocone across the equivalence. -/ def of_cocone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} : is_colimit (h.functor.obj c) ≃ is_colimit c := { to_fun := λ P, of_iso_colimit (of_left_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_left_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cocone_equiv_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit (h.functor.obj c)) (s) : (of_cocone_equiv h P).desc s = (h.unit.app c).hom ≫ (h.inverse.map {hom := P.desc (h.functor.obj s), w' := (by tidy)}).hom ≫ (h.unit_inv.app s).hom := rfl @[simp] lemma of_cocone_equiv_symm_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit c) (s) : ((of_cocone_equiv h).symm P).desc s = (h.functor.map {hom := P.desc (h.inverse.obj s), w' := (by tidy)}).hom ≫ (h.counit.app s).hom := rfl /-- A cocone precomposed with a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone G) : is_colimit ((cocones.precompose α.hom).obj c) ≃ is_colimit c := of_cocone_equiv (cocones.precompose_equivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone F) : is_colimit ((cocones.precompose α.inv).obj c) ≃ is_colimit c := precompose_hom_equiv α.symm c /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cocone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : s.X ≅ t.X := { hom := P.desc ((limits.cocones.precompose w.hom).obj t), inv := Q.desc ((limits.cocones.precompose w.inv).obj s), hom_inv_id' := by { apply hom_ext P, tidy, }, inv_hom_id' := by { apply hom_ext Q, tidy, }, } section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cocone F} (P : is_colimit s) (e : K ≌ J) : is_colimit (s.whisker e.functor) := of_left_adjoint (cocones.whiskering_equivalence e).functor P /-- We can prove two cocone points `(s : cocone F).X` and `(t.cocone F).X` are isomorphic if * both cocones are colimit ccoones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cocone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cocone_points_iso_of_equivalence {F : J ⥤ C} {s : cocone F} {G : K ⥤ C} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := P.desc ((cocones.equivalence_of_reindexing e w).functor.obj t), inv := Q.desc ((cocones.equivalence_of_reindexing e.symm w').functor.obj s), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cocone.whisker_ι, fac, inv_fun_id_assoc_inv_app, whisker_left_app, assoc, comp_id, limits.cocones.precompose_obj_ι, fac_assoc, nat_trans.comp_app], rw [←functor_unit, ←functor.comp_map, ←w.inv.naturality_assoc], dsimp, simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr' with j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_colimit section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits : Prop := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ (limit.cone F) := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := by simp [has_limit.iso_of_nat_iso, is_limit.cone_points_iso_of_nat_iso_hom] /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cone point of any cone over `F` to the cone point of a limit cone over `G`. -/ def is_limit.map {F G : J ⥤ C} (s : cone F) {t : cone G} (P : is_limit t) (α : F ⟶ G) : s.X ⟶ t.X := P.lift ((cones.postcompose α).obj s) @[simp, reassoc] lemma is_limit_map_π {F G : J ⥤ C} (c : cone F) {d : cone G} (hd : is_limit d) (α : F ⟶ G) (j : J) : is_limit.map c hd α ≫ d.π.app j = c.π.app j ≫ α.app j := by apply is_limit.fac /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac variables [has_limits_of_shape J C] section local attribute [simp] lim_map /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma limit.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) := by ext; rw [assoc, limit.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, limit.map_π, assoc, limit.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, limit.map_π, H.map_comp], rw [assoc, limit.map_π, ←assoc, limit.post_π], refl end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits : Prop := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := by simp [has_colimit.iso_of_nat_iso, is_colimit.cocone_points_iso_of_nat_iso_inv] /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cocone point of a colimit cocone over `F` to the cocone point of any cocone over `G`. -/ def is_colimit.map {F G : J ⥤ C} {s : cocone F} (P : is_colimit s) (t : cocone G) (α : F ⟶ G) : s.X ⟶ t.X := P.desc ((cocones.precompose α).obj t) @[simp, reassoc] lemma ι_is_colimit_map {F G : J ⥤ C} {c : cocone F} (hc : is_colimit c) (d : cocone G) (α : F ⟶ G) (j : J) : c.ι.app j ≫ is_colimit.map hc d α = α.app j ≫ d.ι.app j := by apply is_colimit.fac /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit end category_theory.limits
3dffaab4e78c3db8c0a2f721873f65753403d65c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1878.lean
2c981b354da3e0c9e033fa250ce1240b1bb8d723
[ "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
404
lean
import Lean inductive Foo where | a | b | c namespace Foo scoped instance (priority := 10) inst1 : Inhabited Foo := ⟨.a⟩ instance inst2 : Inhabited Foo := ⟨.b⟩ open Lean Meta def test (declName : Name) : CoreM Unit := do IO.println s!"{declName}, priority: {← getInstancePriority? declName}, kind: {← getInstanceAttrKind? declName}" #eval test `Foo.inst1 #eval test `Foo.inst2
1e16ab95a6c1f21c959447a434df7749207b4e06
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/lazy_list/basic.lean
639475b8fd0154d92ba6e679f6bdc59460551d5e
[ "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
7,745
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon Traversable instance for lazy_lists. -/ import control.traversable.equiv import control.traversable.instances import data.lazy_list /-! ## Definitions on lazy lists This file contains various definitions and proofs on lazy lists. TODO: move the `lazy_list.lean` file from core to mathlib. -/ universes u namespace thunk /-- Creates a thunk with a (non-lazy) constant value. -/ def mk {α} (x : α) : thunk α := λ _, x instance {α : Type u} [decidable_eq α] : decidable_eq (thunk α) | a b := have a = b ↔ a () = b (), from ⟨by cc, by intro; ext x; cases x; assumption⟩, by rw this; apply_instance end thunk namespace lazy_list open function /-- Isomorphism between strict and lazy lists. -/ def list_equiv_lazy_list (α : Type*) : list α ≃ lazy_list α := { to_fun := lazy_list.of_list, inv_fun := lazy_list.to_list, right_inv := by { intro, induction x, refl, simp! [*], ext, cases x, refl }, left_inv := by { intro, induction x, refl, simp! [*] } } instance {α : Type u} [decidable_eq α] : decidable_eq (lazy_list α) | nil nil := is_true rfl | (cons x xs) (cons y ys) := if h : x = y then match decidable_eq (xs ()) (ys ()) with | is_false h2 := is_false (by intro; cc) | is_true h2 := have xs = ys, by ext u; cases u; assumption, is_true (by cc) end else is_false (by intro; cc) | nil (cons _ _) := is_false (by cc) | (cons _ _) nil := is_false (by cc) /-- Traversal of lazy lists using an applicative effect. -/ protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (f : α → m β) : lazy_list α → m (lazy_list β) | lazy_list.nil := pure lazy_list.nil | (lazy_list.cons x xs) := lazy_list.cons <$> f x <*> (thunk.mk <$> traverse (xs ())) instance : traversable lazy_list := { map := @lazy_list.traverse id _, traverse := @lazy_list.traverse } instance : is_lawful_traversable lazy_list := begin apply equiv.is_lawful_traversable' list_equiv_lazy_list; intros ; resetI; ext, { induction x, refl, simp! [equiv.map,functor.map] at *, simp [*], refl, }, { induction x, refl, simp! [equiv.map,functor.map_const] at *, simp [*], refl, }, { induction x, { simp! [traversable.traverse,equiv.traverse] with functor_norm, refl }, simp! [equiv.map,functor.map_const,traversable.traverse] at *, rw x_ih, dsimp [list_equiv_lazy_list,equiv.traverse,to_list,traversable.traverse,list.traverse], simp! with functor_norm, refl }, end /-- `init xs`, if `xs` non-empty, drops the last element of the list. Otherwise, return the empty list. -/ def init {α} : lazy_list α → lazy_list α | lazy_list.nil := lazy_list.nil | (lazy_list.cons x xs) := let xs' := xs () in match xs' with | lazy_list.nil := lazy_list.nil | (lazy_list.cons _ _) := lazy_list.cons x (init xs') end /-- Return the first object contained in the list that satisfies predicate `p` -/ def find {α} (p : α → Prop) [decidable_pred p] : lazy_list α → option α | nil := none | (cons h t) := if p h then some h else find (t ()) /-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/ def interleave {α} : lazy_list α → lazy_list α → lazy_list α | lazy_list.nil xs := xs | a@(lazy_list.cons x xs) lazy_list.nil := a | (lazy_list.cons x xs) (lazy_list.cons y ys) := lazy_list.cons x (lazy_list.cons y (interleave (xs ()) (ys ()))) /-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys` and `zs` and the rest alternate. Every other element of the resulting list is taken from `xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/ def interleave_all {α} : list (lazy_list α) → lazy_list α | [] := lazy_list.nil | (x :: xs) := interleave x (interleave_all xs) /-- Monadic bind operation for `lazy_list`. -/ protected def bind {α β} : lazy_list α → (α → lazy_list β) → lazy_list β | lazy_list.nil _ := lazy_list.nil | (lazy_list.cons x xs) f := lazy_list.append (f x) (bind (xs ()) f) /-- Reverse the order of a `lazy_list`. It is done by converting to a `list` first because reversal involves evaluating all the list and if the list is all evaluated, `list` is a better representation for it than a series of thunks. -/ def reverse {α} (xs : lazy_list α) : lazy_list α := of_list xs.to_list.reverse instance : monad lazy_list := { pure := @lazy_list.singleton, bind := @lazy_list.bind } lemma append_nil {α} (xs : lazy_list α) : xs.append lazy_list.nil = xs := begin induction xs, refl, simp [lazy_list.append, xs_ih], ext, congr, end lemma append_assoc {α} (xs ys zs : lazy_list α) : (xs.append ys).append zs = xs.append (ys.append zs) := by induction xs; simp [append, *] lemma append_bind {α β} (xs : lazy_list α) (ys : thunk (lazy_list α)) (f : α → lazy_list β) : (@lazy_list.append _ xs ys).bind f = (xs.bind f).append ((ys ()).bind f) := by induction xs; simp [lazy_list.bind, append, *, append_assoc, append, lazy_list.bind] instance : is_lawful_monad lazy_list := { pure_bind := by { intros, apply append_nil }, bind_assoc := by { intros, dsimp [(>>=)], induction x; simp [lazy_list.bind, append_bind, *], }, id_map := begin intros, simp [(<$>)], induction x; simp [lazy_list.bind, *, singleton, append], ext ⟨ ⟩, refl, end } /-- Try applying function `f` to every element of a `lazy_list` and return the result of the first attempt that succeeds. -/ def mfirst {m} [alternative m] {α β} (f : α → m β) : lazy_list α → m β | nil := failure | (cons x xs) := f x <|> mfirst (xs ()) /-- Membership in lazy lists -/ protected def mem {α} (x : α) : lazy_list α → Prop | lazy_list.nil := false | (lazy_list.cons y ys) := x = y ∨ mem (ys ()) instance {α} : has_mem α (lazy_list α) := ⟨ lazy_list.mem ⟩ instance mem.decidable {α} [decidable_eq α] (x : α) : Π xs : lazy_list α, decidable (x ∈ xs) | lazy_list.nil := decidable.false | (lazy_list.cons y ys) := if h : x = y then decidable.is_true (or.inl h) else decidable_of_decidable_of_iff (mem.decidable (ys ())) (by simp [*, (∈), lazy_list.mem]) @[simp] lemma mem_nil {α} (x : α) : x ∈ @lazy_list.nil α ↔ false := iff.rfl @[simp] lemma mem_cons {α} (x y : α) (ys : thunk (lazy_list α)) : x ∈ @lazy_list.cons α y ys ↔ x = y ∨ x ∈ ys () := iff.rfl theorem forall_mem_cons {α} {p : α → Prop} {a : α} {l : thunk (lazy_list α)} : (∀ x ∈ @lazy_list.cons _ a l, p x) ↔ p a ∧ ∀ x ∈ l (), p x := by simp only [has_mem.mem, lazy_list.mem, or_imp_distrib, forall_and_distrib, forall_eq] /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {α β} {p : α → Prop} (f : Π a, p a → β) : Π l : lazy_list α, (∀ a ∈ l, p a) → lazy_list β | lazy_list.nil H := lazy_list.nil | (lazy_list.cons x xs) H := lazy_list.cons (f x (forall_mem_cons.1 H).1) (pmap (xs ()) (forall_mem_cons.1 H).2) /-- "Attach" the proof that the elements of `l` are in `l` to produce a new `lazy_list` with the same elements but in the type `{x // x ∈ l}`. -/ def attach {α} (l : lazy_list α) : lazy_list {x // x ∈ l} := pmap subtype.mk l (λ a, id) instance {α} [has_repr α] : has_repr (lazy_list α) := ⟨ λ xs, repr xs.to_list ⟩ end lazy_list
f5fee9ea01d69c02d6d4958d60e19eb08f08a653
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/measure_theory/measure/haar_lebesgue.lean
96aa919bff515fcee84289dc5bf55e9f09983195
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,161
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.lebesgue import measure_theory.measure.haar /-! # Relationship between the Haar and Lebesgue measures We prove that the Haar measure and Lebesgue measure are equal on `ℝ`. -/ open topological_space set /-- The interval `[0,1]` as a compact set with non-empty interior. -/ def topological_space.positive_compacts.Icc01 : positive_compacts ℝ := ⟨Icc 0 1, is_compact_Icc, by simp_rw [interior_Icc, nonempty_Ioo, zero_lt_one]⟩ namespace measure_theory open measure topological_space.positive_compacts lemma is_add_left_invariant_real_volume : is_add_left_invariant ⇑(volume : measure ℝ) := by simp [← map_add_left_eq_self, real.map_volume_add_left] /-- The Haar measure equals the Lebesgue measure on `ℝ`. -/ lemma haar_measure_eq_lebesgue_measure : add_haar_measure Icc01 = volume := begin convert (add_haar_measure_unique _ Icc01).symm, { simp [Icc01] }, { apply_instance }, { exact is_add_left_invariant_real_volume } end end measure_theory
9f73eada5366cfcbdfadb411469e7d167163fa64
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/deriv.lean
660c5097655c8d9a10e9041f9598f730065e8ea6
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,756
lean
/- Benchmark for new code generator -/ import Init.System.IO new_frontend inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr open Expr unsafe def pown : Int → Int → Int | a, 0 => 1 | a, 1 => a | a, n => let b := pown a (n / 2); b * b * (if n % 2 = 0 then 1 else a) unsafe def add : Expr → Expr → Expr | Val n, Val m => Val (n + m) | Val 0, f => f | f, Val 0 => f | f, Val n => add (Val n) f | Val n, Add (Val m) f => add (Val (n+m)) f | f, Add (Val n) g => add (Val n) (add f g) | Add f g, h => add f (add g h) | f, g => Add f g unsafe def mul : Expr → Expr → Expr | Val n, Val m => Val (n*m) | Val 0, _ => Val 0 | _, Val 0 => Val 0 | Val 1, f => f | f, Val 1 => f | f, Val n => mul (Val n) f | Val n, Mul (Val m) f => mul (Val (n*m)) f | f, Mul (Val n) g => mul (Val n) (mul f g) | Mul f g, h => mul f (mul g h) | f, g => Mul f g unsafe def pow : Expr → Expr → Expr | Val m, Val n => Val (pown m n) | _, Val 0 => Val 1 | f, Val 1 => f | Val 0, _ => Val 0 | f, g => Pow f g def ln : Expr → Expr | Val 1 => Val 0 | f => Ln f unsafe def d (x : String) : Expr → Expr | Val _ => Val 0 | Var y => if x = y then Val 1 else Val 0 | Add f g => add (d x f) (d x g) | Mul f g => add (mul f (d x g)) (mul g (d x f)) | Pow f g => mul (pow f g) (add (mul (mul g (d x f)) (pow f (Val (0 - 1)))) (mul (ln f) (d x g))) | Ln f => mul (d x f) (pow f (Val (0 - 1))) partial def count : Expr → Nat | Val _ => 1 | Var _ => 1 | Add f g => count f + count g | Mul f g => count f + count g | Pow f g => count f + count g | Ln f => count f partial def Expr.toString : Expr → String | Val n => HasToString.toString n | Var x => x | Add f g => "(" ++ toString f ++ " + " ++ toString g ++ ")" | Mul f g => "(" ++ toString f ++ " * " ++ toString g ++ ")" | Pow f g => "(" ++ toString f ++ " ^ " ++ toString g ++ ")" | Ln f => "ln(" ++ toString f ++ ")" instance : HasToString Expr := ⟨Expr.toString⟩ unsafe def nest (f : Expr → IO Expr) : Nat → Expr → IO Expr | 0, x => pure x | n+1, x => f x >>= nest f n unsafe def deriv (f : Expr) : IO Expr := do let d := d "x" f; IO.print "count: "; IO.println (count f); pure d unsafe def main : IO Unit := do let x := Var "x"; let f := pow x x; nest deriv 9 f; pure ()
ccb22e96521f55d815b20882d4c742b0a0b551c7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/nat/sub.lean
1624b43c52f801645325227d2bfbd688eb82461d
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,615
lean
--- Copyright (c) 2014 Floris van Doorn. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Floris van Doorn -- data.nat.sub -- ============ -- -- Subtraction on the natural numbers, as well as min, max, and distance. import .order import tools.fake_simplifier open eq.ops open fake_simplifier namespace nat -- subtraction -- ----------- theorem sub_zero_right (n : ℕ) : n - 0 = n := rfl theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m) := rfl irreducible sub theorem sub_zero_left (n : ℕ) : 0 - n = 0 := induction_on n !sub_zero_right (take k : nat, assume IH : 0 - k = 0, calc 0 - succ k = pred (0 - k) : !sub_succ_right ... = pred 0 : {IH} ... = 0 : pred.zero) theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m := sub.succ_succ n m theorem sub_self (n : ℕ) : n - n = 0 := induction_on n !sub_zero_right (take k IH, !sub_succ_succ ⬝ IH) theorem sub_add_add_right (n k m : ℕ) : (n + k) - (m + k) = n - m := induction_on k (calc (n + 0) - (m + 0) = n - (m + 0) : {!add.zero_right} ... = n - m : {!add.zero_right}) (take l : nat, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {!add.succ_right} ... = succ (n + l) - succ (m + l) : {!add.succ_right} ... = (n + l) - (m + l) : !sub_succ_succ ... = n - m : IH) theorem sub_add_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := !add.comm ▸ !add.comm ▸ !sub_add_add_right theorem sub_add_left (n m : ℕ) : n + m - m = n := induction_on m (!add.zero_right⁻¹ ▸ !sub_zero_right) (take k : ℕ, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : {!add.succ_right} ... = n + k - k : !sub_succ_succ ... = n : IH) -- TODO: add_sub_inv' theorem sub_add_left2 (n m : ℕ) : n + m - n = m := !add.comm ▸ !sub_add_left theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k) := induction_on k (calc n - m - 0 = n - m : !sub_zero_right ... = n - (m + 0) : {!add.zero_right⁻¹}) (take l : nat, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : !sub_succ_right ... = pred (n - (m + l)) : {IH} ... = n - succ (m + l) : !sub_succ_right⁻¹ ... = n - (m + succ l) : {!add.succ_right⁻¹}) theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : !sub_sub ... = succ n - succ (m + k) : {!add.succ_right} ... = n - (m + k) : !sub_succ_succ ... = n - m - k : !sub_sub⁻¹ theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0 := calc n - (n + m) = n - n - m : !sub_sub⁻¹ ... = 0 - m : {!sub_self} ... = 0 : !sub_zero_left theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : !sub_sub ... = m - (k + n) : {!add.comm} ... = m - k - n : !sub_sub⁻¹ theorem sub_one (n : ℕ) : n - 1 = pred n := calc n - 1 = pred (n - 0) : !sub_succ_right ... = pred n : {!sub_zero_right} theorem succ_sub_one (n : ℕ) : succ n - 1 = n := !sub_succ_succ ⬝ !sub_zero_right -- add_rewrite sub_add_left -- ### interaction with multiplication theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m := induction_on n (calc pred 0 * m = 0 * m : {pred.zero} ... = 0 : !mul.zero_left ... = 0 - m : !sub_zero_left⁻¹ ... = 0 * m - m : {!mul.zero_left⁻¹}) (take k : nat, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : {!pred.succ} ... = k * m + m - m : !sub_add_left⁻¹ ... = succ k * m - m : {!mul.succ_left⁻¹}) theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := calc n * pred m = pred m * n : !mul.comm ... = m * n - n : !mul_pred_left ... = n * m - n : {!mul.comm} theorem mul_sub_distr_right (n m k : ℕ) : (n - m) * k = n * k - m * k := induction_on m (calc (n - 0) * k = n * k : {!sub_zero_right} ... = n * k - 0 : !sub_zero_right⁻¹ ... = n * k - 0 * k : {!mul.zero_left⁻¹}) (take l : nat, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : {!sub_succ_right} ... = (n - l) * k - k : !mul_pred_left ... = n * k - l * k - k : {IH} ... = n * k - (l * k + k) : !sub_sub ... = n * k - (succ l * k) : {!mul.succ_left⁻¹}) theorem mul_sub_distr_left (n m k : ℕ) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : !mul.comm ... = m * n - k * n : !mul_sub_distr_right ... = n * m - k * n : {!mul.comm} ... = n * m - n * k : {!mul.comm} -- ### interaction with inequalities theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) := sub_induction n m (take k, assume H : 0 ≤ k, calc succ k - 0 = succ k : !sub_zero_right ... = succ (k - 0) : {!sub_zero_right⁻¹}) (take k, assume H : succ k ≤ 0, absurd H !not_succ_zero_le) (take k l, assume IH : k ≤ l → succ l - k = succ (l - k), take H : succ k ≤ succ l, calc succ (succ l) - succ k = succ l - k : !sub_succ_succ ... = succ (l - k) : IH (succ_le_cancel H) ... = succ (succ l - succ k) : {!sub_succ_succ⁻¹}) theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0 := obtain (k : ℕ) (Hk : n + k = m), from le_elim H, Hk ▸ !sub_add_right_eq_zero theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m := sub_induction n m (take k, assume H : 0 ≤ k, calc 0 + (k - 0) = k - 0 : !add.zero_left ... = k : !sub_zero_right) (take k, assume H : succ k ≤ 0, absurd H !not_succ_zero_le) (take k l, assume IH : k ≤ l → k + (l - k) = l, take H : succ k ≤ succ l, calc succ k + (succ l - succ k) = succ k + (l - k) : {!sub_succ_succ} ... = succ (k + (l - k)) : !add.succ_left ... = succ l : {IH (succ_le_cancel H)}) theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n := !add.comm ▸ !add_sub_le theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := calc n + (m - n) = n + 0 : {le_imp_sub_eq_zero H} ... = n : !add.zero_right theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m := !add.comm ▸ add_sub_ge theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n) := or.elim !le_total (assume H : n ≤ m, (add_sub_le H)⁻¹ ▸ H) (assume H : m ≤ n, (add_sub_ge H)⁻¹ ▸ !le_refl) theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n) := or.elim !le_total (assume H : n ≤ m, (add_sub_le H)⁻¹ ▸ !le_refl) (assume H : m ≤ n, (add_sub_ge H)⁻¹ ▸ H) theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k) : P (n - m) := or.elim !le_total (assume H3 : n ≤ m, (le_imp_sub_eq_zero H3)⁻¹ ▸ (H1 H3)) (assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3)) theorem le_elim_sub {n m : ℕ} (H : n ≤ m) : ∃k, m - k = n := obtain (k : ℕ) (Hk : n + k = m), from le_elim H, exists_intro k (calc m - k = n + k - k : {Hk⁻¹} ... = n : !sub_add_left) theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := have l1 : k ≤ m → n + m - k = n + (m - k), from sub_induction k m (take m : ℕ, assume H : 0 ≤ m, calc n + m - 0 = n + m : !sub_zero_right ... = n + (m - 0) : {!sub_zero_right⁻¹}) (take k : ℕ, assume H : succ k ≤ 0, absurd H !not_succ_zero_le) (take k m, assume IH : k ≤ m → n + m - k = n + (m - k), take H : succ k ≤ succ m, calc n + succ m - succ k = succ (n + m) - succ k : {!add.succ_right} ... = n + m - k : !sub_succ_succ ... = n + (m - k) : IH (succ_le_cancel H) ... = n + (succ m - succ k) : {!sub_succ_succ⁻¹}), l1 H theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m := sub_split (assume H1 : n ≤ m, assume H2 : 0 = 0, H1) (take k : ℕ, assume H1 : m + k = n, assume H2 : k = 0, have H3 : n = m, from !add.zero_right ▸ H2 ▸ H1⁻¹, H3 ▸ !le_refl) theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0) (H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n) := or.elim !le_total (assume H3 : n ≤ m, le_imp_sub_eq_zero H3⁻¹ ▸ (H2 (m - n) (add_sub_le H3⁻¹))) (assume H3 : m ≤ n, le_imp_sub_eq_zero H3⁻¹ ▸ (H1 (n - m) (add_sub_le H3⁻¹))) theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m := have H2 : k - n + n = m + n, from calc k - n + n = k : add_sub_ge_left (le_intro H) ... = n + m : H⁻¹ ... = m + n : !add.comm, add.cancel_right H2 theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x := sub.lt xpos ypos theorem sub_le_right {n m : ℕ} (H : n ≤ m) (k : nat) : n - k ≤ m - k := obtain (l : ℕ) (Hl : n + l = m), from le_elim H, or.elim !le_total (assume H2 : n ≤ k, (le_imp_sub_eq_zero H2)⁻¹ ▸ !zero_le) (assume H2 : k ≤ n, have H3 : n - k + l = m - k, from calc n - k + l = l + (n - k) : add.comm ... = l + n - k : (add_sub_assoc H2 l)⁻¹ ... = n + l - k : {!add.comm} ... = m - k : {Hl}, le_intro H3) theorem sub_le_left {n m : ℕ} (H : n ≤ m) (k : nat) : k - m ≤ k - n := obtain (l : ℕ) (Hl : n + l = m), from le_elim H, sub_split (assume H2 : k ≤ m, !zero_le) (take m' : ℕ, assume Hm : m + m' = k, have H3 : n ≤ k, from le_trans H (le_intro Hm), have H4 : m' + l + n = k - n + n, from calc m' + l + n = n + (m' + l) : add.comm ... = n + (l + m') : add.comm ... = n + l + m' : add.assoc ... = m + m' : {Hl} ... = k : Hm ... = k - n + n : (add_sub_ge_left H3)⁻¹, le_intro (add.cancel_right H4)) -- theorem sub_lt_cancel_right {n m k : ℕ) (H : n - k < m - k) : n < m -- := -- _ -- theorem sub_lt_cancel_left {n m k : ℕ) (H : n - m < n - k) : k < m -- := -- _ theorem sub_triangle_inequality (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := sub_split (assume H : n ≤ m, !add.zero_left⁻¹ ▸ sub_le_right H k) (take mn : ℕ, assume Hmn : m + mn = n, sub_split (assume H : m ≤ k, have H2 : n - k ≤ n - m, from sub_le_left H n, have H3 : n - k ≤ mn, from sub_intro Hmn ▸ H2, show n - k ≤ mn + 0, from !add.zero_right⁻¹ ▸ H3) (take km : ℕ, assume Hkm : k + km = m, have H : k + (mn + km) = n, from calc k + (mn + km) = k + (km + mn): add.comm ... = k + km + mn : add.assoc ... = m + mn : Hkm ... = n : Hmn, have H2 : n - k = mn + km, from sub_intro H, H2 ▸ !le_refl)) -- add_rewrite sub_self mul_sub_distr_left mul_sub_distr_right -- absolute difference -- -------------------------------------------- -- ### absolute difference -- This section is still incomplete definition dist (n m : ℕ) := (n - m) + (m - n) theorem dist_comm (n m : ℕ) : dist n m = dist m n := !add.comm theorem dist_self (n : ℕ) : dist n n = 0 := calc (n - n) + (n - n) = 0 + (n - n) : sub_self ... = 0 + 0 : sub_self ... = 0 : rfl theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m := have H2 : n - m = 0, from add.eq_zero_left H, have H3 : n ≤ m, from sub_eq_zero_imp_le H2, have H4 : m - n = 0, from add.eq_zero_right H, have H5 : m ≤ n, from sub_eq_zero_imp_le H4, le_antisym H3 H5 theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n := calc dist n m = 0 + (m - n) : {le_imp_sub_eq_zero H} ... = m - n : !add.zero_left theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m := !dist_comm ▸ dist_le H theorem dist_zero_right (n : ℕ) : dist n 0 = n := dist_ge !zero_le ⬝ !sub_zero_right theorem dist_zero_left (n : ℕ) : dist 0 n = n := dist_le !zero_le ⬝ !sub_zero_right theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m := calc dist k n = k - n : dist_ge (le_intro H) ... = m : sub_intro H theorem dist_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : {!sub_add_add_right} ... = (n - m) + (m - n) : {!sub_add_add_right} theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := !add.comm ▸ !add.comm ▸ !dist_add_right -- add_rewrite dist_self dist_add_right dist_add_left dist_zero_left dist_zero_right theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n := calc dist n m + m = n - m + m : {dist_ge H} ... = n : add_sub_ge_left H theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : !dist_add_right⁻¹ ... = dist (k + l) (k + m) : {H} ... = dist l m : !dist_add_left theorem dist_sub_move_add {n m : ℕ} (H : n ≥ m) (k : ℕ) : dist (n - m) k = dist n (k + m) := have H2 : n - m + (k + m) = k + n, from calc n - m + (k + m) = n - m + (m + k) : add.comm ... = n - m + m + k : add.assoc ... = n + k : {add_sub_ge_left H} ... = k + n : add.comm, dist_eq_intro H2 theorem dist_sub_move_add' {k m : ℕ} (H : k ≥ m) (n : ℕ) : dist n (k - m) = dist (n + m) k := (dist_sub_move_add H n ▸ !dist_comm) ▸ !dist_comm --triangle inequality formulated with dist theorem triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have H : (n - m) + (m - k) + ((k - m) + (m - n)) = (n - m) + (m - n) + ((m - k) + (k - m)), by simp, H ▸ add_le !sub_triangle_inequality !sub_triangle_inequality theorem dist_add_le_add_dist (n m k l : ℕ) : dist (n + m) (k + l) ≤ dist n k + dist m l := have H : dist (n + m) (k + m) + dist (k + m) (k + l) = dist n k + dist m l, from !dist_add_left ▸ !dist_add_right ▸ rfl, H ▸ !triangle_inequality --interaction with multiplication theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := have H : ∀n m, dist n m = n - m + (m - n), from take n m, rfl, by simp theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := have H : ∀n m, dist n m = n - m + (m - n), from take n m, rfl, by simp -- add_rewrite dist_mul_right dist_mul_left dist_comm --needed to prove of_nat a * of_nat b = of_nat (a * b) in int theorem dist_mul_dist (n m k l : ℕ) : dist n m * dist k l = dist (n * k + m * l) (n * l + m * k) := have aux : ∀k l, k ≥ l → dist n m * dist k l = dist (n * k + m * l) (n * l + m * k), from take k l : ℕ, assume H : k ≥ l, have H2 : m * k ≥ m * l, from mul_le_left H m, have H3 : n * l + m * k ≥ m * l, from le_trans H2 !le_add_left, calc dist n m * dist k l = dist n m * (k - l) : {dist_ge H} ... = dist (n * (k - l)) (m * (k - l)) : !dist_mul_right⁻¹ ... = dist (n * k - n * l) (m * k - m * l) : by simp ... = dist (n * k) (m * k - m * l + n * l) : dist_sub_move_add (mul_le_left H n) _ ... = dist (n * k) (n * l + (m * k - m * l)) : {!add.comm} ... = dist (n * k) (n * l + m * k - m * l) : {(add_sub_assoc H2 (n * l))⁻¹} ... = dist (n * k + m * l) (n * l + m * k) : dist_sub_move_add' H3 _, or.elim !le_total (assume H : k ≤ l, !dist_comm ▸ !dist_comm ▸ aux l k H) (assume H : l ≤ k, aux k l H) end nat
849409f88c12ac3af974f7d36d6f8fc411dd1fe0
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/phashmap_inst_coherence.lean
5d04564780b815f4a417d5dea3886a8c8d76d95b
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
368
lean
import Std.Data.PersistentHashMap open Std def m : PersistentHashMap Nat Nat := let m : PersistentHashMap Nat Nat := {}; m.insert 1 1 def natDiffHash : Hashable Nat := ⟨fun n => USize.ofNat $ n+10⟩ -- The following example should fail since the `Hashable` instance used to create `m` is not `natDiffHash` #eval @PersistentHashMap.find? Nat Nat _ natDiffHash m 1
70e68cdf82faec4bb7b24060e5fec71f2c8d1974
947b78d97130d56365ae2ec264df196ce769371a
/tests/compiler/expr.lean
bc0c7f18d5760e9ed52a5134eb7e75a98252efb3
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
194
lean
import Lean open Lean def main : IO UInt32 := do let e := mkAppN (mkConst `f) #[mkConst `a, mkConst `b]; IO.println e; IO.println ("hash: " ++ toString e.hash); IO.println e.getAppArgs; pure 0
41c25777bd111740f1d96d1b36a2b973cc2bcb75
d1bbf1801b3dcb214451d48214589f511061da63
/src/analysis/normed_space/inner_product.lean
dc2d00d3473a0392630e250c405e05a834ef42d4
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
100,615
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis, Heather Macbeth -/ import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form import topology.metric_space.pi_Lp import data.complex.is_R_or_C /-! # Inner Product Space This file defines inner product spaces and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i` - We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that this an inner product space. - Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## TODO - Fix the section on the existence of minimizers and orthogonal projections to make sure that it also applies in the complex case. ## Tags inner product space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topological_space variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [semimodule 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_im : ∀ x, im (inner x x) = 0) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [semimodule 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := c.nonneg_im _ lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_square (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_square], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_square, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [semimodule 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sqr_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := _root_.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := @is_R_or_C.conj 𝕜 _ local postfix `⋆`:90 := complex.conj export inner_product_space (norm_sq_eq_inner) section basic_properties lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_product_space.nonneg_im _ lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := begin rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], conv_rhs { rw ←inner_conj_sym, conv { congr, skip, rw ←inner_conj_sym } } end lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.map_sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.map_sum_left (sesq_form_of_inner) _ _ _ @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin have H : ⟪x, x⟫ = (re ⟪x, x⟫ : 𝕜) + im ⟪x, x⟫ * I, { rw re_add_im, }, rw [H, is_add_hom.map_add re ((re ⟪x, x⟫) : 𝕜) (((im ⟪x, x⟫) : 𝕜) * I)], rw [mul_re, I_re, mul_zero, I_im, zero_sub, tactic.ring.add_neg_eq_sub], rw [of_real_re, of_real_im, sub_zero, inner_self_nonneg_im], simp only [abs_of_real, add_zero, of_real_zero, zero_mul], exact (_root_.abs_of_nonneg inner_self_nonneg).symm, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_square (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_square (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_square ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_pow_two {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end /-- Expand the square -/ lemma norm_add_pow_two_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_pow_two {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [pow_two, ←inner_self_eq_norm_square]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end /-- Expand the square -/ lemma norm_sub_pow_two_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_sub_pow_two ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_square], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [(inner_self_eq_norm_square _).symm], rw[←add_monoid_hom.map_add, parallelogram_law, two_mul, two_mul], simp only [add_monoid_hom.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by rw norm_add_mul_self; ring /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by rw norm_sub_mul_self; ring /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_square, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_square] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_square] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, exact h }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_square, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_square] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [pow_two, pow_two, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded to a continuous map which is jointly conjugate-linear in the left argument and linear in the right argument, once (TODO) conjugate-linear maps have been defined. -/ def inner_right (v : E) : E →L[𝕜] 𝕜 := linear_map.mk_continuous { to_fun := λ w, ⟪v, w⟫, map_add' := λ x y, inner_add_right, map_smul' := λ c x, inner_smul_right } ∥v∥ (by simpa [is_R_or_C.norm_eq_abs] using abs_inner_le_norm v) @[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl end norm /-! ### Inner product space structure on product spaces -/ /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw [←finset.sum_hom finset.univ conj], apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, apply_instance end, nonneg_im := begin intro x, unfold inner, rw[←finset.sum_hom finset.univ im], apply finset.sum_eq_zero, rintros z -, exact inner_self_nonneg_im, apply_instance end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], nonneg_im := λ x, by rw [mul_im, conj_re, conj_im]; ring, add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, nonneg_im := λ x, rfl, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section deriv /-! ### Derivative of the inner product In this section we prove that the inner product and square of the norm in an inner space are infinitely `ℝ`-smooth. In order to state these results, we need a `normed_space ℝ E` instance. Though we can deduce this structure from `inner_product_space 𝕜 E`, this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and `[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances. -/ variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul, is_R_or_C.norm_eq_abs], exact abs_inner_le_norm x y, }⟩ } /-- Derivative of the inner product. -/ def fderiv_inner_clm (p : E × E) : E × E →L[ℝ] 𝕜 := is_bounded_bilinear_map_inner.deriv p @[simp] lemma fderiv_inner_clm_apply (p x : E × E) : fderiv_inner_clm p x = ⟪p.1, x.2⟫ + ⟪x.1, p.2⟫ := rfl lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.times_cont_diff lemma times_cont_diff_at_inner {p : E × E} {n} : times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p := times_cont_diff_inner.times_cont_diff_at lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) := is_bounded_bilinear_map_inner.differentiable_at variables {G : Type*} [normed_group G] [normed_space ℝ G] {f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ} include 𝕜 lemma times_cont_diff_within_at.inner (hf : times_cont_diff_within_at ℝ n f s x) (hg : times_cont_diff_within_at ℝ n g s x) : times_cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x := times_cont_diff_at_inner.comp_times_cont_diff_within_at x (hf.prod hg) lemma times_cont_diff_at.inner (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x) : times_cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x := hf.inner hg lemma times_cont_diff_on.inner (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) : times_cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) : times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) := times_cont_diff_inner.comp (hf.prod hg) lemma has_fderiv_within_at.inner (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') s x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.inner (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') x := (is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp x (hf.prod hg) lemma has_deriv_within_at.inner {f g : ℝ → E} {f' g' : E} {s : set ℝ} {x : ℝ} (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) s x := by simpa using (hf.has_fderiv_within_at.inner hg.has_fderiv_within_at).has_deriv_within_at lemma has_deriv_at.inner {f g : ℝ → E} {f' g' : E} {x : ℝ} : has_deriv_at f f' x → has_deriv_at g g' x → has_deriv_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) x := by simpa only [← has_deriv_within_at_univ] using has_deriv_within_at.inner lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) : differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x := ((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg).has_fderiv_within_at).differentiable_within_at lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : differentiable_at ℝ (λ x, ⟪f x, g x⟫) x := (differentiable_inner _).comp x (hf.prod hg) lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) : differentiable_on ℝ (λ x, ⟪f x, g x⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) : differentiable ℝ (λ x, ⟪f x, g x⟫) := λ x, (hf x).inner (hg x) lemma fderiv_inner_apply (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (y : G) : fderiv ℝ (λ t, ⟪f t, g t⟫) x y = ⟪f x, fderiv ℝ g x y⟫ + ⟪fderiv ℝ f x y, g x⟫ := by { rw [(hf.has_fderiv_at.inner hg.has_fderiv_at).fderiv], refl } lemma deriv_inner_apply {f g : ℝ → E} {x : ℝ} (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) : deriv (λ t, ⟪f t, g t⟫) x = ⟪f x, deriv g x⟫ + ⟪deriv f x, g x⟫ := (hf.has_deriv_at.inner hg.has_deriv_at).deriv lemma times_cont_diff_norm_square : times_cont_diff ℝ n (λ x : E, ∥x∥ ^ 2) := begin simp only [pow_two, ← inner_self_eq_norm_square], exact (re_clm : 𝕜 →L[ℝ] ℝ).times_cont_diff.comp (times_cont_diff_id.inner times_cont_diff_id) end lemma times_cont_diff.norm_square (hf : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, ∥f x∥ ^ 2) := times_cont_diff_norm_square.comp hf lemma times_cont_diff_within_at.norm_square (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ y, ∥f y∥ ^ 2) s x := times_cont_diff_norm_square.times_cont_diff_at.comp_times_cont_diff_within_at x hf lemma times_cont_diff_at.norm_square (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ y, ∥f y∥ ^ 2) x := hf.norm_square lemma times_cont_diff_on.norm_square (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ y, ∥f y∥ ^ 2) s := (λ x hx, (hf x hx).norm_square) lemma differentiable_at.norm_square (hf : differentiable_at ℝ f x) : differentiable_at ℝ (λ y, ∥f y∥ ^ 2) x := (times_cont_diff_norm_square.differentiable le_rfl).differentiable_at.comp x hf lemma differentiable.norm_square (hf : differentiable ℝ f) : differentiable ℝ (λ y, ∥f y∥ ^ 2) := λ x, (hf x).norm_square lemma differentiable_within_at.norm_square (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ y, ∥f y∥ ^ 2) s x := (times_cont_diff_norm_square.differentiable le_rfl).differentiable_at.comp_differentiable_within_at x hf lemma differentiable_on.norm_square (hf : differentiable_on ℝ f s) : differentiable_on ℝ (λ y, ∥f y∥ ^ 2) s := λ x hx, (hf x hx).norm_square end deriv section continuous /-! ### Continuity and measurability of the inner product Since the inner product is `ℝ`-smooth, it is continuous. We do not need a `[normed_space ℝ E]` structure to *state* this fact and its corollaries, so we introduce them in the proof instead. -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, exact differentiable_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) lemma measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E] [topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable (λ t, ⟪f t, g t⟫) := continuous.measurable2 continuous_inner hf hg variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section pi_Lp local attribute [reducible] pi_Lp variables {ι : Type*} [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma findim_euclidean_space : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma findim_euclidean_space_fin {n : ℕ} : finite_dimensional.findim 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp end pi_Lp /-! ### Orthogonal projection in inner product spaces -/ section orthogonal open filter /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.semimodule ℝ 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥ + ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_square_eq_norm_square_add_norm_square_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } local attribute [instance] finite_dimensional_bot /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := begin ext u, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { simp }, { intros w hw, simp [(submodule.mem_bot 𝕜).mp hw] } end variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, is_R_or_C.conj_div, mul_comm, hv, inner_product_space.conj_sym, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule submodule.span_zero_singleton], { simp }, { apply_instance } }, have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := begin simp_rw [submodule.disjoint_def, submodule.mem_orthogonal], exact λ x hx ho, inner_self_eq_zero.1 (ho x hx) end /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) (hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩, rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_is_complete (h : is_complete (K : set E)) : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h, simp end /-- If `K` is complete, `K` and `Kᗮ` span the whole space. Version using `complete_space`. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›) variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_sym, exact hw v hv } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_is_complete (h : is_complete (K : set E)) : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩ @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_bot_iff (hK : is_complete (K : set E)) : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, by { rintro rfl, exact submodule.top_orthogonal_eq_bot }⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete hK, rwa [h, sup_comm, bot_sup_eq] at this, end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtype_continuous.comp (orthogonal_projection K) + Kᗮ.subtype_continuous.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : findim 𝕜 K₁ + findim 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = findim 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, findim_bot, submodule.sup_orthogonal_inf_of_is_complete h (submodule.complete_of_finite_dimensional _)] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.findim_add_inf_findim_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : findim 𝕜 K₁ + n = findim 𝕜 K₂) : findim 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (findim 𝕜 K₁), simp [submodule.findim_add_inf_findim_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.findim_add_findim_orthogonal [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} : findim 𝕜 K + findim 𝕜 Kᗮ = findim 𝕜 E := begin convert submodule.findim_add_inf_findim_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.findim_add_findim_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : findim 𝕜 K + n = findim 𝕜 E) : findim 𝕜 Kᗮ = n := by { rw ← add_right_inj (findim 𝕜 K), simp [submodule.findim_add_findim_orthogonal, h_dim] } /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma findim_orthogonal_span_singleton [finite_dimensional 𝕜 E] {v : E} (hv : v ≠ 0) : findim 𝕜 (𝕜 ∙ v)ᗮ = findim 𝕜 E - 1 := begin haveI : nontrivial E := ⟨⟨v, 0, hv⟩⟩, apply submodule.findim_add_findim_orthogonal', simp only [findim_span_singleton hv, findim_euclidean_space, fintype.card_fin], exact nat.add_sub_cancel' (nat.succ_le_iff.mpr findim_pos) end end orthogonal
7502349b3078867753cf713bd315145be9de4ef7
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/nat/sqrt.lean
ae45a7495c55d2dc1e40cbdb1166d5efa62804f5
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
6,939
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro An efficient binary implementation of a (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.basic namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (@pos_pow_of_pos 2 m dec_trivial), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intros; simp; [exact ⟨h₁, a⟩, exact ⟨a, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intros, { have := sqrt_aux_is_sqrt m r h₁ a, simpa [pow_succ, mul_comm, mul_assoc] }, { rw [pow_succ, mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) a h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ end nat
8d2a2153638cf1e4d2470c778f83e011d9a98d2e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/monad/equiv_mon.lean
e812f78f1eda5d25022c9b919010eced6ade3299
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,583
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.monad.bundled import category_theory.monoidal.End import category_theory.monoidal.Mon_ import category_theory.category.Cat /-! # The equivalence between `Monad C` and `Mon_ (C ⥤ C)`. A monad "is just" a monoid in the category of endofunctors. # Definitions/Theorems 1. `to_Mon` associates a monoid object in `C ⥤ C` to any monad on `C`. 2. `Monad_to_Mon` is the functorial version of `to_Mon`. 3. `of_Mon` associates a monad on `C` to any monoid object in `C ⥤ C`. 4. `Monad_Mon_equiv` is the equivalence between `Monad C` and `Mon_ (C ⥤ C)`. -/ namespace category_theory open category universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u} [category.{v} C] namespace Monad local attribute [instance, reducible] endofunctor_monoidal_category /-- To every `Monad C` we associated a monoid object in `C ⥤ C`.-/ @[simps] def to_Mon : Monad C → Mon_ (C ⥤ C) := λ M, { X := M.func, one := η_ _, mul := μ_ _ } variable (C) /-- Passing from `Monad C` to `Mon_ (C ⥤ C)` is functorial. -/ @[simps] def Monad_to_Mon : Monad C ⥤ Mon_ (C ⥤ C) := { obj := to_Mon, map := λ _ _ f, { hom := f.to_nat_trans } } variable {C} /-- To every monoid object in `C ⥤ C` we associate a `Monad C`. -/ @[simps] def of_Mon : Mon_ (C ⥤ C) → Monad C := λ M, { func := M.X, str := { η := M.one, μ := M.mul, assoc' := begin intro X, rw [←nat_trans.hcomp_id_app, ←nat_trans.comp_app], simp, end, left_unit' := begin intro X, rw [←nat_trans.id_hcomp_app, ←nat_trans.comp_app, M.mul_one], refl, end, right_unit' := begin intro X, rw [←nat_trans.hcomp_id_app, ←nat_trans.comp_app, M.one_mul], refl, end } } variable (C) /-- Passing from `Mon_ (C ⥤ C)` to `Monad C` is functorial. -/ @[simps] def Mon_to_Monad : Mon_ (C ⥤ C) ⥤ Monad C := { obj := of_Mon, map := λ _ _ f, { app_η' := begin intro X, erw [←nat_trans.comp_app, f.one_hom], refl, end, app_μ' := begin intro X, erw [←nat_trans.comp_app, f.mul_hom], finish, end, ..f.hom } } namespace Monad_Mon_equiv variable {C} /-- Isomorphism of functors used in `Monad_Mon_equiv` -/ @[simps] def counit_iso : Mon_to_Monad C ⋙ Monad_to_Mon C ≅ 𝟭 _ := { hom := { app := λ _, { hom := 𝟙 _ } }, inv := { app := λ _, { hom := 𝟙 _ } } } /-- Auxilliary definition for `Monad_Mon_equiv` -/ @[simps] def unit_iso_hom : 𝟭 _ ⟶ Monad_to_Mon C ⋙ Mon_to_Monad C := { app := λ _, { app := λ _, 𝟙 _ } } /-- Auxilliary definition for `Monad_Mon_equiv` -/ @[simps] def unit_iso_inv : Monad_to_Mon C ⋙ Mon_to_Monad C ⟶ 𝟭 _ := { app := λ _, { app := λ _, 𝟙 _ } } /-- Isomorphism of functors used in `Monad_Mon_equiv` -/ @[simps] def unit_iso : 𝟭 _ ≅ Monad_to_Mon C ⋙ Mon_to_Monad C := { hom := unit_iso_hom, inv := unit_iso_inv } end Monad_Mon_equiv open Monad_Mon_equiv /-- Oh, monads are just monoids in the category of endofunctors (equivalence of categories). -/ @[simps] def Monad_Mon_equiv : (Monad C) ≌ (Mon_ (C ⥤ C)) := { functor := Monad_to_Mon _, inverse := Mon_to_Monad _, unit_iso := unit_iso, counit_iso := counit_iso } -- Sanity check example (A : Monad C) {X : C} : ((Monad_Mon_equiv C).unit_iso.app A).hom.app X = 𝟙 _ := rfl end Monad end category_theory
34792bdf84a693e4ec94334bc611675833cbe7db
137c667471a40116a7afd7261f030b30180468c2
/src/category_theory/abelian/basic.lean
faa86294b7f38e0420adbd1cdfb1cc73ce275047
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,527
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.constructions.pullbacks import category_theory.limits.shapes.biproducts import category_theory.limits.shapes.images import category_theory.abelian.non_preadditive /-! # Abelian categories This file contains the definition and basic properties of abelian categories. There are many definitions of abelian category. Our definition is as follows: A category is called abelian if it is preadditive, has a finite products, kernels and cokernels, and if every monomorphism and epimorphism is normal. It should be noted that if we also assume coproducts, then preadditivity is actually a consequence of the other properties, as we show in `non_preadditive_abelian.lean`. However, this fact is of little practical relevance, since essentially all interesting abelian categories come with a preadditive structure. In this way, by requiring preadditivity, we allow the user to pass in the preadditive structure the specific category they are working with has natively. ## Main definitions * `abelian` is the type class indicating that a category is abelian. It extends `preadditive`. * `abelian.image f` is `kernel (cokernel.π f)`, and * `abelian.coimage f` is `cokernel (kernel.ι f)`. ## Main results * In an abelian category, mono + epi = iso. * If `f : X ⟶ Y`, then the map `factor_thru_image f : X ⟶ image f` is an epimorphism, and the map `factor_thru_coimage f : coimage f ⟶ Y` is a monomorphism. * Factoring through the image and coimage is a strong epi-mono factorisation. This means that * every abelian category has images. We instantiated this in such a way that `abelian.image f` is definitionally equal to `limits.image f`, and * there is a canonical isomorphism `coimage_iso_image : coimage f ≅ image f` such that `coimage.π f ≫ (coimage_iso_image f).hom ≫ image.ι f = f`. The lemma stating this is called `full_image_factorisation`. * Every epimorphism is a cokernel of its kernel. Every monomorphism is a kernel of its cokernel. * The pullback of an epimorphism is an epimorphism. The pushout of a monomorphism is a monomorphism. (This is not to be confused with the fact that the pullback of a monomorphism is a monomorphism, which is true in any category). ## Implementation notes The typeclass `abelian` does not extend `non_preadditive_abelian`, to avoid having to deal with comparing the two `has_zero_morphisms` instances (one from `preadditive` in `abelian`, and the other a field of `non_preadditive_abelian`). As a consequence, at the beginning of this file we trivially build a `non_preadditive_abelian` instance from an `abelian` instance, and use this to restate a number of theorems, in each case just reusing the proof from `non_preadditive_abelian.lean`. We don't show this yet, but abelian categories are finitely complete and finitely cocomplete. However, the limits we can construct at this level of generality will most likely be less nice than the ones that can be created in specific applications. For this reason, we adopt the following convention: * If the statement of a theorem involves limits, the existence of these limits should be made an explicit typeclass parameter. * If a limit only appears in a proof, but not in the statement of a theorem, the limit should not be a typeclass parameter, but instead be created using `abelian.has_pullbacks` or a similar definition. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] * [P. Aluffi, *Algebra: Chaper 0*][aluffi2016] -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables (C) /-- A (preadditive) category `C` is called abelian if it has all finite products, all kernels and cokernels, and if every monomorphism is the kernel of some morphism and every epimorphism is the cokernel of some morphism. (This definition implies the existence of zero objects: finite products give a terminal object, and in a preadditive category any terminal object is a zero object.) -/ class abelian extends preadditive C := [has_finite_products : has_finite_products C] [has_kernels : has_kernels C] [has_cokernels : has_cokernels C] (normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f) (normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f) attribute [instance, priority 100] abelian.has_finite_products attribute [instance, priority 100] abelian.has_kernels abelian.has_cokernels end category_theory open category_theory namespace category_theory.abelian variables {C : Type u} [category.{v} C] [abelian C] /-- An abelian category has finite biproducts. -/ @[priority 100] instance has_finite_biproducts : has_finite_biproducts C := limits.has_finite_biproducts.of_has_finite_products @[priority 100] instance has_binary_biproducts : has_binary_biproducts C := limits.has_binary_biproducts_of_finite_biproducts _ section to_non_preadditive_abelian /-- Every abelian category is, in particular, `non_preadditive_abelian`. -/ def non_preadditive_abelian : non_preadditive_abelian C := { ..‹abelian C› } end to_non_preadditive_abelian section strong local attribute [instance] abelian.normal_epi /-- In an abelian category, every epimorphism is strong. -/ lemma strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance end strong section mono_epi_iso variables {X Y : C} (f : X ⟶ Y) local attribute [instance] strong_epi_of_epi /-- In an abelian category, a monomorphism which is also an epimorphism is an isomorphism. -/ lemma is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f := is_iso_of_mono_of_strong_epi _ end mono_epi_iso section factor local attribute [instance] non_preadditive_abelian variables {P Q : C} (f : P ⟶ Q) section lemma mono_of_zero_kernel (R : C) (l : is_limit (kernel_fork.of_ι (0 : R ⟶ P) (show 0 ≫ f = 0, by simp))) : mono f := non_preadditive_abelian.mono_of_zero_kernel _ _ l lemma mono_of_kernel_ι_eq_zero (h : kernel.ι f = 0) : mono f := mono_of_kernel_zero h lemma epi_of_zero_cokernel (R : C) (l : is_colimit (cokernel_cofork.of_π (0 : Q ⟶ R) (show f ≫ 0 = 0, by simp))) : epi f := non_preadditive_abelian.epi_of_zero_cokernel _ _ l lemma epi_of_cokernel_π_eq_zero (h : cokernel.π f = 0) : epi f := begin apply epi_of_zero_cokernel _ (cokernel f), simp_rw ←h, exact is_colimit.of_iso_colimit (colimit.is_colimit (parallel_pair f 0)) (iso_of_π _) end end namespace images /-- The kernel of the cokernel of `f` is called the image of `f`. -/ protected abbreviation image : C := kernel (cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected abbreviation image.ι : images.image f ⟶ Q := kernel.ι (cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected abbreviation factor_thru_image : P ⟶ images.image f := kernel.lift (cokernel.π f) f $ cokernel.condition f /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp, reassoc] protected lemma image.fac : images.factor_thru_image f ≫ image.ι f = f := kernel.lift_ι _ _ _ /-- The map `p : P ⟶ image f` is an epimorphism -/ instance : epi (images.factor_thru_image f) := show epi (non_preadditive_abelian.factor_thru_image f), by apply_instance section variables {f} lemma image_ι_comp_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : images.image.ι f ≫ g = 0 := zero_of_epi_comp (images.factor_thru_image f) $ by simp [h] end instance mono_factor_thru_image [mono f] : mono (images.factor_thru_image f) := mono_of_mono_fac $ image.fac f instance is_iso_factor_thru_image [mono f] : is_iso (images.factor_thru_image f) := is_iso_of_mono_of_epi _ /-- Factoring through the image is a strong epi-mono factorisation. -/ @[simps] def image_strong_epi_mono_factorisation : strong_epi_mono_factorisation f := { I := images.image f, m := image.ι f, m_mono := by apply_instance, e := images.factor_thru_image f, e_strong_epi := strong_epi_of_epi _ } end images namespace coimages /-- The cokernel of the kernel of `f` is called the coimage of `f`. -/ protected abbreviation coimage : C := cokernel (kernel.ι f) /-- The projection onto the coimage. -/ protected abbreviation coimage.π : P ⟶ coimages.coimage f := cokernel.π (kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected abbreviation factor_thru_coimage : coimages.coimage f ⟶ Q := cokernel.desc (kernel.ι f) f $ kernel.condition f /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected lemma coimage.fac : coimage.π f ≫ coimages.factor_thru_coimage f = f := cokernel.π_desc _ _ _ /-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/ instance : mono (coimages.factor_thru_coimage f) := show mono (non_preadditive_abelian.factor_thru_coimage f), by apply_instance section variables {f} lemma comp_coimage_π_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : f ≫ coimages.coimage.π g = 0 := zero_of_comp_mono (coimages.factor_thru_coimage g) $ by simp [h] end instance epi_factor_thru_coimage [epi f] : epi (coimages.factor_thru_coimage f) := epi_of_epi_fac $ coimage.fac f instance is_iso_factor_thru_coimage [epi f] : is_iso (coimages.factor_thru_coimage f) := is_iso_of_mono_of_epi _ /-- Factoring through the coimage is a strong epi-mono factorisation. -/ @[simps] def coimage_strong_epi_mono_factorisation : strong_epi_mono_factorisation f := { I := coimages.coimage f, m := coimages.factor_thru_coimage f, m_mono := by apply_instance, e := coimage.π f, e_strong_epi := strong_epi_of_epi _ } end coimages end factor section has_strong_epi_mono_factorisations /-- An abelian category has strong epi-mono factorisations. -/ @[priority 100] instance : has_strong_epi_mono_factorisations C := has_strong_epi_mono_factorisations.mk $ λ X Y f, images.image_strong_epi_mono_factorisation f /- In particular, this means that it has well-behaved images. -/ example : has_images C := by apply_instance example : has_image_maps C := by apply_instance end has_strong_epi_mono_factorisations section images variables {X Y : C} (f : X ⟶ Y) /-- There is a canonical isomorphism between the coimage and the image of a morphism. -/ abbreviation coimage_iso_image : coimages.coimage f ≅ images.image f := is_image.iso_ext (coimages.coimage_strong_epi_mono_factorisation f).to_mono_is_image (images.image_strong_epi_mono_factorisation f).to_mono_is_image /-- There is a canonical isomorphism between the abelian image and the categorical image of a morphism. -/ abbreviation image_iso_image : images.image f ≅ image f := is_image.iso_ext (images.image_strong_epi_mono_factorisation f).to_mono_is_image (image.is_image f) /-- There is a canonical isomorphism between the abelian coimage and the categorical image of a morphism. -/ abbreviation coimage_iso_image' : coimages.coimage f ≅ image f := is_image.iso_ext (coimages.coimage_strong_epi_mono_factorisation f).to_mono_is_image (image.is_image f) lemma full_image_factorisation : coimages.coimage.π f ≫ (coimage_iso_image f).hom ≫ images.image.ι f = f := by rw [limits.is_image.iso_ext_hom, ←images.image_strong_epi_mono_factorisation_to_mono_factorisation_m, is_image.lift_fac, coimages.coimage_strong_epi_mono_factorisation_to_mono_factorisation_m, coimages.coimage.fac] end images section cokernel_of_kernel variables {X Y : C} {f : X ⟶ Y} local attribute [instance] non_preadditive_abelian /-- In an abelian category, an epi is the cokernel of its kernel. More precisely: If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel of `fork.ι s`. -/ def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) : is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) := non_preadditive_abelian.epi_is_cokernel_of_kernel s h /-- In an abelian category, a mono is the kernel of its cokernel. More precisely: If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel of `cofork.π s`. -/ def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) : is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) := non_preadditive_abelian.mono_is_kernel_of_cokernel s h end cokernel_of_kernel section @[priority 100] instance has_equalizers : has_equalizers C := preadditive.has_equalizers_of_has_kernels /-- Any abelian category has pullbacks -/ @[priority 100] instance has_pullbacks : has_pullbacks C := has_pullbacks_of_has_binary_products_of_has_equalizers C end section @[priority 100] instance has_coequalizers : has_coequalizers C := preadditive.has_coequalizers_of_has_cokernels /-- Any abelian category has pushouts -/ @[priority 100] instance has_pushouts : has_pushouts C := has_pushouts_of_has_binary_coproducts_of_has_coequalizers C end namespace pullback_to_biproduct_is_kernel variables [limits.has_pullbacks C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) /-! This section contains a slightly technical result about pullbacks and biproducts. We will need it in the proof that the pullback of an epimorphism is an epimorpism. -/ /-- The canonical map `pullback f g ⟶ X ⊞ Y` -/ abbreviation pullback_to_biproduct : pullback f g ⟶ X ⊞ Y := biprod.lift pullback.fst pullback.snd /-- The canonical map `pullback f g ⟶ X ⊞ Y` induces a kernel cone on the map `biproduct X Y ⟶ Z` induced by `f` and `g`. A slightly more intuitive way to think of this may be that it induces an equalizer fork on the maps induced by `(f, 0)` and `(0, g)`. -/ abbreviation pullback_to_biproduct_fork : kernel_fork (biprod.desc f (-g)) := kernel_fork.of_ι (pullback_to_biproduct f g) $ by rw [biprod.lift_desc, comp_neg, pullback.condition, add_right_neg] /-- The canonical map `pullback f g ⟶ X ⊞ Y` is a kernel of the map induced by `(f, -g)`. -/ def is_limit_pullback_to_biproduct : is_limit (pullback_to_biproduct_fork f g) := fork.is_limit.mk _ (λ s, pullback.lift (fork.ι s ≫ biprod.fst) (fork.ι s ≫ biprod.snd) $ sub_eq_zero.1 $ by rw [category.assoc, category.assoc, ←comp_sub, sub_eq_add_neg, ←comp_neg, ←biprod.desc_eq, kernel_fork.condition s]) (λ s, begin ext; rw [fork.ι_of_ι, category.assoc], { rw [biprod.lift_fst, pullback.lift_fst] }, { rw [biprod.lift_snd, pullback.lift_snd] } end) (λ s m h, by ext; simp [fork.ι_eq_app_zero, ←h walking_parallel_pair.zero]) end pullback_to_biproduct_is_kernel namespace biproduct_to_pushout_is_cokernel variables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) /-- The canonical map `Y ⊞ Z ⟶ pushout f g` -/ abbreviation biproduct_to_pushout : Y ⊞ Z ⟶ pushout f g := biprod.desc pushout.inl pushout.inr /-- The canonical map `Y ⊞ Z ⟶ pushout f g` induces a cokernel cofork on the map `X ⟶ Y ⊞ Z` induced by `f` and `-g`. -/ abbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) := cokernel_cofork.of_π (biproduct_to_pushout f g) $ by rw [biprod.lift_desc, neg_comp, pushout.condition, add_right_neg] /-- The cofork induced by the canonical map `Y ⊞ Z ⟶ pushout f g` is in fact a colimit cokernel cofork. -/ def is_colimit_biproduct_to_pushout : is_colimit (biproduct_to_pushout_cofork f g) := cofork.is_colimit.mk _ (λ s, pushout.desc (biprod.inl ≫ cofork.π s) (biprod.inr ≫ cofork.π s) $ sub_eq_zero.1 $ by rw [←category.assoc, ←category.assoc, ←sub_comp, sub_eq_add_neg, ←neg_comp, ←biprod.lift_eq, cofork.condition s, zero_comp]) (λ s, by ext; simp) (λ s m h, by ext; simp [cofork.π_eq_app_one, ←h walking_parallel_pair.one] ) end biproduct_to_pushout_is_cokernel section epi_pullback variables [limits.has_pullbacks C] {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) /-- In an abelian category, the pullback of an epimorphism is an epimorphism. Proof from [aluffi2016, IX.2.3], cf. [borceux-vol2, 1.7.6] -/ instance epi_pullback_of_epi_f [epi f] : epi (pullback.snd : pullback f g ⟶ Y) := -- It will suffice to consider some morphism e : Y ⟶ R such that -- pullback.snd ≫ e = 0 and show that e = 0. epi_of_cancel_zero _ $ λ R e h, begin -- Consider the morphism u := (0, e) : X ⊞ Y⟶ R. let u := biprod.desc (0 : X ⟶ R) e, -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption. have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa, -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a -- cokernel of pullback_to_biproduct f g have := epi_is_cokernel_of_kernel _ (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g), -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R. obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu, change Z ⟶ R at d, change biprod.desc f (-g) ≫ d = u at hd, -- But then f ≫ d = 0: have : f ≫ d = 0, calc f ≫ d = (biprod.inl ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inl_desc ... = biprod.inl ≫ u : by rw [category.assoc, hd] ... = 0 : biprod.inl_desc _ _, -- But f is an epimorphism, so d = 0... have : d = 0 := (cancel_epi f).1 (by simpa), -- ...or, in other words, e = 0. calc e = biprod.inr ≫ u : by rw biprod.inr_desc ... = biprod.inr ≫ biprod.desc f (-g) ≫ d : by rw ←hd ... = biprod.inr ≫ biprod.desc f (-g) ≫ 0 : by rw this ... = (biprod.inr ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc ... = 0 : has_zero_morphisms.comp_zero _ _ end /-- In an abelian category, the pullback of an epimorphism is an epimorphism. -/ instance epi_pullback_of_epi_g [epi g] : epi (pullback.fst : pullback f g ⟶ X) := -- It will suffice to consider some morphism e : X ⟶ R such that -- pullback.fst ≫ e = 0 and show that e = 0. epi_of_cancel_zero _ $ λ R e h, begin -- Consider the morphism u := (e, 0) : X ⊞ Y ⟶ R. let u := biprod.desc e (0 : Y ⟶ R), -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption. have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa, -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a -- cokernel of pullback_to_biproduct f g have := epi_is_cokernel_of_kernel _ (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g), -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R. obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu, change Z ⟶ R at d, change biprod.desc f (-g) ≫ d = u at hd, -- But then (-g) ≫ d = 0: have : (-g) ≫ d = 0, calc (-g) ≫ d = (biprod.inr ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inr_desc ... = biprod.inr ≫ u : by rw [category.assoc, hd] ... = 0 : biprod.inr_desc _ _, -- But g is an epimorphism, thus so is -g, so d = 0... have : d = 0 := (cancel_epi (-g)).1 (by simpa), -- ...or, in other words, e = 0. calc e = biprod.inl ≫ u : by rw biprod.inl_desc ... = biprod.inl ≫ biprod.desc f (-g) ≫ d : by rw ←hd ... = biprod.inl ≫ biprod.desc f (-g) ≫ 0 : by rw this ... = (biprod.inl ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc ... = 0 : has_zero_morphisms.comp_zero _ _ end lemma epi_snd_of_is_limit [epi f] {s : pullback_cone f g} (hs : is_limit s) : epi s.snd := begin convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _), { refl }, { exact abelian.epi_pullback_of_epi_f _ _ } end lemma epi_fst_of_is_limit [epi g] {s : pullback_cone f g} (hs : is_limit s) : epi s.fst := begin convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _), { refl }, { exact abelian.epi_pullback_of_epi_g _ _ } end /-- Suppose `f` and `g` are two morphisms with a common codomain and suppose we have written `g` as an epimorphism followed by a monomorphism. If `f` factors through the mono part of this factorization, then any pullback of `g` along `f` is an epimorphism. -/ lemma epi_fst_of_factor_thru_epi_mono_factorization (g₁ : Y ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : X ⟶ W) (hf : f' ≫ g₂ = f) (t : pullback_cone f g) (ht : is_limit t) : epi t.fst := by apply epi_fst_of_is_limit _ _ (pullback_cone.is_limit_of_factors f g g₂ f' g₁ hf hg t ht) end epi_pullback section mono_pushout variables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) instance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z ⟶ pushout f g) := mono_of_cancel_zero _ $ λ R e h, begin let u := biprod.lift (0 : R ⟶ Y) e, have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa, have := mono_is_kernel_of_cokernel _ (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g), obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu, change R ⟶ X at d, change d ≫ biprod.lift f (-g) = u at hd, have : d ≫ f = 0, calc d ≫ f = d ≫ biprod.lift f (-g) ≫ biprod.fst : by rw biprod.lift_fst ... = u ≫ biprod.fst : by rw [←category.assoc, hd] ... = 0 : biprod.lift_fst _ _, have : d = 0 := (cancel_mono f).1 (by simpa), calc e = u ≫ biprod.snd : by rw biprod.lift_snd ... = (d ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw ←hd ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw this ... = 0 ≫ biprod.lift f (-g) ≫ biprod.snd : by rw category.assoc ... = 0 : zero_comp end instance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y ⟶ pushout f g) := mono_of_cancel_zero _ $ λ R e h, begin let u := biprod.lift e (0 : R ⟶ Z), have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa, have := mono_is_kernel_of_cokernel _ (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g), obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu, change R ⟶ X at d, change d ≫ biprod.lift f (-g) = u at hd, have : d ≫ (-g) = 0, calc d ≫ (-g) = d ≫ biprod.lift f (-g) ≫ biprod.snd : by rw biprod.lift_snd ... = u ≫ biprod.snd : by rw [←category.assoc, hd] ... = 0 : biprod.lift_snd _ _, have : d = 0 := (cancel_mono (-g)).1 (by simpa), calc e = u ≫ biprod.fst : by rw biprod.lift_fst ... = (d ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw ←hd ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw this ... = 0 ≫ biprod.lift f (-g) ≫ biprod.fst : by rw category.assoc ... = 0 : zero_comp end lemma mono_inr_of_is_colimit [mono f] {s : pushout_cocone f g} (hs : is_colimit s) : mono s.inr := begin convert mono_of_mono_fac (is_colimit.comp_cocone_point_unique_up_to_iso_hom hs (colimit.is_colimit _) _), { refl }, { exact abelian.mono_pushout_of_mono_f _ _ } end lemma mono_inl_of_is_colimit [mono g] {s : pushout_cocone f g} (hs : is_colimit s) : mono s.inl := begin convert mono_of_mono_fac (is_colimit.comp_cocone_point_unique_up_to_iso_hom hs (colimit.is_colimit _) _), { refl }, { exact abelian.mono_pushout_of_mono_g _ _ } end /-- Suppose `f` and `g` are two morphisms with a common domain and suppose we have written `g` as an epimorphism followed by a monomorphism. If `f` factors through the epi part of this factorization, then any pushout of `g` along `f` is a monomorphism. -/ lemma mono_inl_of_factor_thru_epi_mono_factorization (f : X ⟶ Y) (g : X ⟶ Z) (g₁ : X ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : W ⟶ Y) (hf : g₁ ≫ f' = f) (t : pushout_cocone f g) (ht : is_colimit t) : mono t.inl := by apply mono_inl_of_is_colimit _ _ (pushout_cocone.is_colimit_of_factors _ _ _ _ _ hf hg t ht) end mono_pushout end category_theory.abelian namespace category_theory.non_preadditive_abelian variables (C : Type u) [category.{v} C] [non_preadditive_abelian C] /-- Every non_preadditive_abelian category can be promoted to an abelian category. -/ def abelian : abelian C := { has_finite_products := by apply_instance, /- We need the `convert`s here because the instances we have are slightly different from the instances we need: `has_kernels` depends on an instance of `has_zero_morphisms`. In the case of `non_preadditive_abelian`, this instance is an explicit argument. However, in the case of `abelian`, the `has_zero_morphisms` instance is derived from `preadditive`. So we need to transform an instance of "has kernels with non_preadditive_abelian.has_zero_morphisms" to an instance of "has kernels with non_preadditive_abelian.preadditive.has_zero_morphisms". Luckily, we have a `subsingleton` instance for `has_zero_morphisms`, so `convert` can immediately close the goal it creates for the two instances of `has_zero_morphisms`, and the proof is complete. -/ has_kernels := by convert (by apply_instance : limits.has_kernels C), has_cokernels := by convert (by apply_instance : limits.has_cokernels C), normal_mono := by { introsI, convert normal_mono f }, normal_epi := by { introsI, convert normal_epi f }, ..non_preadditive_abelian.preadditive } end category_theory.non_preadditive_abelian
2d6cd7c15bf40b8bb84d702ec768e2203964d977
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/linear_algebra/finsupp.lean
7b40fd542207f45d9b8ba937fd424256066ae6fd
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
14,107
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finit support `α →₀ β` and multivariate polynomials. -/ import data.finsupp data.mv_polynomial import linear_algebra.dimension noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open lattice set linear_map submodule namespace finsupp section module variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [ring γ] [add_comm_group β] [module γ β] instance : module γ (α →₀ β) := finsupp.to_module α β def lsingle (a : α) : β →ₗ[γ] (α →₀ β) := ⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩ def lapply (a : α) : (α →₀ β) →ₗ[γ] β := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩ section lmap_domain variables {α' : Type*} [decidable_eq α'] def lmap_domain (i : α → α') : (α →₀ β) →ₗ[γ] (α' →₀ β) := ⟨map_domain i, assume a b, map_domain_add, map_domain_smul⟩ lemma lmap_domain_apply (i : α → α') (f : α →₀ β) : (lmap_domain i : (α →₀ β) →ₗ[γ] (α' →₀ β)) f = map_domain i f := rfl end lmap_domain protected def dom_lcongr {α₁ : Type*} {α₂ : Type*} [decidable_eq α₁] [decidable_eq α₂] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ₗ[γ] (α₂ →₀ β) := (finsupp.dom_congr e).to_linear_equiv begin change is_linear_map γ (lmap_domain e : (α₁ →₀ β) →ₗ[γ] (α₂ →₀ β)), exact linear_map.is_linear _ end section lsubtype_domain variables (s : set α) [decidable_pred (λx, x ∈ s)] def lsubtype_domain : (α →₀ β) →ₗ[γ] (s →₀ β) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ β) : (lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain lemma lsingle_apply (a : α) (b : β) : (lsingle a : β →ₗ[γ] (α →₀ β)) b = single a b := rfl lemma lapply_apply (a : α) (f : α →₀ β) : (lapply a : (α →₀ β) →ₗ[γ] β) f = f a := rfl lemma ker_lsingle (a : α) : (lsingle a : β →ₗ[γ] (α →₀ β)).ker = ⊥ := ker_eq_bot.2 (injective_single a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ β) →ₗ[γ] β)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : β →ₗ[γ] (α →₀ β)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : β →ₗ[γ] (α →₀ β)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint_mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set β) (a : α) : submodule.span γ (single a '' s) = (submodule.span γ s).map (lsingle a) := by rw ← span_image; refl lemma linear_independent_single {f : α → set β} (hf : ∀a, linear_independent γ (f a)) : linear_independent γ (⋃a, single a '' f a) := begin refine linear_independent_Union_finite _ _ , { refine assume a, @linear_independent.image _ _ _ _ _ _ _ _ _ (lsingle a) (hf a) _, rw ker_lsingle, exact disjoint_bot_right }, { assume a s hs hat, have : ∀a, span γ (single a '' f a) ≤ range (lsingle a), { simp only [span_single_image], exact assume a, map_mono le_top }, refine disjoint_mono _ _ (disjoint_lsingle_lsingle {a} s _), { simp only [supr_singleton, this] }, { exact supr_le_supr (assume a, supr_le_supr (assume ha, this a)) }, { rwa [disjoint_singleton_left] } } end section variables (β γ) def restrict_dom (s : set α) : submodule γ (α →₀ β) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end lemma mem_restrict_dom {s : set α} (p : α →₀ β) : p ∈ (restrict_dom β γ s) ↔ ↑p.support ⊆ s := iff.rfl section set_option class.instance_max_depth 37 def restrict_dom_equiv_finsupp (s : set α) [decidable_pred (λ (x : α), x ∈ s)] : (restrict_dom β γ s) ≃ₗ[γ] (s →₀ β) := (restrict_support_equiv s).to_linear_equiv begin show is_linear_map γ ((lsubtype_domain s : (α →₀ β) →ₗ[γ] (s →₀ β)).comp (submodule.subtype (restrict_dom β γ s))), exact linear_map.is_linear _ end end end end module section vector_space variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] open linear_map submodule instance : vector_space γ (α →₀ β) := { to_module := finsupp.module } lemma is_basis_single {f : α → set β} (hf : ∀a, is_basis γ (f a)) : is_basis γ (⋃a, single a '' f a) := ⟨linear_independent_single $ assume a, (hf a).1, by simp only [span_Union, span_single_image, (hf _).2, map_top, supr_lsingle_range]⟩ end vector_space section dim universes u v variables {α : Type u} {β : Type u} {γ : Type v} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] lemma dim_eq : vector_space.dim γ (α →₀ β) = cardinal.mk α * vector_space.dim γ β := begin rcases exists_is_basis γ β with ⟨bs, hbs⟩, rw [← hbs.mk_eq_dim, ← (is_basis_single (λa:α, hbs)).mk_eq_dim, cardinal.mk_Union_eq_sum_mk], { simp only [cardinal.mk_eq_of_injective (injective_single.{u u} _), cardinal.sum_const] }, { refine assume i j h, disjoint_image_image (assume b hb c hc, _), simp only [(≠), single_eq_single_iff, not_or_distrib, not_and_distrib], have : (0:β) ∉ bs := zero_not_mem_of_linear_independent (zero_ne_one : (0:γ) ≠ 1) hbs.1, exact ⟨or.inl h, or.inl (assume eq, this $ eq ▸ hb)⟩ } end end dim end finsupp namespace lc universes u v w variables (α : Type v) {β : Type u} {γ : Type w} variables [ring α] variables [add_comm_group β] [module α β] variables [add_comm_group γ] [module α γ] noncomputable def congr (s : set β) (t : set γ) (e : s ≃ t) : supported α s ≃ₗ[α] supported α t := begin show (finsupp.restrict_dom α α s) ≃ₗ[α] (finsupp.restrict_dom α α t), refine linear_equiv.trans (finsupp.restrict_dom_equiv_finsupp α α s) (linear_equiv.trans _ (finsupp.restrict_dom_equiv_finsupp α α t).symm), exact finsupp.dom_lcongr e end -- TODO: this is bad, we need to fix the decidability instances noncomputable def supported_equiv [decidable_eq β] (s : set β) : lc.supported α s ≃ₗ[α] (s →₀ α) := begin have eq : _inst_6 = (λa b : β, classical.prop_decidable (a = b)) := subsingleton.elim _ _, unfreezeI, subst eq, refine (finsupp.restrict_dom_equiv_finsupp α α s) end end lc section vector_space universes u v variables {α : Type u} {β γ : Type v} variables [discrete_field α] variables [add_comm_group β] [vector_space α β] variables [add_comm_group γ] [vector_space α γ] open vector_space set_option class.instance_max_depth 100 lemma equiv_of_dim_eq_dim (h : dim α β = dim α γ) : nonempty (β ≃ₗ[α] γ) := begin rcases exists_is_basis α β with ⟨b, hb⟩, rcases exists_is_basis α γ with ⟨c, hc⟩, rw [← hb.mk_eq_dim, ← hc.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, exact ⟨ (module_equiv_lc hb).trans (linear_equiv.trans (lc.congr α b c e) (module_equiv_lc hc).symm) ⟩ end lemma eq_bot_iff_dim_eq_zero (p : submodule α β) (h : dim α p = 0) : p = ⊥ := begin have : dim α p = dim α (⊥ : submodule α β) := by rwa [dim_bot], rcases equiv_of_dim_eq_dim this with ⟨e⟩, exact e.eq_bot_of_equiv _ end lemma injective_of_surjective (f : β →ₗ[α] γ) (hβ : dim α β < cardinal.omega) (heq : dim α γ = dim α β) (hf : f.range = ⊤) : f.ker = ⊥ := have hk : dim α f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hβ, begin rcases cardinal.lt_omega.1 hβ with ⟨d₁, eq₁⟩, rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩, have : 0 = d₂, { have := dim_eq_surjective f (linear_map.range_eq_top.1 hf), rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this, exact nat.add_left_cancel this }, refine eq_bot_iff_dim_eq_zero _ _, rw [eq₂, ← this, nat.cast_zero] end end vector_space section vector_space universes u open vector_space set_option class.instance_max_depth 100 lemma cardinal_mk_eq_cardinal_mk_field_pow_dim {α β : Type u} [discrete_field α] [add_comm_group β] [vector_space α β] (h : dim α β < cardinal.omega) : cardinal.mk β = cardinal.mk α ^ dim α β := begin rcases exists_is_basis α β with ⟨s, hs⟩, have : nonempty (fintype s), { rwa [← cardinal.lt_omega_iff_fintype, hs.mk_eq_dim] }, cases this with hsf, letI := hsf, calc cardinal.mk β = cardinal.mk (↥(lc.supported α s)) : quotient.sound ⟨(module_equiv_lc hs).to_equiv⟩ ... = cardinal.mk (s →₀ α) : begin refine quotient.sound ⟨@linear_equiv.to_equiv α _ _ _ _ _ _ _ _⟩, convert @lc.supported_equiv α β _ _ _ _ s, { funext, exact subsingleton.elim _ _ }, end ... = cardinal.mk (s → α) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_dim_lt_omega {α β : Type u} [discrete_field α] [add_comm_group β] [vector_space α β] [fintype α] (h : dim α β < cardinal.omega) : cardinal.mk β < cardinal.omega := begin rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h], exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h end end vector_space namespace mv_polynomial universes u v variables {σ : Type u} {α : Type v} [decidable_eq σ] instance [discrete_field α] : vector_space α (mv_polynomial σ α) := finsupp.vector_space section variables (σ α) [discrete_field α] (m : ℕ) def restrict_total_degree : submodule α (mv_polynomial σ α) := finsupp.restrict_dom _ _ {n | n.sum (λn e, e) ≤ m } lemma mem_restrict_total_degree (p : mv_polynomial σ α) : p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end end noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := assume n, classical.prop_decidable _ section variables (σ α) def restrict_degree (m : ℕ) [discrete_field α] : submodule α (mv_polynomial σ α) := finsupp.restrict_dom _ _ {n | ∀i, n i ≤ m } end lemma mem_restrict_degree [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_restrict_dom], refl end lemma mem_restrict_degree_iff_sup [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end lemma map_range_eq_map {β : Type*} [decidable_eq α] [comm_ring α] [decidable_eq β] [comm_ring β] (p : mv_polynomial σ α) (f : α → β) [is_semiring_hom f]: finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f := begin rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum, ← finset.sum_hom (map f)], { refine finset.sum_congr rfl (assume n _, _), rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] }, apply_instance end section variables (σ α) lemma is_basis_monomials [discrete_field α] : is_basis α (range (λs, monomial s 1) : set (mv_polynomial σ α)) := suffices is_basis α (⋃i, (monomial i : α → mv_polynomial σ α) '' {1}), by simpa only [range_eq_Union, image_singleton], finsupp.is_basis_single (assume s, is_basis_singleton_one α) end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [decidable_eq σ] [discrete_field α] lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) := begin rw [← (is_basis_monomials σ α).mk_eq_dim, ← set.image_univ, cardinal.mk_eq_of_injective, cardinal.mk_univ], assume a b h, rcases (finsupp.single_eq_single_iff _ _ _ _).1 h with ⟨rfl, _⟩ | ⟨h, _⟩, { refl }, { exact (zero_ne_one.symm h).elim } end end mv_polynomial
13e2345aa976f57a889a3af290a71c982d89f616
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/analysis/analytic/basic.lean
72e87bae62483acb46df3488e6fd2c349826b7fa
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,320
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import data.equiv.fin /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥₊ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma le_radius_of_eventually_le (C) (h : ∀ᶠ n in at_top, ∥p n∥ * r ^ n ≤ C) : ↑r ≤ p.radius := p.le_radius_of_is_O $ is_O.of_bound C $ h.mono $ λ n hn, by simpa lemma le_radius_of_summable_nnnorm (h : summable (λ n, ∥p n∥₊ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_bound_nnreal (∑' n, ∥p n∥₊ * r ^ n) $ λ n, le_tsum' h _ lemma le_radius_of_summable (h : summable (λ n, ∥p n∥ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_summable_nnnorm $ by { simp only [← coe_nnnorm] at h, exact_mod_cast h } lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, nat.sub_add_cancel hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc abs (∥p n∥ * r ^ n) = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, rw [← pos_iff_ne_zero, ← nnreal.coe_pos] at h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := by simpa only [div_one] using (div_lt_div_left h₀ zero_lt_one ha.1).2 ha.2, norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥₊ * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < ∥x∥₊) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_of_lt_radius (p : formal_multilinear_series 𝕜 E F) (h : ↑r < p.radius) : summable (λ n, ∥p n∥ * r^n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) end lemma summable_of_nnnorm_lt_radius (p : formal_multilinear_series 𝕜 E F) [complete_space F] {x : E} (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : summable (λ n, p n (λ i, x)) := begin refine summable_of_norm_bounded (λ n, ∥p n∥ * ∥x∥₊^n) (p.summable_norm_of_lt_radius h) _, intros n, calc ∥(p n) (λ (i : fin n), x)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥x∥) : continuous_multilinear_map.le_op_norm _ _ ... = ∥p n∥ * ∥x∥₊^n : by simp end lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow' _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_0_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_0_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)), rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at lemma formal_multilinear_series.summable_norm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥ * r ^ n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, exact summable_of_nonneg_of_le (λ n, mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg _)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _), end lemma formal_multilinear_series.summable_nnnorm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥₊ * r ^ n) := by { rw ← nnreal.summable_coe, push_cast, exact p.summable_norm_mul_pow h } protected lemma formal_multilinear_series.summable [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, p n (λ _, x)) := begin rw mem_emetric_ball_0_iff at hx, refine summable_of_norm_bounded _ (p.summable_norm_mul_pow hx) (λ n, ((p n).le_op_norm _).trans_eq _), simp end protected lemma formal_multilinear_series.has_sum [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : has_sum (λ n : ℕ, p n (λ _, x)) (p.sum x) := (p.summable hx).has_sum /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ protected lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, by { rw zero_add, exact p.has_sum hy } } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := (h.has_sum hy).unique (p.has_sum (lt_of_lt_of_le hy h.r_le)) /-- The sum of a converging power series is continuous in its disk of convergence. -/ protected lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series section variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} /-- A term of `formal_multilinear_series.change_origin_series`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Each term of `p.change_origin x` is itself an analytic function of `x` given by the series `p.change_origin_series`. Each term in `change_origin_series` is the sum of `change_origin_series_term`'s over all `s` of cardinality `l`. -/ def change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : E [×l]→L[𝕜] E [×k]→L[𝕜] F := continuous_multilinear_map.curry_fin_finset 𝕜 E F hs (by erw [finset.card_compl, fintype.card_fin, hs, nat.add_sub_cancel]) (p $ k + l) lemma change_origin_series_term_apply (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y)) := continuous_multilinear_map.curry_fin_finset_apply_const _ _ _ _ _ @[simp] lemma norm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥ = ∥p (k + l)∥ := by simp only [change_origin_series_term, linear_isometry_equiv.norm_map] @[simp] lemma nnnorm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥₊ = ∥p (k + l)∥₊ := by simp only [change_origin_series_term, linear_isometry_equiv.nnnorm_map] lemma nnnorm_change_origin_series_term_apply_le (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : ∥p.change_origin_series_term k l s hs (λ _, x) (λ _, y)∥₊ ≤ ∥p (k + l)∥₊ * ∥x∥₊ ^ l * ∥y∥₊ ^ k := begin rw [← p.nnnorm_change_origin_series_term k l s hs, ← fin.prod_const, ← fin.prod_const], apply continuous_multilinear_map.le_of_op_nnnorm_le, apply continuous_multilinear_map.le_op_nnnorm end /-- The power series for `f.change_origin k`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin_series (k : ℕ) : formal_multilinear_series 𝕜 E (E [×k]→L[𝕜] F) := λ l, ∑ s : {s : finset (fin (k + l)) // finset.card s = l}, p.change_origin_series_term k l s s.2 lemma nnnorm_change_origin_series_le_tsum (k l : ℕ) : ∥p.change_origin_series k l∥₊ ≤ ∑' (x : {s : finset (fin (k + l)) // s.card = l}), ∥p (k + l)∥₊ := (nnnorm_sum_le _ _).trans_eq $ by simp only [tsum_fintype, nnnorm_change_origin_series_term] lemma nnnorm_change_origin_series_apply_le_tsum (k l : ℕ) (x : E) : ∥p.change_origin_series k l (λ _, x)∥₊ ≤ ∑' s : {s : finset (fin (k + l)) // s.card = l}, ∥p (k + l)∥₊ * ∥x∥₊ ^ l := begin rw [nnreal.tsum_mul_right, ← fin.prod_const], exact (p.change_origin_series k l).le_of_op_nnnorm_le _ (p.nnnorm_change_origin_series_le_tsum _ _) end /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, (p.change_origin_series k).sum x /-- An auxiliary equivalence useful in the proofs about `formal_multilinear_series.change_origin_series`: the set of triples `(k, l, s)`, where `s` is a `finset (fin (k + l))` of cardinality `l` is equivalent to the set of pairs `(n, s)`, where `s` is a `finset (fin n)`. The forward map sends `(k, l, s)` to `(k + l, s)` and the inverse map sends `(n, s)` to `(n - finset.card s, finset.card s, s)`. The actual definition is less readable because of problems with non-definitional equalities. -/ @[simps] def change_origin_index_equiv : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}) ≃ Σ n : ℕ, finset (fin n) := { to_fun := λ s, ⟨s.1 + s.2.1, s.2.2⟩, inv_fun := λ s, ⟨s.1 - s.2.card, s.2.card, ⟨s.2.map (fin.cast $ (nat.sub_add_cancel $ card_finset_fin_le s.2).symm).to_equiv.to_embedding, finset.card_map _⟩⟩, left_inv := begin rintro ⟨k, l, ⟨s : finset (fin $ k + l), hs : s.card = l⟩⟩, dsimp only [subtype.coe_mk], -- Lean can't automatically generalize `k' = k + l - s.card`, `l' = s.card`, so we explicitly -- formulate the generalized goal suffices : ∀ k' l', k' = k → l' = l → ∀ (hkl : k + l = k' + l') hs', (⟨k', l', ⟨finset.map (fin.cast hkl).to_equiv.to_embedding s, hs'⟩⟩ : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l})) = ⟨k, l, ⟨s, hs⟩⟩, { apply this; simp only [hs, nat.add_sub_cancel] }, rintro _ _ rfl rfl hkl hs', simp only [equiv.refl_to_embedding, fin.cast_refl, finset.map_refl, eq_self_iff_true, order_iso.refl_to_equiv, and_self, heq_iff_eq] end, right_inv := begin rintro ⟨n, s⟩, simp [nat.sub_add_cancel (card_finset_fin_le s), fin.cast_to_equiv] end } lemma change_origin_series_summable_aux₁ {r r' : ℝ≥0} (hr : (r + r' : ℝ≥0∞) < p.radius) : summable (λ s : Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (s.1 + s.2.1)∥₊ * r ^ s.2.1 * r' ^ s.1) := begin rw ← change_origin_index_equiv.symm.summable_iff, dsimp only [(∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst], have : ∀ n : ℕ, has_sum (λ s : finset (fin n), ∥p (n - s.card + s.card)∥₊ * r ^ s.card * r' ^ (n - s.card)) (∥p n∥₊ * (r + r') ^ n), { intro n, -- TODO: why `simp only [nat.sub_add_cancel (card_finset_fin_le _)]` fails? convert_to has_sum (λ s : finset (fin n), ∥p n∥₊ * (r ^ s.card * r' ^ (n - s.card))) _, { ext1 s, rw [nat.sub_add_cancel (card_finset_fin_le _), mul_assoc] }, rw ← fin.sum_pow_mul_eq_add_pow, exact (has_sum_fintype _).mul_left _ }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact p.summable_nnnorm_mul_pow hr end lemma change_origin_series_summable_aux₂ (hr : (r : ℝ≥0∞) < p.radius) (k : ℕ) : summable (λ s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * r ^ s.1) := begin rcases ennreal.lt_iff_exists_add_pos_lt.1 hr with ⟨r', h0, hr'⟩, simpa only [mul_inv_cancel_right' (pow_pos h0 _).ne'] using ((nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr')).1 k).mul_right (r' ^ k)⁻¹ end lemma change_origin_series_summable_aux₃ {r : ℝ≥0} (hr : ↑r < p.radius) (k : ℕ) : summable (λ l : ℕ, ∥p.change_origin_series k l∥₊ * r ^ l) := begin refine nnreal.summable_of_le (λ n, _) (nnreal.summable_sigma.1 $ p.change_origin_series_summable_aux₂ hr k).2, simp only [nnreal.tsum_mul_right], exact mul_le_mul' (p.nnnorm_change_origin_series_le_tsum _ _) le_rfl end lemma le_change_origin_series_radius (k : ℕ) : p.radius ≤ (p.change_origin_series k).radius := ennreal.le_of_forall_nnreal_lt $ λ r hr, le_radius_of_summable_nnnorm _ (p.change_origin_series_summable_aux₃ hr k) lemma nnnorm_change_origin_le (k : ℕ) (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : ∥p.change_origin x k∥₊ ≤ ∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1 := begin refine tsum_of_nnnorm_bounded _ (λ l, p.nnnorm_change_origin_series_apply_le_tsum k l x), have := p.change_origin_series_summable_aux₂ h k, refine has_sum.sigma this.has_sum (λ l, _), exact ((nnreal.summable_sigma.1 this).1 l).has_sum end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - ∥x∥₊ ≤ (p.change_origin x).radius := begin refine ennreal.le_of_forall_pos_nnreal_lt (λ r h0 hr, _), rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, have hr' : (∥x∥₊ : ℝ≥0∞) < p.radius, from (le_add_right le_rfl).trans_lt hr, apply le_radius_of_summable_nnnorm, have : ∀ k : ℕ, ∥p.change_origin x k∥₊ * r ^ k ≤ (∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1) * r ^ k, from λ k, mul_le_mul_right' (p.nnnorm_change_origin_le k hr') (r ^ k), refine nnreal.summable_of_le this _, simpa only [← nnreal.tsum_mul_right] using (nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr)).2 end end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variables [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} lemma has_fpower_series_on_ball_change_origin (k : ℕ) (hr : 0 < p.radius) : has_fpower_series_on_ball (λ x, p.change_origin x k) (p.change_origin_series k) 0 p.radius := have _ := p.le_change_origin_series_radius k, ((p.change_origin_series k).has_fpower_series_on_ball (hr.trans_le this)).mono hr this /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (∥x∥₊ + ∥y∥₊ : ℝ≥0∞) < p.radius) : (p.change_origin x).sum y = (p.sum (x + y)) := begin have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, have x_mem_ball : x ∈ emetric.ball (0 : E) p.radius, from mem_emetric_ball_0_iff.2 ((le_add_right le_rfl).trans_lt h), have y_mem_ball : y ∈ emetric.ball (0 : E) (p.change_origin x).radius, { refine mem_emetric_ball_0_iff.2 (lt_of_lt_of_le _ p.change_origin_radius), rwa [ennreal.lt_sub_iff_add_lt, add_comm] }, have x_add_y_mem_ball : x + y ∈ emetric.ball (0 : E) p.radius, { refine mem_emetric_ball_0_iff.2 (lt_of_le_of_lt _ h), exact_mod_cast nnnorm_add_le x y }, set f : (Σ (k l : ℕ), {s : finset (fin (k + l)) // s.card = l}) → F := λ s, p.change_origin_series_term s.1 s.2.1 s.2.2 s.2.2.2 (λ _, x) (λ _, y), have hsf : summable f, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₁ h) _, rintro ⟨k, l, s, hs⟩, dsimp only [subtype.coe_mk], exact p.nnnorm_change_origin_series_term_apply_le _ _ _ _ _ _ }, have hf : has_sum f ((p.change_origin x).sum y), { refine has_sum.sigma_of_has_sum ((p.change_origin x).summable y_mem_ball).has_sum (λ k, _) hsf, { dsimp only [f], refine continuous_multilinear_map.has_sum_eval _ _, have := (p.has_fpower_series_on_ball_change_origin k radius_pos).has_sum x_mem_ball, rw zero_add at this, refine has_sum.sigma_of_has_sum this (λ l, _) _, { simp only [change_origin_series, continuous_multilinear_map.sum_apply], apply has_sum_fintype }, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₂ (mem_emetric_ball_0_iff.1 x_mem_ball) k) (λ s, _), refine (continuous_multilinear_map.le_op_nnnorm _ _).trans_eq _, simp } } }, refine hf.unique (change_origin_index_equiv.symm.has_sum_iff.1 _), refine has_sum.sigma_of_has_sum (p.has_sum x_add_y_mem_ball) (λ n, _) (change_origin_index_equiv.symm.summable_iff.2 hsf), erw [(p n).map_add_univ (λ _, x) (λ _, y)], convert has_sum_fintype _, ext1 s, dsimp only [f, change_origin_series_term, (∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst, change_origin_index_equiv_symm_apply_snd_snd_coe], rw continuous_multilinear_map.curry_fin_finset_apply_const, have : ∀ m (hm : n = m), p n (s.piecewise (λ _, x) (λ _, y)) = p m ((s.map (fin.cast hm).to_equiv.to_embedding).piecewise (λ _, x) (λ _, y)), { rintro m rfl, simp, congr /- probably different `decidable_eq` instances -/ }, apply this end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (∥y∥₊ : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - ∥y∥₊) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := λ z hz, begin convert (p.change_origin y).has_sum _, { rw [mem_emetric_ball_0_iff, ennreal.lt_sub_iff_add_lt, add_comm] at hz, rw [p.change_origin_eval (hz.trans_le hf.r_le), add_assoc, hf.sum], refine mem_emetric_ball_0_iff.2 (lt_of_le_of_lt _ hz), exact_mod_cast nnnorm_add_le y z }, { refine emetric.ball_subset_ball (le_trans _ p.change_origin_radius) hz, exact ennreal.sub_le_sub hf.r_le le_rfl } end } /-- If a function admits a power series expansion `p` on an open ball `B (x, r)`, then it is analytic at every point of this ball. -/ lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (∥y - x∥₊ : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) /-- For any function `f` from a normed vector space to a Banach space, the set of points `x` such that `f` is analytic at `x` is open. -/ lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_mem_nhds, rintro x ⟨p, r, hr⟩, exact mem_of_superset (emetric.ball_mem_nhds _ hr.r_pos) (λ y hy, hr.analytic_at_of_mem hy) end end
3bb80fdf044f47d3bd3744c9eebbe3c6b6b636f2
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/breen_deligne.lean
78b985fe37a27b1b3303ff5463e42d1ee9a27502
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,222
lean
import linear_algebra.matrix import group_theory.free_abelian_group import algebra.direct_sum import algebra.big_operators.finsupp import prereqs import type_pow /-! # Breen-Deligne resolutions Reference: https://www.math.uni-bonn.de/people/scholze/Condensed.pdf#section*.4 ("Appendix to Lecture IV", p. 28) We formalize the notion of `breen_deligne_data`. Roughly speaking, this is a collection of formal finite sums of matrices that encode that data that rolls out of the Breen--Deligne resolution. -/ noncomputable theory -- get some notation working: open_locale big_operators direct_sum local attribute [instance] type_pow local notation `ℤ[` A `]` := free_abelian_group A namespace breen_deligne open free_abelian_group /-! Suppose you have an abelian group `A`. What data do you need to specify a "universal" map `f : ℤ[A^m] → ℤ[A^n]`? That is, it should be functorial in `A`. Well, such a map is specified by what it does to `(a 1, a 2, a 3, ..., a m)`. It can send this element to an arbitrary element of `ℤ[A^n]`, but it has to be "universal". In the end, this means that `f` will be a `ℤ`-linear combination of "basic universal maps", where a "basic universal map" is one that sends `(a 1, a 2, ..., a m)` to `(b 1, ..., b n)`, where `b i` is a `ℤ`-linear combination `c i 1 * a 1 + ... + c i m * a m`. So a "basic universal map" is specified by the `n × m`-matrix `c`. -/ @[derive add_comm_group] def basic_universal_map (m n : ℕ) := matrix (fin n) (fin m) ℤ namespace basic_universal_map variables {k l m n : ℕ} (g : basic_universal_map m n) (f : basic_universal_map l m) variables (A : Type*) [add_comm_group A] def eval : ℤ[A^m] →+ ℤ[A^n] := map $ λ x i, ∑ j, g i j • (x : fin _ → A) j @[simp] lemma eval_of (x : A^m) : g.eval A (of x) = (of $ λ i, ∑ j, g i j • x j) := lift.of _ _ def comp : basic_universal_map l n := matrix.mul g f lemma eval_comp : (g.comp f).eval A = (g.eval A).comp (f.eval A) := begin ext1 x, simp only [add_monoid_hom.coe_comp, function.comp_app, eval_of, comp, finset.smul_sum, matrix.mul_apply, finset.sum_smul, mul_smul], congr' 1, ext1 i, exact finset.sum_comm end lemma comp_assoc (h : basic_universal_map m n) (g : basic_universal_map l m) (f : basic_universal_map k l) : comp (comp h g) f = comp h (comp g f) := matrix.mul_assoc _ _ _ def id (n : ℕ) : basic_universal_map n n := (1 : matrix (fin n) (fin n) ℤ) @[simp] lemma id_comp : (id _).comp f = f := by simp only [comp, id, matrix.one_mul] @[simp] lemma comp_id : g.comp (id _) = g := by simp only [comp, id, matrix.mul_one] end basic_universal_map @[derive add_comm_group] def universal_map (m n : ℕ) := ℤ[basic_universal_map m n] namespace universal_map universe variable u variables {k l m n : ℕ} (g : universal_map m n) (f : universal_map l m) variables (A : Type u) [add_comm_group A] def eval : universal_map m n →+ ℤ[A^m] →+ ℤ[A^n] := free_abelian_group.lift $ λ f, f.eval A @[simp] lemma eval_of (f : basic_universal_map m n) : eval A (of f) = f.eval A := lift.of _ _ def comp : universal_map m n →+ universal_map l m →+ universal_map l n := free_abelian_group.lift $ λ g, free_abelian_group.lift $ λ f, of $ g.comp f @[simp] lemma comp_of (g : basic_universal_map m n) (f : basic_universal_map l m) : comp (of g) (of f) = of (g.comp f) := by rw [comp, lift.of, lift.of] section open add_monoid_hom lemma eval_comp : eval A (comp g f) = (eval A g).comp (eval A f) := show comp_hom (comp_hom (@eval l n A _)) (comp) g f = comp_hom (comp_hom (comp_hom.flip (@eval l m A _)) (comp_hom)) (@eval m n A _) g f, begin congr' 2, clear f g, ext g f : 2, show eval A (comp (of g) (of f)) = (eval A (of g)).comp (eval A (of f)), simp only [basic_universal_map.eval_comp, comp_of, eval_of] end lemma comp_assoc (h : universal_map m n) (g : universal_map l m) (f : universal_map k l) : comp (comp h g) f = comp h (comp g f) := show comp_hom (comp_hom (@comp k l n)) (@comp l m n) h g f = comp_hom (comp_hom (comp_hom.flip (@comp k l m)) (comp_hom)) (@comp k m n) h g f, begin congr' 3, clear h g f, ext h g f : 3, show comp (comp (of h) (of g)) (of f) = comp (of h) (comp (of g) (of f)), simp only [basic_universal_map.comp_assoc, comp_of] end def id (n : ℕ) : universal_map n n := of (basic_universal_map.id n) @[simp] lemma id_comp : comp (id _) f = f := show comp (id _) f = add_monoid_hom.id _ f, begin congr' 1, clear f, ext1 f, simp only [id, comp_of, id_apply, basic_universal_map.id_comp] end @[simp] lemma comp_id : comp g (id _) = g := show (@comp m m n).flip (id _) g = add_monoid_hom.id _ g, begin congr' 1, clear g, ext1 g, show comp (of g) (id _) = (of g), simp only [id, comp_of, id_apply, basic_universal_map.comp_id] end def double : universal_map m n →+ universal_map (m + m) (n + n) := map $ λ f, matrix.reindex_linear_equiv sum_fin_sum_equiv sum_fin_sum_equiv $ matrix.from_blocks f 0 0 f lemma double_of (f : basic_universal_map m n) : double (of f) = of (matrix.reindex_linear_equiv sum_fin_sum_equiv sum_fin_sum_equiv $ matrix.from_blocks f 0 0 f) := rfl lemma comp_double_double (g : universal_map m n) (f : universal_map l m) : comp (double g) (double f) = double (comp g f) := show comp_hom (comp_hom (comp_hom.flip (@double l m)) ((@comp (l+l) (m+m) (n+n)))) (double) g f = comp_hom (comp_hom (@double l n)) (@comp l m n) g f, begin congr' 2, clear g f, ext g f : 2, show comp (double (of g)) (double (of f)) = double (comp (of g) (of f)), simp only [double_of, comp_of, basic_universal_map.comp], rw [matrix.reindex_mul, matrix.from_blocks_multiply], congr' 2, simp only [add_zero, matrix.zero_mul, zero_add, matrix.mul_zero], end lemma double_zero : double (0 : universal_map m n) = 0 := double.map_zero end end universal_map /-- Roughly speaking, this is a collection of formal finite sums of matrices that encode that data that rolls out of the Breen--Deligne resolution. -/ structure data := (rank : ℕ → ℕ) (map : Π n, universal_map (rank (n+1)) (rank n)) def is_complex (BD : data) : Prop := ∀ n, universal_map.comp (BD.map n) (BD.map (n+1)) = 0 /- We use a small hack: mathlib only has block matrices with 4 blocks. So we add two zero-width blocks in the definition of `σ_add` and `σ_proj`. -/ def σ_add (n : ℕ) : universal_map (n + n) n := of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 1 1 0 0 def σ_proj (n : ℕ) : universal_map (n + n) n := (of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 1 0 0 0) + (of $ matrix.reindex_linear_equiv (equiv.sum_empty _) sum_fin_sum_equiv $ matrix.from_blocks 0 1 0 0) def σ_diff (n : ℕ) := σ_add n - σ_proj n section universe variables u open universal_map variables {m n : ℕ} (A : Type u) [add_comm_group A] (f : universal_map m n) -- lemma eval_σ_add (n : ℕ) : eval A (σ_add n) = map (λ x, x.left + x.right) := -- begin -- ext x, apply lift.ext; clear x, intro x, -- delta σ_add, -- rw [eval_of, basic_universal_map.eval_of], -- congr' 1, -- ext i, -- simp only [pi.add_apply], -- rw (sum_fin_sum_equiv.sum_comp _).symm, -- swap, { apply_instance }, -- sorry -- end lemma σ_add_comp_double : comp (σ_add n) (double f) = comp f (σ_add m) := show add_monoid_hom.comp_hom ((@comp (m+m) (n+n) n) (σ_add _)) (double) f = (@comp (m+m) m n).flip (σ_add _) f, begin congr' 1, clear f, ext1 f, show comp (σ_add n) (double (of f)) = comp (of f) (σ_add m), dsimp only [double_of, σ_add], simp only [comp_of], conv_rhs { rw ← (matrix.reindex_linear_equiv (equiv.sum_empty _) (equiv.sum_empty _)).apply_symm_apply f }, simp only [basic_universal_map.comp, matrix.reindex_mul, matrix.from_blocks_multiply, add_zero, matrix.one_mul, matrix.mul_one, matrix.zero_mul, zero_add, matrix.reindex_linear_equiv_sum_empty_symm] end -- lemma eval_σ_proj (n : ℕ) : eval A (σ_proj n) = map tuple.left + map tuple.right := -- begin -- ext x, apply lift.ext; clear x, intro x, -- delta σ_proj, -- simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, -- eval_of, basic_universal_map.eval_of], -- congr' 2, -- { ext i, -- rw [(sum_fin_sum_equiv.sum_comp _).symm, finset.sum_eq_single (sum.inl i)], -- { dsimp, sorry }, -- all_goals { sorry } }, -- sorry -- end lemma σ_proj_comp_double : comp (σ_proj n) (double f) = comp f (σ_proj m) := show add_monoid_hom.comp_hom ((@comp (m+m) (n+n) n) (σ_proj _)) (double) f = (@comp (m+m) m n).flip (σ_proj _) f, begin congr' 1, clear f, ext1 f, show comp (σ_proj n) (double (of f)) = comp (of f) (σ_proj m), dsimp only [double_of, σ_proj], simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, comp_of], conv_rhs { rw ← (matrix.reindex_linear_equiv (equiv.sum_empty _) (equiv.sum_empty _)).apply_symm_apply f }, simp only [basic_universal_map.comp, matrix.reindex_mul, matrix.from_blocks_multiply, add_zero, matrix.one_mul, matrix.mul_one, matrix.zero_mul, matrix.mul_zero, zero_add, matrix.reindex_linear_equiv_sum_empty_symm], end lemma σ_diff_comp_double : comp (σ_diff n) (double f) = comp f (σ_diff m) := begin simp only [σ_diff, add_monoid_hom.map_sub, ← σ_add_comp_double, ← σ_proj_comp_double], simp only [sub_eq_add_neg, ← add_monoid_hom.neg_apply, ← add_monoid_hom.add_apply] end end structure homotopy (BD : data) := (map : Π n, universal_map (BD.rank n + BD.rank n) (BD.rank (n+1))) (is_homotopy : ∀ n, σ_diff (BD.rank (n+1)) = universal_map.comp (BD.map (n+1)) (map (n+1)) + universal_map.comp (map n) (BD.map n).double) (is_homotopy_zero : σ_add (BD.rank 0) - σ_proj (BD.rank 0) = universal_map.comp (BD.map 0) (map 0)) -- TODO! Is ↑ the thing we want? structure package := (data : data) (is_complex : is_complex data) (homotopy : homotopy data) namespace package def rank (BD : package) := BD.data.rank def map (BD : package) := BD.data.map @[simp] lemma map_comp_map (BD : package) (n : ℕ) : universal_map.comp (BD.map n) (BD.map (n+1)) = 0 := BD.is_complex n end package namespace eg /-! ## An explicit nontrivial example -/ open universal_map def rank : ℕ → ℕ | 0 := 1 | (n+1) := rank n + rank n lemma rank_eq : ∀ n, rank n = 2 ^ n | 0 := rfl | (n+1) := by rw [pow_succ, two_mul, rank, rank_eq] def map : Π n, universal_map (rank (n+1)) (rank n) | 0 := σ_diff 1 | (n+1) := (σ_diff (rank (n+1))) - (map n).double @[simps] def data : data := ⟨rank, map⟩ def hmap (n : ℕ) : universal_map (rank n + rank n) (rank (n+1)) := universal_map.id _ lemma hmap_is_homotopy : ∀ n, σ_diff (rank (n+1)) = comp (map (n+1)) (hmap (n+1)) + comp (hmap n) (map n).double | _ := by { simp only [hmap, id_comp, comp_id, map], simp only [sub_add_cancel], } lemma hmap_is_homotopy_zero : σ_diff (rank 0) = universal_map.comp (map 0) (hmap 0) := begin simp only [hmap, id_comp, comp_id, map, σ_diff, σ_add, σ_proj, sub_sub], congr' 3; { ext (j : fin 1) (i : fin 2), fin_cases j, fin_cases i; refl } end @[simps] def homotopy : homotopy data := ⟨hmap, hmap_is_homotopy, hmap_is_homotopy_zero⟩ lemma is_complex_zero : comp (map 0) (map 1) = 0 := begin show comp (σ_diff 1) (σ_diff (1+1) - double (σ_diff 1)) = 0, rw [add_monoid_hom.map_sub, σ_diff_comp_double, sub_self], end lemma is_complex_succ (n : ℕ) (ih : (comp (map n)) (map (n + 1)) = 0) : comp (map (n+1)) (map (n+1+1)) = 0 := begin have H := hmap_is_homotopy n, simp only [hmap, comp_id, id_comp] at H, show comp (map (n+1)) ((σ_diff (rank $ n+1+1)) - double (map (n+1))) = 0, simp only [add_monoid_hom.map_sub, ← σ_diff_comp_double, H], simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply], simp only [comp_double_double, ih, double_zero, add_zero, sub_self], end lemma is_complex : is_complex data | 0 := is_complex_zero | (n+1) := is_complex_succ n (is_complex n) end eg /-- An example of a Breen--Deligne data coming from a nontrivial complex. -/ def eg : package := ⟨eg.data, eg.is_complex, eg.homotopy⟩ end breen_deligne
3dfc6f9972c33d777a0f36e02f0fe7b379b8ab67
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/topology/metric_space/gromov_hausdorff_realized.lean
bdce8c37b26fa83dcb65da3e45acf058e450663d
[ "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
26,253
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.bounded_continuous_function noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.to_fun ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := pseudo_metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
d95dfc5b0fb4624281f5d5c90b12a2d8b52c810d
2d787ac9a5ab28a7d164cd13cee8a3cdc1e4680a
/src/my_exercises/07bis_abstract_negations.lean
3f9d02c20ed299ebcf68491a8605a8393d52635c
[ "Apache-2.0" ]
permissive
paulzfm/lean3-tutorials
8c113ec2c9494d401c8a877f094db93e5a631fd6
f41baf1c62c251976ec8dd9ccae9e85ec4c4d336
refs/heads/master
1,679,267,488,532
1,614,782,461,000
1,614,782,461,000
344,157,026
0
0
null
null
null
null
UTF-8
Lean
false
false
2,445
lean
import data.real.basic open_locale classical /- Theoretical negations. This file is for people interested in logic who want to fully understand negations. Here we don't use `contrapose` or `push_neg`. The goal is to prove lemmas that are used by those tactics. Of course we can use `exfalso`, `by_contradiction` and `by_cases`. If this doesn't sound like fun then skip ahead to the next file. -/ section negation_prop variables P Q : Prop -- 0055 example : (P → Q) ↔ (¬ Q → ¬ P) := begin split, { intros h hnotQ hP, apply hnotQ, apply h, exact hP, }, { intros h hP, by_contradiction hnotQ, specialize h hnotQ, apply h, exact hP, } end -- 0056 lemma non_imp (P Q : Prop) : ¬ (P → Q) ↔ P ∧ ¬ Q := begin split, { intros h, by_contradiction H, apply h, intro hP, by_contradiction hnotQ, apply H, exact ⟨hP, hnotQ⟩, }, { rintros ⟨hP, hnotQ⟩ h, specialize h hP, apply hnotQ, exact h, } end -- In the next one, let's use the axiom -- propext {P Q : Prop} : (P ↔ Q) → P = Q -- 0057 example (P : Prop) : ¬ P ↔ P = false := begin split, { intro hnotP, apply propext, split, { exact hnotP, }, { intro contra, exfalso, exact contra, } }, { rintro rfl, intro contra, exfalso, exact contra, } end end negation_prop section negation_quantifiers variables (X : Type) (P : X → Prop) -- 0058 example : ¬ (∀ x, P x) ↔ ∃ x, ¬ P x := begin split, { intro h, by_contradiction H, apply h, intro x, by_contradiction hnotP, apply H, use x, }, { rintros ⟨x, hnotP⟩ h', apply hnotP, exact h' x, } end -- 0059 example : ¬ (∃ x, P x) ↔ ∀ x, ¬ P x := begin split, { intros h x hP, apply h, use [x, hP], }, { rintros h ⟨x, hnotP⟩, exact h x hnotP, } end -- 0060 example (P : ℝ → Prop) : ¬ (∃ ε > 0, P ε) ↔ ∀ ε > 0, ¬ P ε := begin split, { intros h ε hε hP, apply h, use [ε, hε, hP], }, { rintros h ⟨ε, hε, hP⟩, exact h ε hε hP, } end -- 0061 example (P : ℝ → Prop) : ¬ (∀ x > 0, P x) ↔ ∃ x > 0, ¬ P x := begin split, { intros h, by_contradiction H, apply h, intros x hx, by_contradiction hnotP, apply H, use [x, hx, hnotP], }, { rintros ⟨x, hx, hnotP⟩ h, apply hnotP, exact h x hx, } end end negation_quantifiers
8ff8141725ad9db33ea571b6d7023f415b11437d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/lie/basic.lean
c0be2e4fea34a611ae46d736199842b8a9eb4fe2
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,628
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.bracket import algebra.algebra.basic import tactic.noncomm_ring /-! # Lie algebras This file defines Lie rings and Lie algebras over a commutative ring together with their modules, morphisms and equivalences, as well as various lemmas to make these definitions usable. ## Main definitions * `lie_ring` * `lie_algebra` * `lie_ring_module` * `lie_module` * `lie_hom` * `lie_equiv` * `lie_module_hom` * `lie_module_equiv` ## Notation Working over a fixed commutative ring `R`, we introduce the notations: * `L →ₗ⁅R⁆ L'` for a morphism of Lie algebras, * `L ≃ₗ⁅R⁆ L'` for an equivalence of Lie algebras, * `M →ₗ⁅R,L⁆ N` for a morphism of Lie algebra modules `M`, `N` over a Lie algebra `L`, * `M ≃ₗ⁅R,L⁆ N` for an equivalence of Lie algebra modules `M`, `N` over a Lie algebra `L`. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure and thus, like modules, are partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975) ## Tags lie bracket, jacobi identity, lie ring, lie algebra, lie module -/ universes u v w w₁ w₂ /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. -/ @[protect_proj] class lie_ring (L : Type v) extends add_comm_group L, has_bracket L L := (add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : ∀ (x y z : L), ⁅x, y + z⁆ = ⁅x, y⁆ + ⁅x, z⁆) (lie_self : ∀ (x : L), ⁅x, x⁆ = 0) (leibniz_lie : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆) /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ @[protect_proj] class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends module R L := (lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆) /-- A Lie ring module is an additive group, together with an additive action of a Lie ring on this group, such that the Lie bracket acts as the commutator of endomorphisms. (For representations of Lie *algebras* see `lie_module`.) -/ @[protect_proj] class lie_ring_module (L : Type v) (M : Type w) [lie_ring L] [add_comm_group M] extends has_bracket L M := (add_lie : ∀ (x y : L) (m : M), ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆) (lie_add : ∀ (x : L) (m n : M), ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆) (leibniz_lie : ∀ (x y : L) (m : M), ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆) /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ @[protect_proj] class lie_module (R : Type u) (L : Type v) (M : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] [lie_ring_module L M] := (smul_lie : ∀ (t : R) (x : L) (m : M), ⁅t • x, m⁆ = t • ⁅x, m⁆) (lie_smul : ∀ (t : R) (x : L) (m : M), ⁅x, t • m⁆ = t • ⁅x, m⁆) section basic_properties variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] variables (t : R) (x y z : L) (m n : M) @[simp] lemma add_lie : ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆ := lie_ring_module.add_lie x y m @[simp] lemma lie_add : ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆ := lie_ring_module.lie_add x m n @[simp] lemma smul_lie : ⁅t • x, m⁆ = t • ⁅x, m⁆ := lie_module.smul_lie t x m @[simp] lemma lie_smul : ⁅x, t • m⁆ = t • ⁅x, m⁆ := lie_module.lie_smul t x m lemma leibniz_lie : ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆ := lie_ring_module.leibniz_lie x y m @[simp] lemma lie_zero : ⁅x, 0⁆ = (0 : M) := (add_monoid_hom.mk' _ (lie_add x)).map_zero @[simp] lemma zero_lie : ⁅(0 : L), m⁆ = 0 := (add_monoid_hom.mk' (λ (x : L), ⁅x, m⁆) (λ x y, add_lie x y m)).map_zero @[simp] lemma lie_self : ⁅x, x⁆ = 0 := lie_ring.lie_self x instance lie_ring_self_module : lie_ring_module L L := { ..(infer_instance : lie_ring L) } @[simp] lemma lie_skew : -⁅y, x⁆ = ⁅x, y⁆ := have h : ⁅x + y, x⁆ + ⁅x + y, y⁆ = 0, { rw ← lie_add, apply lie_self, }, by simpa [neg_eq_iff_add_eq_zero] using h /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := { smul_lie := λ t x m, by rw [←lie_skew, ←lie_skew x m, lie_algebra.lie_smul, smul_neg], lie_smul := by apply lie_algebra.lie_smul, } @[simp] lemma neg_lie : ⁅-x, m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg : ⁅x, -m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←lie_add], simp, } @[simp] lemma sub_lie : ⁅x - y, m⁆ = ⁅x, m⁆ - ⁅y, m⁆ := by simp [sub_eq_add_neg] @[simp] lemma lie_sub : ⁅x, m - n⁆ = ⁅x, m⁆ - ⁅x, n⁆ := by simp [sub_eq_add_neg] @[simp] lemma nsmul_lie (n : ℕ) : ⁅n • x, m⁆ = n • ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_nsmul (n : ℕ) : ⁅x, n • m⁆ = n • ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, λ _ _, lie_add _ _ _⟩ _ _ @[simp] lemma gsmul_lie (a : ℤ) : ⁅a • x, m⁆ = a • ⁅x, m⁆ := add_monoid_hom.map_gsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_gsmul (a : ℤ) : ⁅x, a • m⁆ = a • ⁅x, m⁆ := add_monoid_hom.map_gsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, λ _ _, lie_add _ _ _⟩ _ _ @[simp] lemma lie_lie : ⁅⁅x, y⁆, m⁆ = ⁅x, ⁅y, m⁆⁆ - ⁅y, ⁅x, m⁆⁆ := by rw [leibniz_lie, add_sub_cancel] lemma lie_jacobi : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := by { rw [← neg_neg ⁅x, y⁆, lie_neg z, lie_skew y x, ← lie_skew, lie_lie], abel, } instance lie_ring.int_lie_algebra : lie_algebra ℤ L := { lie_smul := λ n x y, lie_gsmul x y n, } instance : lie_ring_module L (M →ₗ[R] N) := { bracket := λ x f, { to_fun := λ m, ⁅x, f m⁆ - f ⁅x, m⁆, map_add' := λ m n, by { simp only [lie_add, linear_map.map_add], abel, }, map_smul' := λ t m, by simp only [smul_sub, linear_map.map_smul, lie_smul, ring_hom.id_apply] }, add_lie := λ x y f, by { ext n, simp only [add_lie, linear_map.coe_mk, linear_map.add_apply, linear_map.map_add], abel, }, lie_add := λ x f g, by { ext n, simp only [linear_map.coe_mk, lie_add, linear_map.add_apply], abel, }, leibniz_lie := λ x y f, by { ext n, simp only [lie_lie, linear_map.coe_mk, linear_map.map_sub, linear_map.add_apply, lie_sub], abel, }, } @[simp] lemma lie_hom.lie_apply (f : M →ₗ[R] N) (x : L) (m : M) : ⁅x, f⁆ m = ⁅x, f m⁆ - f ⁅x, m⁆ := rfl instance : lie_module R L (M →ₗ[R] N) := { smul_lie := λ t x f, by { ext n, simp only [smul_sub, smul_lie, linear_map.smul_apply, lie_hom.lie_apply, linear_map.map_smul], }, lie_smul := λ t x f, by { ext n, simp only [smul_sub, linear_map.smul_apply, lie_hom.lie_apply, lie_smul], }, } end basic_properties /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure lie_hom (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ[R] L' := (map_lie' : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) attribute [nolint doc_blame] lie_hom.to_linear_map notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := lie_hom R L L' namespace lie_hom variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] variables [lie_ring L₁] [lie_algebra R L₁] variables [lie_ring L₂] [lie_algebra R L₂] variables [lie_ring L₃] [lie_algebra R L₃] instance : has_coe (L₁ →ₗ⁅R⁆ L₂) (L₁ →ₗ[R] L₂) := ⟨lie_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ L₂) (λ _, L₁ → L₂) := ⟨λ f, f.to_linear_map.to_fun⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂ := h initialize_simps_projections lie_hom (to_linear_map_to_fun → apply) @[simp, norm_cast] lemma coe_to_linear_map (f : L₁ →ₗ⁅R⁆ L₂) : ((f : L₁ →ₗ[R] L₂) : L₁ → L₂) = f := rfl @[simp] lemma to_fun_eq_coe (f : L₁ →ₗ⁅R⁆ L₂) : f.to_fun = ⇑f := rfl @[simp] lemma map_smul (f : L₁ →ₗ⁅R⁆ L₂) (c : R) (x : L₁) : f (c • x) = c • f x := linear_map.map_smul (f : L₁ →ₗ[R] L₂) c x @[simp] lemma map_add (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : L₁ →ₗ[R] L₂) x y @[simp] lemma map_sub (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : L₁ →ₗ[R] L₂) x y @[simp] lemma map_neg (f : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f (-x) = -(f x) := linear_map.map_neg (f : L₁ →ₗ[R] L₂) x @[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := lie_hom.map_lie' f @[simp] lemma map_zero (f : L₁ →ₗ⁅R⁆ L₂) : f 0 = 0 := (f : L₁ →ₗ[R] L₂).map_zero /-- The identity map is a morphism of Lie algebras. -/ def id : L₁ →ₗ⁅R⁆ L₁ := { map_lie' := λ x y, rfl, .. (linear_map.id : L₁ →ₗ[R] L₁) } @[simp] lemma coe_id : ((id : L₁ →ₗ⁅R⁆ L₁) : L₁ → L₁) = _root_.id := rfl lemma id_apply (x : L₁) : (id : L₁ →ₗ⁅R⁆ L₁) x = x := rfl /-- The constant 0 map is a Lie algebra morphism. -/ instance : has_zero (L₁ →ₗ⁅R⁆ L₂) := ⟨{ map_lie' := by simp, ..(0 : L₁ →ₗ[R] L₂)}⟩ @[norm_cast, simp] lemma coe_zero : ((0 : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = 0 := rfl lemma zero_apply (x : L₁) : (0 : L₁ →ₗ⁅R⁆ L₂) x = 0 := rfl /-- The identity map is a Lie algebra morphism. -/ instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨id⟩ @[simp] lemma coe_one : ((1 : (L₁ →ₗ⁅R⁆ L₁)) : L₁ → L₁) = _root_.id := rfl lemma one_apply (x : L₁) : (1 : (L₁ →ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ →ₗ⁅R⁆ L₂) := ⟨0⟩ lemma coe_injective : @function.injective (L₁ →ₗ⁅R⁆ L₂) (L₁ → L₂) coe_fn := by rintro ⟨⟨f, _⟩⟩ ⟨⟨g, _⟩⟩ ⟨h⟩; congr @[ext] lemma ext {f g : L₁ →ₗ⁅R⁆ L₂} (h : ∀ x, f x = g x) : f = g := coe_injective $ funext h lemma ext_iff {f g : L₁ →ₗ⁅R⁆ L₂} : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ lemma congr_fun {f g : L₁ →ₗ⁅R⁆ L₂} (h : f = g) (x : L₁) : f x = g x := h ▸ rfl @[simp] lemma mk_coe (f : L₁ →ₗ⁅R⁆ L₂) (h₁ h₂ h₃) : (⟨⟨f, h₁, h₂⟩, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) = f := by { ext, refl, } @[simp] lemma coe_mk (f : L₁ → L₂) (h₁ h₂ h₃) : ((⟨⟨f, h₁, h₂⟩, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = f := rfl /-- The composition of morphisms is a morphism. -/ def comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ⁅R⁆ L₃ := { map_lie' := λ x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f.comp g x = f (g x) := rfl @[norm_cast, simp] lemma coe_comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : (f.comp g : L₁ → L₃) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : (f.comp g : L₁ →ₗ[R] L₃) = (f : L₂ →ₗ[R] L₃).comp (g : L₁ →ₗ[R] L₂) := rfl @[simp] lemma comp_id (f : L₁ →ₗ⁅R⁆ L₂) : f.comp (id : L₁ →ₗ⁅R⁆ L₁) = f := by { ext, refl, } @[simp] lemma id_comp (f : L₁ →ₗ⁅R⁆ L₂) : (id : L₂ →ₗ⁅R⁆ L₂).comp f = f := by { ext, refl, } /-- The inverse of a bijective morphism is a morphism. -/ def inverse (f : L₁ →ₗ⁅R⁆ L₂) (g : L₂ → L₁) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : L₂ →ₗ⁅R⁆ L₁ := { map_lie' := λ x y, calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←h₂ x, ←h₂ y], }, } ... = g (f ⁅g x, g y⁆) : by rw map_lie ... = ⁅g x, g y⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ h₂ } end lie_hom /-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/ structure lie_equiv (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ⁅R⁆ L' := (inv_fun : L' → L) (left_inv : function.left_inverse inv_fun to_lie_hom.to_fun) (right_inv : function.right_inverse inv_fun to_lie_hom.to_fun) attribute [nolint doc_blame] lie_equiv.to_lie_hom notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := lie_equiv R L L' namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] /-- Consider an equivalence of Lie algebras as a linear equivalence. -/ def to_linear_equiv (f : L₁ ≃ₗ⁅R⁆ L₂) : L₁ ≃ₗ[R] L₂ := { ..f.to_lie_hom, ..f } instance has_coe_to_lie_hom : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ →ₗ⁅R⁆ L₂) := ⟨to_lie_hom⟩ instance has_coe_to_linear_equiv : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ ≃ₗ[R] L₂) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ ≃ₗ⁅R⁆ L₂) (λ _, L₁ → L₂) := ⟨λ e, e.to_lie_hom.to_fun⟩ @[simp, norm_cast] lemma coe_to_lie_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ ≃ₗ[R] L₂) : L₁ → L₂) = e := rfl instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) := ⟨{ map_lie' := λ x y, by { change ((1 : L₁→ₗ[R] L₁) ⁅x, y⁆) = ⁅(1 : L₁→ₗ[R] L₁) x, (1 : L₁→ₗ[R] L₁) y⁆, simp, }, ..(1 : L₁ ≃ₗ[R] L₁)}⟩ @[simp] lemma one_apply (x : L₁) : (1 : (L₁ ≃ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩ /-- Lie algebra equivalences are reflexive. -/ @[refl] def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1 @[simp] lemma refl_apply (x : L₁) : (refl : L₁ ≃ₗ⁅R⁆ L₁) x = x := rfl /-- Lie algebra equivalences are symmetric. -/ @[symm] def symm (e : L₁ ≃ₗ⁅R⁆ L₂) : L₂ ≃ₗ⁅R⁆ L₁ := { ..lie_hom.inverse e.to_lie_hom e.inv_fun e.left_inv e.right_inv, ..e.to_linear_equiv.symm } @[simp] lemma symm_symm (e : L₁ ≃ₗ⁅R⁆ L₂) : e.symm.symm = e := by { rcases e with ⟨⟨⟨⟩⟩⟩, refl, } @[simp] lemma apply_symm_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply /-- Lie algebra equivalences are transitive. -/ @[trans] def trans (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ := { ..lie_hom.comp e₂.to_lie_hom e₁.to_lie_hom, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } @[simp] lemma trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma symm_trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₃) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl lemma bijective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.bijective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.bijective lemma injective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.injective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.injective lemma surjective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.surjective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.surjective end lie_equiv section lie_module_morphisms variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) (P : Type w₂) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [add_comm_group N] [add_comm_group P] variables [module R M] [module R N] [module R P] variables [lie_ring_module L M] [lie_ring_module L N] [lie_ring_module L P] variables [lie_module R L M] [lie_module R L N] [lie_module R L P] /-- A morphism of Lie algebra modules is a linear map which commutes with the action of the Lie algebra. -/ structure lie_module_hom extends M →ₗ[R] N := (map_lie' : ∀ {x : L} {m : M}, to_fun ⁅x, m⁆ = ⁅x, to_fun m⁆) attribute [nolint doc_blame] lie_module_hom.to_linear_map notation M ` →ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_hom R L M N namespace lie_module_hom variables {R L M N P} instance : has_coe (M →ₗ⁅R,L⁆ N) (M →ₗ[R] N) := ⟨lie_module_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M →ₗ⁅R,L⁆ N) (λ _, M → N) := ⟨λ f, f.to_linear_map.to_fun⟩ @[simp, norm_cast] lemma coe_to_linear_map (f : M →ₗ⁅R,L⁆ N) : ((f : M →ₗ[R] N) : M → N) = f := rfl @[simp] lemma map_smul (f : M →ₗ⁅R,L⁆ N) (c : R) (x : M) : f (c • x) = c • f x := linear_map.map_smul (f : M →ₗ[R] N) c x @[simp] lemma map_add (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : M →ₗ[R] N) x y @[simp] lemma map_sub (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : M →ₗ[R] N) x y @[simp] lemma map_neg (f : M →ₗ⁅R,L⁆ N) (x : M) : f (-x) = -(f x) := linear_map.map_neg (f : M →ₗ[R] N) x @[simp] lemma map_lie (f : M →ₗ⁅R,L⁆ N) (x : L) (m : M) : f ⁅x, m⁆ = ⁅x, f m⁆ := lie_module_hom.map_lie' f lemma map_lie₂ (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) (x : L) (m : M) (n : N) : ⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆ := by simp only [sub_add_cancel, map_lie, lie_hom.lie_apply] @[simp] lemma map_zero (f : M →ₗ⁅R,L⁆ N) : f 0 = 0 := linear_map.map_zero (f : M →ₗ[R] N) /-- The constant 0 map is a Lie module morphism. -/ instance : has_zero (M →ₗ⁅R,L⁆ N) := ⟨{ map_lie' := by simp, ..(0 : M →ₗ[R] N) }⟩ @[norm_cast, simp] lemma coe_zero : ((0 : M →ₗ⁅R,L⁆ N) : M → N) = 0 := rfl lemma zero_apply (m : M) : (0 : M →ₗ⁅R,L⁆ N) m = 0 := rfl /-- The identity map is a Lie module morphism. -/ instance : has_one (M →ₗ⁅R,L⁆ M) := ⟨{ map_lie' := by simp, ..(1 : M →ₗ[R] M) }⟩ instance : inhabited (M →ₗ⁅R,L⁆ N) := ⟨0⟩ lemma coe_injective : @function.injective (M →ₗ⁅R,L⁆ N) (M → N) coe_fn := by { rintros ⟨⟨f, _⟩⟩ ⟨⟨g, _⟩⟩ ⟨h⟩, congr, } @[ext] lemma ext {f g : M →ₗ⁅R,L⁆ N} (h : ∀ m, f m = g m) : f = g := coe_injective $ funext h lemma ext_iff {f g : M →ₗ⁅R,L⁆ N} : f = g ↔ ∀ m, f m = g m := ⟨by { rintro rfl m, refl, }, ext⟩ lemma congr_fun {f g : M →ₗ⁅R,L⁆ N} (h : f = g) (x : M) : f x = g x := h ▸ rfl @[simp] lemma mk_coe (f : M →ₗ⁅R,L⁆ N) (h) : (⟨f, h⟩ : M →ₗ⁅R,L⁆ N) = f := by { ext, refl, } @[simp] lemma coe_mk (f : M →ₗ[R] N) (h) : ((⟨f, h⟩ : M →ₗ⁅R,L⁆ N) : M → N) = f := by { ext, refl, } @[norm_cast, simp] lemma coe_linear_mk (f : M →ₗ[R] N) (h) : ((⟨f, h⟩ : M →ₗ⁅R,L⁆ N) : M →ₗ[R] N) = f := by { ext, refl, } /-- The composition of Lie module morphisms is a morphism. -/ def comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : M →ₗ⁅R,L⁆ P := { map_lie' := λ x m, by { change f (g ⁅x, m⁆) = ⁅x, f (g m)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) (m : M) : f.comp g m = f (g m) := rfl @[norm_cast, simp] lemma coe_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M → P) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M →ₗ[R] P) = (f : N →ₗ[R] P).comp (g : M →ₗ[R] N) := rfl /-- The inverse of a bijective morphism of Lie modules is a morphism of Lie modules. -/ def inverse (f : M →ₗ⁅R,L⁆ N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : N →ₗ⁅R,L⁆ M := { map_lie' := λ x n, calc g ⁅x, n⁆ = g ⁅x, f (g n)⁆ : by rw h₂ ... = g (f ⁅x, g n⁆) : by rw map_lie ... = ⁅x, g n⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ h₂ } instance : has_add (M →ₗ⁅R,L⁆ N) := { add := λ f g, { map_lie' := by simp, ..((f : M →ₗ[R] N) + (g : M →ₗ[R] N)) }, } instance : has_sub (M →ₗ⁅R,L⁆ N) := { sub := λ f g, { map_lie' := by simp, ..((f : M →ₗ[R] N) - (g : M →ₗ[R] N)) }, } instance : has_neg (M →ₗ⁅R,L⁆ N) := { neg := λ f, { map_lie' := by simp, ..(-(f : (M →ₗ[R] N))) }, } @[norm_cast, simp] lemma coe_add (f g : M →ₗ⁅R,L⁆ N) : ⇑(f + g) = f + g := rfl lemma add_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f + g) m = f m + g m := rfl @[norm_cast, simp] lemma coe_sub (f g : M →ₗ⁅R,L⁆ N) : ⇑(f - g) = f - g := rfl lemma sub_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f - g) m = f m - g m := rfl @[norm_cast, simp] lemma coe_neg (f : M →ₗ⁅R,L⁆ N) : ⇑(-f) = -f := rfl lemma neg_apply (f : M →ₗ⁅R,L⁆ N) (m : M) : (-f) m = -(f m) := rfl instance : add_comm_group (M →ₗ⁅R,L⁆ N) := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, nsmul := λ n f, { map_lie' := λ x m, by simp, ..(n • (f : M →ₗ[R] N)) }, nsmul_zero' := λ f, by { ext, simp, }, nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_nsmul], }, ..(coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub : add_comm_group (M →ₗ⁅R,L⁆ N)) } instance : has_scalar R (M →ₗ⁅R,L⁆ N) := { smul := λ t f, { map_lie' := by simp, ..(t • (f : M →ₗ[R] N)) }, } @[norm_cast, simp] lemma coe_smul (t : R) (f : M →ₗ⁅R,L⁆ N) : ⇑(t • f) = t • f := rfl lemma smul_apply (t : R) (f : M →ₗ⁅R,L⁆ N) (m : M) : (t • f) m = t • (f m) := rfl instance : module R (M →ₗ⁅R,L⁆ N) := function.injective.module R ⟨λ f, f.to_linear_map.to_fun, rfl, coe_add⟩ coe_injective coe_smul end lie_module_hom /-- An equivalence of Lie algebra modules is a linear equivalence which is also a morphism of Lie algebra modules. -/ structure lie_module_equiv extends M →ₗ⁅R,L⁆ N := (inv_fun : N → M) (left_inv : function.left_inverse inv_fun to_fun) (right_inv : function.right_inverse inv_fun to_fun) attribute [nolint doc_blame] lie_module_equiv.to_lie_module_hom notation M ` ≃ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_equiv R L M N namespace lie_module_equiv variables {R L M N P} /-- View an equivalence of Lie modules as a linear equivalence. -/ @[ancestor] def to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : M ≃ₗ[R] N := { ..e } /-- View an equivalence of Lie modules as a type level equivalence. -/ @[ancestor] def to_equiv (e : M ≃ₗ⁅R,L⁆ N) : M ≃ N := { ..e } instance has_coe_to_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ N) := ⟨to_equiv⟩ instance has_coe_to_lie_module_hom : has_coe (M ≃ₗ⁅R,L⁆ N) (M →ₗ⁅R,L⁆ N) := ⟨to_lie_module_hom⟩ instance has_coe_to_linear_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ₗ[R] N) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M ≃ₗ⁅R,L⁆ N) (λ _, M → N) := ⟨λ e, e.to_lie_module_hom.to_fun⟩ lemma injective (e : M ≃ₗ⁅R,L⁆ N) : function.injective e := e.to_equiv.injective @[simp] lemma coe_mk (f : M →ₗ⁅R,L⁆ N) (inv_fun h₁ h₂) : ((⟨f, inv_fun, h₁, h₂⟩ : M ≃ₗ⁅R,L⁆ N) : M → N) = f := rfl @[simp, norm_cast] lemma coe_to_lie_module_hom (e : M ≃ₗ⁅R,L⁆ N) : ((e : M →ₗ⁅R,L⁆ N) : M → N) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : ((e : M ≃ₗ[R] N) : M → N) = e := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ⁅R,L⁆ N) → M ≃ N) := λ e₁ e₂ h, begin rcases e₁ with ⟨⟨⟩⟩, rcases e₂ with ⟨⟨⟩⟩, have inj := equiv.mk.inj h, dsimp at inj, apply lie_module_equiv.mk.inj_eq.mpr, split, { congr, ext, rw inj.1 }, { exact inj.2 }, end @[ext] lemma ext (e₁ e₂ : M ≃ₗ⁅R,L⁆ N) (h : ∀ m, e₁ m = e₂ m) : e₁ = e₂ := to_equiv_injective (equiv.ext h) instance : has_one (M ≃ₗ⁅R,L⁆ M) := ⟨{ map_lie' := λ x m, rfl, ..(1 : M ≃ₗ[R] M) }⟩ @[simp] lemma one_apply (m : M) : (1 : (M ≃ₗ⁅R,L⁆ M)) m = m := rfl instance : inhabited (M ≃ₗ⁅R,L⁆ M) := ⟨1⟩ /-- Lie module equivalences are reflexive. -/ @[refl] def refl : M ≃ₗ⁅R,L⁆ M := 1 @[simp] lemma refl_apply (m : M) : (refl : M ≃ₗ⁅R,L⁆ M) m = m := rfl /-- Lie module equivalences are syemmtric. -/ @[symm] def symm (e : M ≃ₗ⁅R,L⁆ N) : N ≃ₗ⁅R,L⁆ M := { ..lie_module_hom.inverse e.to_lie_module_hom e.inv_fun e.left_inv e.right_inv, ..(e : M ≃ₗ[R] N).symm } @[simp] lemma apply_symm_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply @[simp] lemma symm_symm (e : M ≃ₗ⁅R,L⁆ N) : e.symm.symm = e := by { ext, apply_fun e.symm using e.symm.injective, simp, } /-- Lie module equivalences are transitive. -/ @[trans] def trans (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) : M ≃ₗ⁅R,L⁆ P := { ..lie_module_hom.comp e₂.to_lie_module_hom e₁.to_lie_module_hom, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } @[simp] lemma trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (m : M) : (e₁.trans e₂) m = e₂ (e₁ m) := rfl @[simp] lemma symm_trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (p : P) : (e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl end lie_module_equiv end lie_module_morphisms