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
02be07ec05831abd70a29730864fa695c2f95f83
097294e9b80f0d9893ac160b9c7219aa135b51b9
/assignments/final_exam.lean
3623e95d4aae1dd7900e58dc8f5bbb8efbd09f78
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
6,864
lean
/- CS2102 Spring 2020 Final Exam. You are to take this exam entirely on your own. You may not discuss it with anyone but the instructor and TAs. The exam has 6 qustions, some with several parts. Read the entire exam first to get a sense of the easy and hard parts. Do the easier parts first while letting your mind work in the background on the harder parts. Submit your completed exam on Collab. The exam is due no later than 5PM sharp ***EDT*** on May 8. Please set yourself a reminder. -/ /- 1. You know from our study of the Boolean satisfiability problem that there are 2^n possible combinations of Boolean values for n Boolean variables. Your task here is to give an English language (quasi-formal) proof of this fact *by induction*. To get started, let's make the property of natural numbers that is at issue clear by defining "P n" to be proposition that "the number of possible combinations of values for *n* Boolean variables is *2^n*." What your are to prove is the proposition that this is true for any value of n. That is, you are to prove ∀ n, P n. Mext, recall that a proof of a universal generalization (such as ∀ n, P n) *by induction* is based on the application of the *induction principle* for for the given data type. Here the data type is ℕ, and the induction rule for ℕ is as follows: ∀ {P : Prop}, P 0 → (∀ n', P n' → P (n' + 1)) → ∀ n, P n. Reading backwards, this says that if you want to prove ∀ n, P n, it will *suffice* to prove P 0 and ∀ n', P n' → P (n' + 1)). The reason is that you can then apply the rule to deduce that ∀ n, P n must be true. In other words, you can reduce the task of proving ∀ n, P n to the tasks of proving the two antecedents of this conclusion in the induction rule. This induction principles tells you exactly what needs to be done. We give you the start of a quasi-formal proof. You must complete it. -/ -- Answer /- Theorem: For any natural number, n, the number of combinations of values for n Boolean variables is 2^n. Proof: By induction. To prove ∀ n, P n, where P is defined to be the proposition, "the number of possible combinations of values for n Boolean variables is 2^n," it will suffice ... <the rest of your answer here>. -/ /- 2. Consider the following proposition. -/ def aProp := ∀ (α : Type), ∀ (Heavy Charmed: α → Prop), ∃ (a : α), Heavy a ∧ Charmed a → ∃ (a : α), Charmed a /- 2a. Give an English language rendition of this proposition. In plain English, what does it say? -/ /- 2b. Give a formal proof of it. -/ example : aProp := _ /- 2c. Give a quasi-formal, English-language proof of it. Try to be guided by your formal proof. Justify each step in your proof by naming the inference rule that you're using. -/ -- Your answer here /- 3. Consider the following proposition. -/ def aProp2 := ∀ (α : Type), ∀ (Heavy Charmed: α → Prop), (∃ (a : α), Heavy a ∨ Charmed a) → (∃ (a : α), Heavy a) ∨ (∃ (a : α), Charmed a) /- 3a. Give an English language rendition of this proposition. In plain English, what does it say? -/ /- 3b. Give a formal proof of it. -/ example : aProp2 := _ /- 3c. Give a quasi-formal, English-language proof of it. Try to be guided by your formal proof. Justify each step in your proof by naming the inference rule that you're using. -/ -- Your answer here /- 4. Formally specify the syntax and semantics of a language of *arithmetic* expressions that can include variables, where the meaning of an expression is (reduces to) a natural number. Hint: model your answer on our specification of the syntax and semantics of *propositional logic* expressions. -/ /- In this language, an interpretation will map variables to natural numbers rather than to Boolean values. We'll give you a start on a solution by defining (1) a type of variables that are distinguished from one another by a ℕ-valued index, (2) specifying the type of an interpretation, and (3) giving an example of an interpretation in which all variables have the value zero. -/ -- our variable type structure a_var : Type := mk :: (index : ℕ) -- friendly names for a few variables def X_var := a_var.mk 0 def Y_var := a_var.mk 1 def Z_var := a_var.mk 2 -- the type of an interpretation def interp := a_var → ℕ -- one possible interpretation, "all zero" def all_zero_interp : interp := λ v, 0 /- 4a. Define an interpretation in which X has value 3, Y has value 7, and Z has value 1, and all other variables have value 0. -/ def an_interp : interp := _ /- 4b. Define the syntax of your language to have the following kinds of expressions. - ℕ literal expression - ℕ variable expression - expression + expression - expression * expression Do this by defining an inductive type, aexp, the values of which are arithmetic expressions in our language. Call your constructors lit, var, add, and mul. When you succeed, the test expressions we give you should type check. -/ inductive aexp : Type -- fill in constructors here -- These expressions should type-check def X := aexp.var X_var def Y := aexp.var Y_var def Z := aexp.var Z_var def l6 := aexp.lit 6 def e1 := aexp.add X Y def e2 := aexp.mul X Z def e3 := aexp.mul e1 l6 /- 4c. Define a semantics for your language so that expressions evaluate to natural numbers as they would using the standard notions of addition and multiplication. Furthermore, literal expressions should evaluate to their natural numbers arguments, and variable expressions should evaluate the natural numbers according to an interpretation given to the evaluation function (call it aEval). Remember to put constructor expressions in parentheses when using pattern matching / destructuring. When you've succeeded, the test cases we've provided should all pass. -/ -- Your answer here def aEval : aexp → interp → ℕ -- fill in cases here -- Test cases that should pass when you've succeeded example : aEval X an_interp = 3 := rfl example : aEval Y an_interp = 7 := rfl example : aEval Z an_interp = 1 := rfl example : aEval l6 all_zero_interp = 6 := rfl example : aEval e1 all_zero_interp = 0 := rfl example : aEval e2 an_interp = 3 := rfl example : aEval e3 an_interp = 60 := rfl /- 5. Explain concisely but also precisely how a proof of a proposition, P, "by contradiction" would be carried out. Be sure to point out exactly where negation elimination is involved. Then explain concisely and precisely how a proof of a proposition, ¬ P, would be carried out. -/ /- 6. A simplish proof. Give a formal proof of the following proposition. Then explain briefly in English why the proposition must be true no matter what propositions P and Q are. -/ example : ∀ (P Q R : Prop), ¬ ((P ∧ ¬ Q) ∧ (Q ∧ ¬ R)) := _ -- Your explanation
14e1d739c9e90185a341760b4a50b4e69b11cd9c
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Server/FileSource.lean
1e7fe990f5781b672d504e27a0b6bb0adf591f54
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,429
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga -/ import Lean.Data.Lsp namespace Lean.Lsp class FileSource (α : Type) where fileSource : α → DocumentUri export FileSource (fileSource) instance : FileSource Location := ⟨fun l => l.uri⟩ instance : FileSource TextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource VersionedTextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentEdit := ⟨fun e => fileSource e.textDocument⟩ instance : FileSource TextDocumentItem := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentPositionParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidOpenTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidChangeTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidCloseTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource CompletionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource HoverParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DeclarationParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource TypeDefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource WaitForDiagnosticsParams := ⟨fun p => p.uri⟩ instance : FileSource DocumentHighlightParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DocumentSymbolParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainGoalParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainTermGoalParams where fileSource p := fileSource p.textDocument instance : FileSource RpcConnectParams where fileSource p := p.uri instance : FileSource RpcCallParams where fileSource p := fileSource p.textDocument instance : FileSource RpcReleaseParams where fileSource p := p.uri end Lean.Lsp
43441d1a0788fcbe5e02a2649c189b09d033b3ee
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/convex/topology.lean
a74689f192bc3fd2f1f76b99ed47483491c438e5
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
8,636
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import analysis.convex.basic import analysis.normed_space.finite_dimension import topology.path_connected /-! # Topological and metric properties of convex sets We prove the following facts: * `convex.interior` : interior of a convex set is convex; * `convex.closure` : closure of a convex set is convex; * `set.finite.compact_convex_hull` : convex hull of a finite set is compact; * `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed; * `convex_on_dist` : distance to a fixed point is convex on any convex set; * `convex_hull_ediam`, `convex_hull_diam` : convex hull of a set has the same (e)metric diameter as the original set; * `bounded_convex_hull` : convex hull of a set is bounded if and only if the original set is bounded. * `bounded_std_simplex`, `is_closed_std_simplex`, `compact_std_simplex`: topological properties of the standard simplex; -/ variables {ι : Type*} {E : Type*} open set lemma real.convex_iff_is_preconnected {s : set ℝ} : convex s ↔ is_preconnected s := real.convex_iff_ord_connected.trans is_preconnected_iff_ord_connected.symm alias real.convex_iff_is_preconnected ↔ convex.is_preconnected is_preconnected.convex /-! ### Standard simplex -/ section std_simplex variables [fintype ι] /-- Every vector in `std_simplex ι` has `max`-norm at most `1`. -/ lemma std_simplex_subset_closed_ball : std_simplex ι ⊆ metric.closed_ball 0 1 := begin assume f hf, rw [metric.mem_closed_ball, dist_zero_right], refine (nnreal.coe_one ▸ nnreal.coe_le_coe.2 $ finset.sup_le $ λ x hx, _), change abs (f x) ≤ 1, rw [abs_of_nonneg $ hf.1 x], exact (mem_Icc_of_mem_std_simplex hf x).2 end variable (ι) /-- `std_simplex ι` is bounded. -/ lemma bounded_std_simplex : metric.bounded (std_simplex ι) := (metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩ /-- `std_simplex ι` is closed. -/ lemma is_closed_std_simplex : is_closed (std_simplex ι) := (std_simplex_eq_inter ι).symm ▸ is_closed_inter (is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i)) (is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const) /-- `std_simplex ι` is compact. -/ lemma compact_std_simplex : is_compact (std_simplex ι) := metric.compact_iff_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩ end std_simplex /-! ### Topological vector space -/ section topological_vector_space variables [add_comm_group E] [vector_space ℝ E] [topological_space E] [topological_add_group E] [topological_vector_space ℝ E] /-- In a topological vector space, the interior of a convex set is convex. -/ lemma convex.interior {s : set E} (hs : convex s) : convex (interior s) := convex_iff_pointwise_add_subset.mpr $ λ a b ha hb hab, have h : is_open (a • interior s + b • interior s), from or.elim (classical.em (a = 0)) (λ heq, have hne : b ≠ 0, by { rw [heq, zero_add] at hab, rw hab, exact one_ne_zero }, by { rw ← image_smul, exact (is_open_map_smul_of_ne_zero hne _ is_open_interior).add_left } ) (λ hne, by { rw ← image_smul, exact (is_open_map_smul_of_ne_zero hne _ is_open_interior).add_right }), (subset_interior_iff_subset_of_open h).mpr $ subset.trans (by { simp only [← image_smul], apply add_subset_add; exact image_subset _ interior_subset }) (convex_iff_pointwise_add_subset.mp hs ha hb hab) /-- In a topological vector space, the closure of a convex set is convex. -/ lemma convex.closure {s : set E} (hs : convex s) : convex (closure s) := λ x y hx hy a b ha hb hab, let f : E → E → E := λ x' y', a • x' + b • y' in have hf : continuous (λ p : E × E, f p.1 p.2), from (continuous_const.smul continuous_fst).add (continuous_const.smul continuous_snd), show f x y ∈ closure s, from mem_closure_of_continuous2 hf hx hy (λ x' hx' y' hy', subset_closure (hs hx' hy' ha hb hab)) /-- Convex hull of a finite set is compact. -/ lemma set.finite.compact_convex_hull {s : set E} (hs : finite s) : is_compact (convex_hull s) := begin rw [hs.convex_hull_eq_image], apply (compact_std_simplex _).image, haveI := hs.fintype, apply linear_map.continuous_on_pi end /-- Convex hull of a finite set is closed. -/ lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : finite s) : is_closed (convex_hull s) := hs.compact_convex_hull.is_closed end topological_vector_space /-! ### Normed vector space -/ section normed_space variables [normed_group E] [normed_space ℝ E] lemma convex_on_dist (z : E) (s : set E) (hs : convex s) : convex_on s (λz', dist z' z) := and.intro hs $ assume x y hx hy a b ha hb hab, calc dist (a • x + b • y) z = ∥ (a • x + b • y) - (a + b) • z ∥ : by rw [hab, one_smul, normed_group.dist_eq] ... = ∥a • (x - z) + b • (y - z)∥ : by rw [add_smul, smul_sub, smul_sub, sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, neg_add, ←add_assoc, add_assoc (a • x), add_comm (b • y)]; simp only [add_assoc] ... ≤ ∥a • (x - z)∥ + ∥b • (y - z)∥ : norm_add_le (a • (x - z)) (b • (y - z)) ... = a * dist x z + b * dist y z : by simp [norm_smul, normed_group.dist_eq, real.norm_eq_abs, abs_of_nonneg ha, abs_of_nonneg hb] lemma convex_ball (a : E) (r : ℝ) : convex (metric.ball a r) := by simpa only [metric.ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_lt r lemma convex_closed_ball (a : E) (r : ℝ) : convex (metric.closed_ball a r) := by simpa only [metric.closed_ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_le r /-- Given a point `x` in the convex hull of `s` and a point `y`, there exists a point of `s` at distance at least `dist x y` from `y`. -/ lemma convex_hull_exists_dist_ge {s : set E} {x : E} (hx : x ∈ convex_hull s) (y : E) : ∃ x' ∈ s, dist x y ≤ dist x' y := (convex_on_dist y _ (convex_convex_hull _)).exists_ge_of_mem_convex_hull hx /-- Given a point `x` in the convex hull of `s` and a point `y` in the convex hull of `t`, there exist points `x' ∈ s` and `y' ∈ t` at distance at least `dist x y`. -/ lemma convex_hull_exists_dist_ge2 {s t : set E} {x y : E} (hx : x ∈ convex_hull s) (hy : y ∈ convex_hull t) : ∃ (x' ∈ s) (y' ∈ t), dist x y ≤ dist x' y' := begin rcases convex_hull_exists_dist_ge hx y with ⟨x', hx', Hx'⟩, rcases convex_hull_exists_dist_ge hy x' with ⟨y', hy', Hy'⟩, use [x', hx', y', hy'], exact le_trans Hx' (dist_comm y x' ▸ dist_comm y' x' ▸ Hy') end /-- Emetric diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_ediam (s : set E) : emetric.diam (convex_hull s) = emetric.diam s := begin refine le_antisymm (emetric.diam_le_of_forall_edist_le $ λ x hx y hy, _) (emetric.diam_mono $ subset_convex_hull s), rcases convex_hull_exists_dist_ge2 hx hy with ⟨x', hx', y', hy', H⟩, rw edist_dist, apply le_trans (ennreal.of_real_le_of_real H), rw ← edist_dist, exact emetric.edist_le_diam_of_mem hx' hy' end /-- Diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_diam (s : set E) : metric.diam (convex_hull s) = metric.diam s := by simp only [metric.diam, convex_hull_ediam] /-- Convex hull of `s` is bounded if and only if `s` is bounded. -/ @[simp] lemma bounded_convex_hull {s : set E} : metric.bounded (convex_hull s) ↔ metric.bounded s := by simp only [metric.bounded_iff_ediam_ne_top, convex_hull_ediam] lemma convex.is_path_connected {s : set E} (hconv : convex s) (hne : s.nonempty) : is_path_connected s := begin refine is_path_connected_iff.mpr ⟨hne, _⟩, intros x y x_in y_in, let f := λ θ : ℝ, x + θ • (y - x), have hf : continuous f, by continuity, have h₀ : f 0 = x, by simp [f], have h₁ : f 1 = y, by { dsimp [f], rw one_smul, abel }, have H := hconv.segment_subset x_in y_in, rw segment_eq_image' at H, exact joined_in.of_line hf.continuous_on h₀ h₁ H end @[priority 100] instance normed_space.path_connected : path_connected_space E := path_connected_space_iff_univ.mpr $ convex_univ.is_path_connected ⟨(0 : E), trivial⟩ @[priority 100] instance normed_space.loc_path_connected : loc_path_connected_space E := loc_path_connected_of_bases (λ x, metric.nhds_basis_ball) (λ x r r_pos, (convex_ball x r).is_path_connected $ by simp [r_pos]) end normed_space
46faf7184462e188f1a3b5ffff667fb44d16a929
17d3c61bf162bf88be633867ed4cb201378a8769
/library/tools/super/prover_state.lean
0ecc8202c8c9fc787299ae01775dacd798bec3de
[ "Apache-2.0" ]
permissive
u20024804/lean
11def01468fb4796fb0da76015855adceac7e311
d315e424ff17faf6fe096a0a1407b70193009726
refs/heads/master
1,611,388,567,561
1,485,836,506,000
1,485,836,625,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,612
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .lpo .cdcl_solver open tactic monad expr namespace super structure score := (priority : ℕ) (in_sos : bool) (cost : ℕ) (age : ℕ) namespace score def prio.immediate : ℕ := 0 def prio.default : ℕ := 1 def prio.never : ℕ := 2 def sched_default (sc : score) : score := { sc with priority := prio.default } def sched_now (sc : score) : score := { sc with priority := prio.immediate } def inc_cost (sc : score) (n : ℕ) : score := { sc with cost := sc^.cost + n } def min (a b : score) : score := { priority := nat.min a^.priority b^.priority, in_sos := a^.in_sos && b^.in_sos, cost := nat.min a^.cost b^.cost, age := nat.min a^.age b^.age } def combine (a b : score) : score := { priority := nat.max a^.priority b^.priority, in_sos := a^.in_sos && b^.in_sos, cost := a^.cost + b^.cost, age := nat.max a^.age b^.age } end score namespace score meta instance : has_to_string score := ⟨λe, "[" ++ to_string e^.priority ++ "," ++ to_string e^.cost ++ "," ++ to_string e^.age ++ ",sos=" ++ to_string e^.in_sos ++ "]"⟩ end score def clause_id := ℕ namespace clause_id def to_nat (id : clause_id) : ℕ := id instance : decidable_eq clause_id := nat.decidable_eq instance : has_ordering clause_id := nat.has_ordering end clause_id meta structure derived_clause := (id : clause_id) (c : clause) (selected : list ℕ) (assertions : list expr) (sc : score) namespace derived_clause meta instance : has_to_tactic_format derived_clause := ⟨λc, do prf_fmt ← pp c^.c^.proof, c_fmt ← pp c^.c, ass_fmt ← pp (c^.assertions^.for (λa, a^.local_type)), return $ to_string c^.sc ++ " " ++ prf_fmt ++ " " ++ c_fmt ++ " <- " ++ ass_fmt ++ " (selected: " ++ to_fmt c^.selected ++ ")" ⟩ meta def clause_with_assertions (ac : derived_clause) : clause := ac^.c^.close_constn ac^.assertions end derived_clause meta structure locked_clause := (dc : derived_clause) (reasons : list (list expr)) namespace locked_clause meta instance : has_to_tactic_format locked_clause := ⟨λc, do c_fmt ← pp c^.dc, reasons_fmt ← pp (c^.reasons^.for (λr, r^.for (λa, a^.local_type))), return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")" ⟩ end locked_clause meta structure prover_state := (active : rb_map clause_id derived_clause) (passive : rb_map clause_id derived_clause) (newly_derived : list derived_clause) (prec : list expr) (locked : list locked_clause) (local_false : expr) (sat_solver : cdcl.state) (current_model : rb_map expr bool) (sat_hyps : rb_map expr (expr × expr)) (needs_sat_run : bool) (clause_counter : nat) open prover_state private meta def join_with_nl : list format → format := list.foldl (λx y, x ++ format.line ++ y) format.nil private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do active_fmts ← mapm pp $ rb_map.values s^.active, passive_fmts ← mapm pp $ rb_map.values s^.passive, new_fmts ← mapm pp s^.newly_derived, locked_fmts ← mapm pp s^.locked, sat_fmts ← mapm pp s^.sat_solver^.clauses, sat_model_fmts ← for s^.current_model^.to_list (λx, if x.2 = tt then pp x.1 else pp (not_ x.1)), prec_fmts ← mapm pp s^.prec, return (join_with_nl ([to_fmt "active:"] ++ map (append (to_fmt " ")) active_fmts ++ [to_fmt "passive:"] ++ map (append (to_fmt " ")) passive_fmts ++ [to_fmt "new:"] ++ map (append (to_fmt " ")) new_fmts ++ [to_fmt "locked:"] ++ map (append (to_fmt " ")) locked_fmts ++ [to_fmt "sat formulas:"] ++ map (append (to_fmt " ")) sat_fmts ++ [to_fmt "sat model:"] ++ map (append (to_fmt " ")) sat_model_fmts ++ [to_fmt "precedence order: " ++ to_fmt prec_fmts])) meta instance : has_to_tactic_format prover_state := ⟨prover_state_tactic_fmt⟩ meta def prover := state_t prover_state tactic namespace prover meta instance : monad prover := state_t.monad _ _ meta instance : has_monad_lift tactic prover := monad.monad_transformer_lift (state_t prover_state) tactic meta instance (α : Type) : has_coe (tactic α) (prover α) := ⟨monad.monad_lift⟩ meta def fail {α β : Type} [has_to_format β] (msg : β) : prover α := fail msg meta def orelse (A : Type) (p1 p2 : prover A) : prover A := take state, p1 state <|> p2 state meta instance : alternative prover := { monad_is_applicative prover with failure := λα, fail "failed", orelse := orelse } end prover meta def selection_strategy := derived_clause → prover derived_clause meta def get_active : prover (rb_map clause_id derived_clause) := do state ← state_t.read, return state^.active meta def add_active (a : derived_clause) : prover unit := do state ← state_t.read, state_t.write { state with active := state^.active^.insert a^.id a } meta def get_passive : prover (rb_map clause_id derived_clause) := lift passive state_t.read meta def get_precedence : prover (list expr) := do state ← state_t.read, return state^.prec meta def get_term_order : prover (expr → expr → bool) := do state ← state_t.read, return $ mk_lpo (map name_of_funsym state^.prec) private meta def set_precedence (new_prec : list expr) : prover unit := do state ← state_t.read, state_t.write { state with prec := new_prec } meta def register_consts_in_precedence (consts : list expr) := do p ← get_precedence, p_set ← return (rb_map.set_of_list (map name_of_funsym p)), new_syms ← return $ list.filter (λc, ¬p_set^.contains (name_of_funsym c)) consts, set_precedence (new_syms ++ p) meta def in_sat_solver {A} (cmd : cdcl.solver A) : prover A := do state ← state_t.read, result ← cmd state^.sat_solver, state_t.write { state with sat_solver := result.2 }, return result.1 meta def collect_ass_hyps (c : clause) : prover (list expr) := let lcs := contained_lconsts c^.proof in do st ← state_t.read, return (do hs ← st^.sat_hyps^.values, h ← [hs.1, hs.2], guard $ lcs^.contains h^.local_uniq_name, [h]) meta def get_clause_count : prover ℕ := do s ← state_t.read, return s^.clause_counter meta def get_new_cls_id : prover clause_id := do state ← state_t.read, state_t.write { state with clause_counter := state^.clause_counter + 1 }, return state^.clause_counter meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do ass ← collect_ass_hyps c, id ← get_new_cls_id, return { id := id, c := c, selected := [], assertions := ass, sc := sc } meta def add_inferred (c : derived_clause) : prover unit := do c' ← c^.c^.normalize, c' ← return { c with c := c' }, register_consts_in_precedence (contained_funsyms c'^.c^.type)^.values, state ← state_t.read, state_t.write { state with newly_derived := c' :: state^.newly_derived } -- FIXME: what if we've seen the variable before, but with a weaker score? meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit := do st ← state_t.read, if st^.sat_hyps^.contains v then return () else do hpv ← mk_local_def `h v, hnv ← mk_local_def `hn $ imp v st^.local_false, state_t.modify $ λst, { st with sat_hyps := st^.sat_hyps^.insert v (hpv, hnv) }, in_sat_solver $ cdcl.mk_var_core v suggested_ph, match v with | (pi _ _ _ _) := do c ← clause.of_proof st^.local_false hpv, mk_derived c suggested_ev >>= add_inferred | _ := do cp ← clause.of_proof st^.local_false hpv, mk_derived cp suggested_ev >>= add_inferred, cn ← clause.of_proof st^.local_false hnv, mk_derived cn suggested_ev >>= add_inferred end meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) := flip monad.lift state_t.read $ λst, match st^.sat_hyps^.find v with | some (hp, hn) := some $ if ph then hp else hn | none := none end meta def get_sat_hyp (v : expr) (ph : bool) : prover expr := do hyp_opt ← get_sat_hyp_core v ph, match hyp_opt with | some hyp := return hyp | none := fail $ "unknown sat variable: " ++ v^.to_string end meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do c ← c^.distinct, already_added ← flip monad.lift state_t.read $ λst, decidable.to_bool $ c^.type ∈ st^.sat_solver^.clauses^.for (λd, d^.type), if already_added then return () else do for c^.get_lits $ λl, mk_sat_var l^.formula l^.is_neg suggested_ev, in_sat_solver $ cdcl.mk_clause c, state_t.modify $ λst, { st with needs_sat_run := tt } meta def sat_eval_lit (v : expr) (pol : bool) : prover bool := do v_st ← flip monad.lift state_t.read $ λst, st^.current_model^.find v, match v_st with | some ph := return $ if pol then ph else bnot ph | none := return tt end meta def sat_eval_assertion (assertion : expr) : prover bool := do lf ← flip monad.lift state_t.read $ λst, st^.local_false, match is_local_not lf assertion^.local_type with | some v := sat_eval_lit v ff | none := sat_eval_lit assertion^.local_type tt end meta def sat_eval_assertions : list expr → prover bool | (a::ass) := do v_a ← sat_eval_assertion a, if v_a then sat_eval_assertions ass else return ff | [] := return tt private meta def intern_clause (c : derived_clause) : prover derived_clause := do hyp_name ← get_unused_name (mk_simple_name $ "clause_" ++ to_string c^.id^.to_nat) none, c' ← return $ c^.c^.close_constn c^.assertions, assertv hyp_name c'^.type c'^.proof, proof' ← get_local hyp_name, type ← infer_type proof', -- FIXME: otherwise "" return { c with c := { (c^.c : clause) with proof := app_of_list proof' c^.assertions } } meta def register_as_passive (c : derived_clause) : prover unit := do c ← intern_clause c, ass_v ← sat_eval_assertions c^.assertions, if c^.c^.num_quants = 0 ∧ c^.c^.num_lits = 0 then add_sat_clause c^.clause_with_assertions c^.sc else if ¬ass_v then do state_t.modify $ λst, { st with locked := ⟨c, []⟩ :: st^.locked } else do state_t.modify $ λst, { st with passive := st^.passive^.insert c^.id c } meta def remove_passive (id : clause_id) : prover unit := do state ← state_t.read, state_t.write { state with passive := state^.passive^.erase id } meta def move_locked_to_passive : prover unit := do locked ← flip monad.lift state_t.read (λst, st^.locked), new_locked ← flip filter locked (λlc, do reason_vals ← mapm sat_eval_assertions lc^.reasons, c_val ← sat_eval_assertions lc^.dc^.assertions, if reason_vals^.for_all (λr, r = ff) ∧ c_val then do state_t.modify $ λst, { st with passive := st^.passive^.insert lc^.dc^.id lc^.dc }, return ff else return tt ), state_t.modify $ λst, { st with locked := new_locked } meta def move_active_to_locked : prover unit := do active ← get_active, for' active^.values $ λac, do c_val ← sat_eval_assertions ac^.assertions, if ¬c_val then do state_t.modify $ λst, { st with active := st^.active^.erase ac^.id, locked := ⟨ac, []⟩ :: st^.locked } else return () meta def move_passive_to_locked : prover unit := do passive ← flip monad.lift state_t.read $ λst, st^.passive, for' passive^.to_list $ λpc, do c_val ← sat_eval_assertions pc.2^.assertions, if ¬c_val then do state_t.modify $ λst, { st with passive := st^.passive^.erase pc.1, locked := ⟨pc.2, []⟩ :: st^.locked } else return () def super_cc_config : cc_config := { em := ff } meta def do_sat_run : prover (option expr) := do sat_result ← in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic $ using_smt $ return ()), state_t.modify $ λst, { st with needs_sat_run := ff }, old_model ← lift prover_state.current_model state_t.read, match sat_result with | (cdcl.result.unsat proof) := return (some proof) | (cdcl.result.sat new_model) := do state_t.modify $ λst, { st with current_model := new_model }, move_locked_to_passive, move_active_to_locked, move_passive_to_locked, return none end meta def take_newly_derived : prover (list derived_clause) := do state ← state_t.read, state_t.write { state with newly_derived := [] }, return state^.newly_derived meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do when (not $ parents^.for_all $ λp, p^.id ≠ id) (fail "clause is redundant because of itself"), red ← flip monad.lift state_t.read (λst, st^.active^.find id), match red with | none := return () | some red := do let reasons := parents^.for (λp, p^.assertions), assertion := red^.assertions in if reasons^.for_all $ λr, r^.subset_of assertion then do state_t.modify $ λst, { st with active := st^.active^.erase id } else do state_t.modify $ λst, { st with active := st^.active^.erase id, locked := ⟨red, reasons⟩ :: st^.locked } end meta def inference := derived_clause → prover unit meta structure inf_decl := (prio : ℕ) (inf : inference) meta def inf_attr : user_attribute := ⟨ `super.inf, "inference for the super prover" ⟩ run_command attribute.register `super.inf_attr meta def seq_inferences : list inference → inference | [] := λgiven, return () | (inf::infs) := λgiven, do inf given, now_active ← get_active, if rb_map.contains now_active given^.id then seq_inferences infs given else return () meta def simp_inference (simpl : derived_clause → prover (option clause)) : inference := λgiven, do maybe_simpld ← simpl given, match maybe_simpld with | some simpld := do derived_simpld ← mk_derived simpld given^.sc^.sched_now, add_inferred derived_simpld, remove_redundant given^.id [] | none := return () end meta def preprocessing_rule (f : list derived_clause → prover (list derived_clause)) : prover unit := do state ← state_t.read, newly_derived' ← f state^.newly_derived, state' ← state_t.read, state_t.write { state' with newly_derived := newly_derived' } meta def clause_selection_strategy := ℕ → prover clause_id namespace prover_state meta def empty (local_false : expr) : prover_state := { active := rb_map.mk _ _, passive := rb_map.mk _ _, newly_derived := [], prec := [], clause_counter := 0, local_false := local_false, locked := [], sat_solver := cdcl.state.initial local_false, current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff } meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do after_setup ← for' clauses (λc, let in_sos := decidable.to_bool $ ((contained_lconsts c^.proof)^.erase local_false^.local_uniq_name)^.size = 0 in do mk_derived c { priority := score.prio.immediate, in_sos := in_sos, age := 0, cost := 0 } >>= add_inferred ) $ empty local_false, return after_setup.2 end prover_state meta def inf_score (add_cost : ℕ) (scores : list score) : prover score := do age ← get_clause_count, return $ list.foldl score.combine { priority := score.prio.default, in_sos := tt, age := age, cost := add_cost } scores meta def inf_if_successful (add_cost : ℕ) (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, for' inferred $ λc, inf_score add_cost [parent^.sc] >>= mk_derived c >>= add_inferred) <|> return () meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, for' inferred $ λc, mk_derived c parent^.sc^.sched_now >>= add_inferred, remove_redundant parent^.id []) <|> return () end super
520c5c53226c49e8d2e19615aecde19d761f0ba8
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/projet_A2/action_Idem_X.lean
639ce82cfa54490b09bfdc6cc3f93e0f7fdbc485
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
1,616
lean
import .X import .Idem import group_theory.group_action open X namespace idem_action_X def mul_action' (R : Type)[comm_ring R] : Idem(R) → X(R) → X(R) := λ g η, begin exact { x := g.e * (η.x-η.y) + η .y, y := η.x + g.e * (η .y -η.x) , inv := η.inv, certif := begin have h : g.e * (η.x - η.y) + η.y - (η.x + g.e * (η.y - η.x)) = g.e * (η.x - η.y) - (1-g.e) * (η.x - η.y), ring, rw h, rw ← Idem.Idem.calculus.square_idem, exact η.certif, end } end instance (R : Type)[comm_ring R] : has_scalar (Idem(R)) (X(R)) := ⟨mul_action' R⟩ variables (R :Type)[comm_ring R] lemma mul_action_comp_x (g : Idem R) (η : X R): (g • η).x = g.e * (η.x-η.y) + η.y := rfl lemma mul_action_comp_y (g : Idem R) (η : X R): (g • η).y = η.x + g.e * (η .y -η.x) := rfl lemma mul_action_comp_inv (g : Idem R) (η : X R): (g • η).inv = η.inv := rfl --- Ecrire un revriter ! open Idem open X meta def idem_ring : tactic unit := `[simp only [one_e, mul_action_comp_x,mul_action_comp_y, e_comp], ring] run_cmd add_interactive [`idem_ring] def one_smul' (η : X R) : (1 : Idem R) • η = η := begin ext ; idem_ring, end def mul_smul' (g1 g2 : Idem R) (η : X(R)) : (g1 * g2) • η = g1 • g2 • η := begin ext ; idem_ring, end instance (R : Type)[comm_ring R]: mul_action (Idem R) (X(R)) := ⟨ one_smul' R, mul_smul' R⟩ open mul_action def A := orbit_rel (Idem (R)) (X(R)) #check (A(R)).r end idem_action_X
385a2249456e911220e9a68ccda29ccde32d925b
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/zmod/quadratic_reciprocity.lean
22815fa1ac89ba3a329af1a319b84cf3838bc191
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
23,168
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.finite data.zmod.basic data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and `exists_pow_two_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and `exists_pow_two_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmodp namespace zmodp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : ℕ} (hp : nat.prime p) {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (∃ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (λ h, by resetI; subst h; revert x; exact dec_trivial) (λ hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], λ hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.two_le dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a ≠ 0) : (∃ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y ≠ 0, from λ h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), λ h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmodp p hp, y ^ 2 = -1) ↔ p % 4 ≠ 3 := have (-1 : zmodp p hp) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, hp.eq_two_or_odd.elim (λ hp, by resetI; subst hp; exact dec_trivial) (λ hp1, (mod_two_eq_zero_or_one (p / 2)).elim (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_zero, eq_self_iff_true, true_iff], assume h, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, h] at hp2, exact absurd hp2 dec_trivial, end) (λ hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_one, iff_false_intro (zmodp.ne_neg_self hp hp1 one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at hp2, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp1, have hp4 : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp1 hp2, revert hp4, generalize : p % 4 = k, revert k, exact dec_trivial end)) lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (λ h, by revert a ha; resetI; subst h; exact dec_trivial) (λ hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : ℕ} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_Ico_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom _ (coe : units (zmodp p hp) → zmodp p hp), ← prod_hom _ (coe : ℕ → zmodp p hp)], exact eq.symm (prod_bij (λ a _, (a : zmodp p hp).1) (λ a ha, Ico.mem.2 ⟨nat.pos_of_ne_zero (λ h, units.coe_ne_zero a (fin.eq_of_veq h)), by rw [← succ_sub hp.pos, succ_sub_one]; exact (a : zmodp p hp).2⟩) (λ a _, by simp) (λ _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (λ b hb, have b ≠ 0 ∧ b < p, by rwa [Ico.mem, nat.succ_le_iff, ← succ_sub hp.pos, succ_sub_one, nat.pos_iff_ne_zero] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) ≠ 0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_Ico_one_prime {p : ℕ} (hp : nat.prime p) : (Ico 1 p).prod (λ x, (x : zmodp p hp)) = -1 := by conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom _ (coe : ℕ → zmodp p hp), finset.prod_Ico_id_eq_fact, wilsons_lemma] end zmodp /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id {p : ℕ} (hp : p.prime) (a : zmodp p hp) (hpa : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hsurj : ∀ b : ℕ , b ∈ Ico 1 (p / 2).succ → ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmodp p hp).val_min_abs.nat_abs, from λ b hb, ⟨(b / a : zmodp p hp).val_min_abs.nat_abs, Ico.mem.2 ⟨nat.pos_of_ne_zero $ by simp [div_eq_mul_inv, hpa, zmodp.eq_zero_iff_dvd_nat hp b, hpe hb], nat.lt_succ_of_le $ zmodp.nat_abs_val_min_abs_le _⟩, begin rw [zmodp.cast_nat_abs_val_min_abs], split_ifs, { erw [mul_div_cancel' _ hpa, zmodp.val_min_abs, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hpa, zmod.nat_abs_val_min_abs_neg, zmod.val_min_abs, zmodp.val_cast_of_lt hp (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] }, end⟩, have hmem : ∀ x : ℕ, x ∈ Ico 1 (p / 2).succ → (a * x : zmodp p hp).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, from λ x hx, by simp [hpa, zmodp.eq_zero_iff_dvd_nat hp x, hpe hx, lt_succ_iff, succ_le_iff, nat.pos_iff_ne_zero, zmodp.nat_abs_val_min_abs_le _], multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmodp p hp).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj private lemma gauss_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) * (p / 2).fact : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact := calc (a ^ (p / 2) * (p / 2).fact : zmodp p hp) = (Ico 1 (p / 2).succ).prod (λ x, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact, prod_const, Ico.card, succ_sub_one]; simp ... = (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val) : by simp ... = (Ico 1 (p / 2).succ).prod (λ x, (if (a * x : zmodp p hp).val ≤ p / 2 then 1 else -1) * (a * x : zmodp p hp).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [zmodp.cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs) : have (Ico 1 (p / 2).succ).prod (λ x, if (a * x : zmodp p hp).val ≤ p / 2 then (1 : zmodp p hp) else -1) = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).prod (λ _, -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmodp p hp).val ≤ p / 2)).card * (p / 2).fact : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp a hpa, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact] private lemma gauss_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hpa : (a : zmodp p hp) ≠ 0) : (a^(p / 2) : zmodp p hp) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := (domain.mul_right_inj (show ((p / 2).fact : zmodp p hp) ≠ 0, by rw [ne.def, zmodp.eq_zero_iff_dvd_nat, hp.dvd_fact, not_le]; exact nat.div_lt_self hp.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ _ hp2 hpa private lemma eisenstein_lemma_aux₁ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (hap : (a : zmodp p hp) ≠ 0) : (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card + (Ico 1 (p / 2).succ).sum (λ x, x) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 hp2, calc (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = (((Ico 1 (p / 2).succ).sum (λ x, (a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = ((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) : by simp only [zmodp.val_cast_nat]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2] ... = _ : congr_arg2 (+) (calc (((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmodp p hp).val) : ℕ) : zmod 2) = (Ico 1 (p / 2).succ).sum (λ x, ((((a * x : zmodp p hp).val_min_abs + (if (a * x : zmodp p hp).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2)) : by simp only [(zmodp.val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card + (((Ico 1 (p / 2).succ).sum (λ x, (a * x : zmodp p hp).val_min_abs.nat_abs)) : ℕ) : by simp [add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast] ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id hp _ hap, ← finset.sum_eq_multiset_sum]; simp [sum_nat_cast]) rfl private lemma eisenstein_lemma_aux₂ {p : ℕ} (hp : p.prime) (hp2 : p % 2 = 1) {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmodp p hp) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmodp p hp).val))).card ≡ (Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from zmod.eq_iff_modeq_nat.2 ha2, (@zmod.eq_iff_modeq_nat 2 _ _).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast, add_neg_eq_iff_eq_add.symm, zmod.neg_eq_self_mod_two] using eq.symm (eisenstein_lemma_aux₁ hp hp2 hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _$ finset.ext.2 $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integers point in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext] else calc (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (Ico 1 (p / 2).succ).sum (λ a, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card) : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul {p q : ℕ} (hp : p.prime) (hq0 : (q : zmodp p hp) ≠ 0) : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) + (Ico 1 (q / 2).succ).sum (λ a, (a * p) / q) = (p / 2) * (q / 2) := have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), from disjoint_filter.2 $ λ x hx hpq hqp, have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp [*, nat.lt_succ_iff] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), begin have : (x.1 : zmodp p hp) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmodp p hp) (le_antisymm hpq hqp) }, rw [fin.eq_iff_veq, zmodp.val_cast_of_lt hp hxp, zmodp.zero_val] at this, simp * at * end, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext.2 $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto, by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product]; simp variables {p q : ℕ} (hp : nat.prime p) (hq : nat.prime q) namespace zmodp def legendre_sym (a p : ℕ) (hp : nat.prime p) : ℤ := if (a : zmodp p hp) = 0 then 0 else if ∃ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.two_le (succ_pos 1))] else (nat.prime.eq_two_or_odd hp).elim (λ hp2, begin resetI; subst hp2, suffices : ∀ a : zmodp 2 nat.prime_two, (((ite (a = 0) 0 (ite (∃ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : ℤ) : zmodp 2 nat.prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (λ hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) ≠ 1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : ℕ) (hp : nat.prime p) (ha : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} (hp1 : p % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card := have (legendre_sym a p hp : zmodp p hp) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card : ℤ) : zmodp p hp), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ hp hp1 ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a hp ha0; cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmodp p hp).val)).card; simp [*, zmodp.ne_neg_self hp hp1 one_ne_zero, (zmodp.ne_neg_self hp hp1 one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = 1 ↔ (∃ b : zmodp p hp, b ^ 2 = a) := by rw [legendre_sym]; split_ifs; finish lemma eisenstein_lemma (hp1 : p % 2 = 1) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmodp p hp) ≠ 0) : legendre_sym a p hp = (-1)^(Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma hp hp1 ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ hp hp1 ha1 ha0] theorem quadratic_reciprocity (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p ≠ q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmodp q hq) ≠ 0, from zmodp.prime_ne_zero _ hp hpq.symm, have hqp0 : (q : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero _ hq hpq, by rw [eisenstein_lemma _ hq1 hp1 hpq0, eisenstein_lemma _ hp1 hq1 hqp0, ← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul _ hpq0, mul_comm] lemma legendre_sym_two (hp1 : p % 2 = 1) : legendre_sym 2 p hp = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simp [hp1]), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmodp p hp).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, zmodp.val_cast_of_lt _ h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmodp p hp).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmodp p hp).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma _ hp1 (prime_ne_zero hp prime_two hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((@zmod.eq_iff_modeq_nat 2 _ _).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, zmod.neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_pow_two_eq_two_iff (hp1 : p % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmodp p hp) ≠ 0, from zmodp.prime_ne_zero hp prime_two (λ h, by simp * at *), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmodp p hp) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff hp hp2, legendre_sym_two hp hp1, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, clear hm, revert m, exact dec_trivial end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ∃ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by resetI; subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmodp p hp, a ^ 2 = q) ↔ ¬∃ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
4f8604b4124dcc743eec8d7b1b3350e8210b4360
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1844.lean
a098821b2a68b38c3055db221cb8d19de724fc1b
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
131
lean
variables p q r : Prop -- BEGIN example (h : p ∨ q) (k₁ : p → r) (k₂ : q → r) : r := by exact or.elim h k₁ k₂ -- END
45341dc2a3b3f59f8922ad00caa75d58844ed221
664d56f0f2c151a9cad4364e1985b16d7451c93e
/mm0-lean/x86/x86.lean
827cc14649e7b2528174619b4ecfccc8f3120e67
[ "CC0-1.0" ]
permissive
mattsse/mm0
fc684080b092c3bed865afaa92ea16ae71c179d5
247fd3e2ac65eec7d5317285bb2fee639b17a63f
refs/heads/master
1,608,054,450,033
1,580,386,002,000
1,580,386,002,000
235,200,156
0
0
CC0-1.0
1,579,554,774,000
1,579,554,773,000
null
UTF-8
Lean
false
false
30,174
lean
import x86.bits logic.relation namespace x86 local notation `S` := bitvec.singleton @[reducible] def regnum := bitvec 4 def RAX : regnum := 0 def RCX : regnum := 1 def RDX : regnum := 2 def RSP : regnum := 4 def RBP : regnum := 5 def RSI : regnum := 6 def RDI : regnum := 7 def REX := option (bitvec 4) def REX.to_nat : REX → ℕ | none := 0 | (some r) := r.to_nat def REX.W (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 3) def REX.R (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 2) def REX.X (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 1) def REX.B (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 0) def rex_reg (b : bool) (r : bitvec 3) : regnum := (bitvec.append r (S b) : _) structure scale_index := (scale : bitvec 2) (index : regnum) inductive base | none | rip | reg (reg : regnum) inductive RM : Type | reg : regnum → RM | mem : option scale_index → base → qword → RM def RM.is_mem : RM → Prop | (RM.mem _ _ _) := true | _ := false @[reducible] def Mod := bitvec 2 inductive read_displacement : Mod → qword → list byte → Prop | disp0 : read_displacement 0 0 [] | disp8 (b : byte) : read_displacement 1 (EXTS b) [b] | disp32 (w : word) (l) : w.to_list_byte l → read_displacement 2 (EXTS w) l def read_sib_displacement (mod : Mod) (bbase : regnum) (w : qword) (Base : base) (l : list byte) : Prop := if bbase = RBP ∧ mod = 0 then ∃ b, w = EXTS b ∧ Base = base.none ∧ l = [b] else read_displacement mod w l ∧ Base = base.reg bbase inductive read_SIB (rex : REX) (mod : Mod) : RM → list byte → Prop | mk (b : byte) (bs ix SS) (disp bbase' l) : split_bits b.to_nat [⟨3, bs⟩, ⟨3, ix⟩, ⟨2, SS⟩] → let bbase := rex_reg rex.B bs, index := rex_reg rex.X ix, scaled_index : option scale_index := if index = RSP then none else some ⟨SS, index⟩ in read_sib_displacement mod bbase disp bbase' l → read_SIB (RM.mem scaled_index bbase' disp) (b :: l) inductive read_ModRM (rex : REX) : regnum → RM → list byte → Prop | imm32 (b : byte) (reg_opc : bitvec 3) (i : word) (disp) : split_bits b.to_nat [⟨3, 0b101⟩, ⟨3, reg_opc⟩, ⟨2, 0b00⟩] → i.to_list_byte disp → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none base.rip (EXTS i)) (b :: disp) | reg (b : byte) (rm reg_opc : bitvec 3) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, 0b11⟩] → read_ModRM (rex_reg rex.R reg_opc) (RM.reg (rex_reg rex.B rm)) [b] | sib (b : byte) (reg_opc : bitvec 3) (mod : Mod) (sib) (l) : split_bits b.to_nat [⟨3, 0b100⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → read_SIB rex mod sib l → read_ModRM (rex_reg rex.R reg_opc) sib (b :: l) | mem (b : byte) (rm reg_opc : bitvec 3) (mod : Mod) (disp l) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → rm ≠ 0b100 → ¬ (rm = 0b101 ∧ mod = 0b00) → read_displacement mod disp l → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none (base.reg (rex_reg rex.B rm)) disp) (b :: l) inductive read_opcode_ModRM (rex : REX) : bitvec 3 → RM → list byte → Prop | mk (rn : regnum) (rm l v b) : read_ModRM rex rn rm l → split_bits rn.to_nat [⟨3, v⟩, ⟨1, b⟩] → read_opcode_ModRM v rm l -- obsolete group 1-4 prefixes omitted inductive read_prefixes : REX → list byte → Prop | nil : read_prefixes none [] | rex (b : byte) (rex) : split_bits b.to_nat [⟨4, rex⟩, ⟨4, 0b0100⟩] → read_prefixes (some rex) [b] @[derive decidable_eq] inductive wsize | Sz8 (have_rex : bool) | Sz16 | Sz32 | Sz64 open wsize def wsize.to_nat : wsize → ℕ | (Sz8 _) := 8 | Sz16 := 16 | Sz32 := 32 | Sz64 := 64 inductive read_imm8 : qword → list byte → Prop | mk (b : byte) : read_imm8 (EXTS b) [b] inductive read_imm16 : qword → list byte → Prop | mk (w : bitvec 16) (l) : bits_to_byte 2 w l → read_imm16 (EXTS w) l inductive read_imm32 : qword → list byte → Prop | mk (w : word) (l) : w.to_list_byte l → read_imm32 (EXTS w) l def read_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := λ _ _, false def read_full_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := λ w l, w.to_list_byte l def op_size (have_rex w v : bool) : wsize := if ¬ v then Sz8 have_rex else if w then Sz64 else -- if override then Sz16 else Sz32 def op_size_W (rex : REX) : bool → wsize := op_size rex.is_some rex.W inductive dest_src | Rm_i : RM → qword → dest_src | Rm_r : RM → regnum → dest_src | R_rm : regnum → RM → dest_src open dest_src inductive imm_rm | rm : RM → imm_rm | imm : qword → imm_rm inductive unop | dec | inc | not | neg inductive binop | add | or | adc | sbb | and | sub | xor | cmp | rol | ror | rcl | rcr | shl | shr | tst | sar inductive binop.bits : binop → bitvec 4 → Prop | add : binop.bits binop.add 0x0 | or : binop.bits binop.or 0x1 | adc : binop.bits binop.adc 0x2 | sbb : binop.bits binop.sbb 0x3 | and : binop.bits binop.and 0x4 | sub : binop.bits binop.sub 0x5 | xor : binop.bits binop.xor 0x6 | cmp : binop.bits binop.cmp 0x7 | rol : binop.bits binop.rol 0x8 | ror : binop.bits binop.ror 0x9 | rcl : binop.bits binop.rcl 0xa | rcr : binop.bits binop.rcr 0xb | shl : binop.bits binop.shl 0xc | shr : binop.bits binop.shr 0xd | tst : binop.bits binop.tst 0xe | sar : binop.bits binop.sar 0xf inductive basic_cond | o | b | e | na | s | l | ng inductive basic_cond.bits : basic_cond → bitvec 3 → Prop | o : basic_cond.bits basic_cond.o 0x0 | b : basic_cond.bits basic_cond.b 0x1 | e : basic_cond.bits basic_cond.e 0x2 | na : basic_cond.bits basic_cond.na 0x3 | s : basic_cond.bits basic_cond.s 0x4 | l : basic_cond.bits basic_cond.l 0x6 | ng : basic_cond.bits basic_cond.ng 0x7 inductive cond_code | always | pos : basic_cond → cond_code | neg : basic_cond → cond_code def cond_code.mk : bool → basic_cond → cond_code | ff := cond_code.pos | tt := cond_code.neg inductive cond_code.bits : cond_code → bitvec 4 → Prop | mk (v : bitvec 4) (b c code) : split_bits v.to_nat [⟨3, c⟩, ⟨1, S b⟩] → basic_cond.bits code c → cond_code.bits (cond_code.mk b code) v inductive ast | unop : unop → wsize → RM → ast | binop : binop → wsize → dest_src → ast | mul : wsize → RM → ast | div : wsize → RM → ast | lea : wsize → dest_src → ast | movsx : wsize → dest_src → wsize → ast | movzx : wsize → dest_src → wsize → ast | xchg : wsize → RM → regnum → ast | cmpxchg : wsize → RM → regnum → ast | xadd : wsize → RM → regnum → ast | cmov : cond_code → wsize → dest_src → ast | setcc : cond_code → bool → RM → ast | jump : RM → ast | jcc : cond_code → qword → ast | call : imm_rm → ast | ret : qword → ast | push : imm_rm → ast | pop : RM → ast | leave : ast | cmc | clc | stc -- | int : byte → ast | syscall def ast.mov := ast.cmov cond_code.always inductive decode_hi (v : bool) (sz : wsize) (r : RM) : bool → bitvec 3 → ast → list byte → Prop | test (imm l) : read_imm sz imm l → decode_hi ff 0b000 (ast.binop binop.tst sz (Rm_i r imm)) l | not : decode_hi ff 0b010 (ast.unop unop.not sz r) [] | neg : decode_hi ff 0b011 (ast.unop unop.neg sz r) [] | mul : decode_hi ff 0b100 (ast.mul sz r) [] | div : decode_hi ff 0b110 (ast.div sz r) [] | inc : decode_hi tt 0b000 (ast.unop unop.inc sz r) [] | dec : decode_hi tt 0b001 (ast.unop unop.dec sz r) [] | call : v → decode_hi tt 0b010 (ast.call (imm_rm.rm r)) [] | jump : v → decode_hi tt 0b100 (ast.jump r) [] | push : v → decode_hi tt 0b110 (ast.push (imm_rm.rm r)) [] inductive decode_two (rex : REX) : ast → list byte → Prop | cmov (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x4⟩] → let sz := op_size tt rex.W tt in read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.cmov code sz (R_rm reg r)) (b :: l) | jcc (b : byte) (c imm l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x8⟩] → read_imm32 imm l → cond_code.bits code c → decode_two (ast.jcc code imm) (b :: l) | setcc (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x9⟩] → read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.setcc code rex.is_some r) (b :: l) | cmpxchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1011000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.cmpxchg sz r reg) (b :: l) | movsx (b : byte) (v s reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S s⟩, ⟨4, 0xb⟩] → let sz2 := op_size_W rex tt, sz := if v then Sz16 else Sz8 rex.is_some in read_ModRM rex reg r l → decode_two ((if s then ast.movsx else ast.movzx) sz (R_rm reg r) sz2) (b :: l) | xadd (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.xadd sz r reg) (b :: l) | syscall : decode_two ast.syscall [0x05] inductive decode_aux (rex : REX) : ast → list byte → Prop | binop1 (b : byte) (v d opc reg r l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨1, 0b0⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz src_dst) (b :: l) | binop_imm_rax (b : byte) (v opc imm l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b10⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in binop.bits op (EXTZ opc) → read_imm sz imm l → decode_aux (ast.binop op sz (Rm_i (RM.reg RAX) imm)) (b :: l) | binop_imm (b : byte) (v opc r l1 imm l2 op) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_imm8 (opc r l1 imm l2 op) : let sz := op_size_W rex tt in read_opcode_ModRM rex opc r l1 → binop.bits op (EXTZ opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (0x83 :: l1 ++ l2) | binop_hi (b : byte) (v opc r imm op l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → opc ≠ 6 → binop.bits op (rex_reg tt opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_hi_reg (b : byte) (v x opc r op l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S x⟩, ⟨6, 0b110100⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l → opc ≠ 6 → binop.bits op (rex_reg tt opc) → decode_aux (ast.binop op sz (if x then Rm_r r RCX else Rm_i r 1)) (b :: l) | two (a l) : decode_two rex a l → decode_aux a (0x0f :: l) | movsx (reg r l) : read_ModRM rex reg r l → decode_aux (ast.movsx Sz32 (R_rm reg r) Sz64) (0x63 :: l) | mov (b : byte) (v d reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨6, 0b100010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in decode_aux (ast.mov sz src_dst) (b :: l) | mov64 (b : byte) (r v imm l) : split_bits b.to_nat [⟨3, r⟩, ⟨1, S v⟩, ⟨4, 0xb⟩] → let sz := op_size_W rex v in read_full_imm sz imm l → decode_aux (ast.mov sz (Rm_i (RM.reg (rex_reg rex.B r)) imm)) (b :: l) | mov_imm (b : byte) (v opc r imm l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100011⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → decode_aux (ast.mov sz (Rm_i r imm)) (b :: l1 ++ l2) | xchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000011⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.xchg sz r reg) (b :: l) | xchg_rax (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b10010⟩] → let sz := op_size tt rex.W tt in decode_aux (ast.xchg sz (RM.reg RAX) (rex_reg rex.B r)) [b] | push_imm (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b0⟩, ⟨1, S x⟩, ⟨6, 0b011010⟩] → read_imm (if x then Sz8 ff else Sz32) imm l → decode_aux (ast.push (imm_rm.imm imm)) (b :: l) | push_rm (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01010⟩] → decode_aux (ast.push (imm_rm.rm (RM.reg (rex_reg rex.B r)))) [b] | pop (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01011⟩] → decode_aux (ast.pop (RM.reg (rex_reg rex.B r))) [b] | pop_rm (r l) : read_opcode_ModRM rex 0 r l → decode_aux (ast.pop r) (0x8f :: l) | jump (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b1⟩, ⟨1, S x⟩, ⟨6, 0b111010⟩] → (if x then read_imm8 imm l else read_imm32 imm l) → decode_aux (ast.jcc cond_code.always imm) (b :: l) | jcc8 (b : byte) (c code imm l) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0b0111⟩] → cond_code.bits code c → read_imm8 imm l → decode_aux (ast.jcc code imm) (b :: l) | call (imm l) : read_imm32 imm l → decode_aux (ast.call (imm_rm.imm imm)) (0xe8 :: l) | ret (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100001⟩] → (if v then imm = 0 ∧ l = [] else read_imm16 imm l) → decode_aux (ast.ret imm) (b :: l) | leave : decode_aux ast.leave [0xc9] | lea (reg r l) : let sz := op_size tt rex.W tt in read_ModRM rex reg r l → RM.is_mem r → decode_aux (ast.lea sz (R_rm reg r)) (0x8d :: l) | test (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.binop binop.tst sz (Rm_r r reg)) (b :: l) | test_rax (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1010100⟩] → let sz := op_size tt rex.W v in read_imm sz imm l → decode_aux (ast.binop binop.tst sz (Rm_i (RM.reg RAX) imm)) (b :: l) | cmc : decode_aux ast.cmc [0xf5] | clc : decode_aux ast.clc [0xf8] | stc : decode_aux ast.stc [0xf9] -- | int (imm) : decode_aux (ast.int imm) [0xcd, imm] | hi (b : byte) (v x opc r a l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S x⟩, ⟨4, 0xf⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → decode_hi v sz r x opc a l2 → decode_aux a (b :: l1 ++ l2) inductive decode : ast → list byte → Prop | mk {rex l1 a l2} : read_prefixes rex l1 → decode_aux rex a l2 → decode a (l1 ++ l2) ---------------------------------------- -- Dynamic semantics ---------------------------------------- structure flags := (CF ZF SF OF : bool) def basic_cond.read : basic_cond → flags → bool | basic_cond.o f := f.OF | basic_cond.b f := f.CF | basic_cond.e f := f.ZF | basic_cond.na f := f.CF || f.ZF | basic_cond.s f := f.SF | basic_cond.l f := f.SF ≠ f.OF | basic_cond.ng f := f.ZF || (f.SF ≠ f.OF) def cond_code.read : cond_code → flags → bool | cond_code.always f := tt | (cond_code.pos c) f := c.read f | (cond_code.neg c) f := bnot $ c.read f structure perm := (isR isW isX : bool) def perm.R : perm := ⟨tt, ff, ff⟩ def perm.W : perm := ⟨ff, tt, ff⟩ def perm.X : perm := ⟨ff, ff, tt⟩ instance perm.has_add : has_add perm := ⟨λ p1 p2, ⟨p1.isR || p2.isR, p1.isW || p2.isW, p1.isX || p2.isX⟩⟩ instance perm.has_le : has_le perm := ⟨λ p1 p2, p1 + p2 = p2⟩ structure mem := (valid : qword → Prop) (mem : ∀ w, valid w → byte) (perm : ∀ w, valid w → perm) structure config := (rip : qword) (regs : regnum → qword) (flags : flags) (mem : mem) def mem.read1 (p : perm) (m : mem) (w : qword) (b : byte) : Prop := ∃ h, b = m.mem w h ∧ p ≤ m.perm w h inductive mem.read' (p : perm) (m : mem) : qword → list byte → Prop | nil (w) : mem.read' w [] | cons {w b l} : m.read1 p w b → mem.read' (w + 1) l → mem.read' w (b :: l) def mem.read (m : mem) : qword → list byte → Prop := m.read' perm.R def mem.readX (m : mem) : qword → list byte → Prop := m.read' (perm.R + perm.X) def mem.set (m : mem) (w : qword) (b : byte) : mem := {mem := λ w' h', if w = w' then b else m.mem w' h', ..m} inductive mem.write1 (m : mem) (w : qword) (b : byte) : mem → Prop | mk (h : m.valid w) : perm.R + perm.W ≤ m.perm w h → mem.write1 (m.set w b) inductive mem.write : mem → qword → list byte → mem → Prop | nil (m w) : mem.write m w [] m | cons {m1 m2 m3 : mem} {w b l} : m1.write1 w b m2 → mem.write m2 (w + 1) l m3 → mem.write m1 w (b :: l) m3 inductive EA | i : qword → EA | r : regnum → EA | m : qword → EA def EA.addr : EA → qword | (EA.m a) := a | _ := 0 def index_ea (k : config) : option scale_index → qword | none := 0 | (some ⟨sc, ix⟩) := (bitvec.shl 1 sc.to_nat) * (k.regs ix) def base.ea (k : config) : base → qword | base.none := 0 | base.rip := k.rip | (base.reg r) := k.regs r def RM.ea (k : config) : RM → EA | (RM.reg r) := EA.r r | (RM.mem ix b d) := EA.m (index_ea k ix + b.ea k + d) def ea_dest (k : config) : dest_src → EA | (Rm_i v _) := v.ea k | (Rm_r v _) := v.ea k | (R_rm r _) := EA.r r def ea_src (k : config) : dest_src → EA | (Rm_i _ v) := EA.i v | (Rm_r _ v) := EA.r v | (R_rm _ v) := v.ea k def imm_rm.ea (k : config) : imm_rm → EA | (imm_rm.rm rm) := rm.ea k | (imm_rm.imm q) := EA.i q def EA.read (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → Prop | (EA.i i) sz b := b = EXTZ i | (EA.r r) (Sz8 ff) b := b = EXTZ (if r.nth 2 then (k.regs (r - 4)).ushr 8 else k.regs r) | (EA.r r) sz b := b = EXTZ (k.regs r) | (EA.m a) sz b := ∃ l, k.mem.read a l ∧ bits_to_byte (sz.to_nat / 8) b l def EA.readq (k : config) (ea : EA) (sz : wsize) (q : qword) : Prop := ∃ w, ea.read k sz w ∧ q = EXTZ w def EA.read' (ea : EA) (sz : wsize) : pstate config qword := pstate.assert $ λ k, ea.readq k sz def config.set_reg (k : config) (r : regnum) (v : qword) : config := {regs := λ i, if i = r then v else k.regs i, ..k} def config.write_reg (k : config) (r : regnum) : ∀ sz : wsize, bitvec sz.to_nat → config | (Sz8 have_rex) v := if ¬ have_rex ∧ r.nth 2 then let r' := r - 4 in config.set_reg k r' ((k.regs r').update 8 v) else config.set_reg k r ((k.regs r).update 0 v) | Sz16 v := config.set_reg k r ((k.regs r).update 0 v) | Sz32 v := config.set_reg k r (EXTZ v) | Sz64 v := config.set_reg k r v inductive config.write_mem (k : config) : qword → list byte → config → Prop | mk {a l m'} : k.mem.write a l m' → config.write_mem a l {mem := m', ..k} inductive EA.write (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → config → Prop | r (r sz v) : EA.write (EA.r r) sz v (config.write_reg k r sz v) | m {a} {sz : wsize} {v l k'} : let n := sz.to_nat / 8 in bits_to_byte n v l → k.write_mem a l k' → EA.write (EA.m a) sz v k' def EA.writeq (k : config) (ea : EA) (sz : wsize) (q : qword) (k' : config) : Prop := ea.write k sz (EXTZ q) k' def EA.write' (ea : EA) (sz : wsize) (q : qword) : pstate config unit := pstate.lift $ λ k _, EA.writeq k ea sz q def write_rip (q : qword) : pstate config unit := pstate.modify $ λ k, {rip := q, ..k} inductive dest_src.read (k : config) (sz : wsize) (ds : dest_src) : EA → qword → qword → Prop | mk (d s) : let ea := ea_dest k ds in ea.readq k sz d → (ea_src k ds).readq k sz s → dest_src.read ea d s def dest_src.read' (sz : wsize) (ds : dest_src) : pstate config (EA × qword × qword) := pstate.assert $ λ k ⟨ea, d, s⟩, dest_src.read k sz ds ea d s def EA.call_dest (k : config) : EA → qword → Prop | (EA.i i) q := q = k.rip + i | (EA.r r) q := q = k.regs r | (EA.m a) q := (EA.m a).read k Sz64 q inductive EA.jump (k : config) : EA → config → Prop | mk (ea : EA) (q) : ea.call_dest k q → EA.jump ea {rip := q, ..k} def write_flags (f : config → flags → flags) : pstate config unit := pstate.lift $ λ k _ k', k' = {flags := f k k.flags, ..k} def MSB (sz : wsize) (w : qword) : bool := w.nth (fin.of_nat (sz.to_nat - 1)) def write_SF_ZF (sz : wsize) (w : qword) : pstate config unit := write_flags $ λ k f, { SF := MSB sz w, ZF := (EXTZ w : bitvec sz.to_nat) = 0, ..f } def write_result_flags (sz : wsize) (w : qword) (c o : bool) : pstate config unit := write_flags (λ k f, {CF := c, OF := o, ..f}) >> write_SF_ZF sz w def erase_flags : pstate config unit := do f ← pstate.any, pstate.modify $ λ s, {flags := f, ..s} def sadd_OV (sz : wsize) (a b : qword) : bool := MSB sz a = MSB sz b ∧ MSB sz (a + b) ≠ MSB sz a def ssub_OV (sz : wsize) (a b : qword) : bool := MSB sz a ≠ MSB sz b ∧ MSB sz (a - b) ≠ MSB sz a def add_carry (sz : wsize) (a b : qword) : qword × bool × bool := (a + b, 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, sadd_OV sz a b) def sub_borrow (sz : wsize) (a b : qword) : qword × bool × bool := (a - b, a.to_nat < b.to_nat, ssub_OV sz a b) def write_CF_OF_result (sz : wsize) (w : qword) (c o : bool) (ea : EA) : pstate config unit := write_result_flags sz w c o >> ea.write' sz w def write_SF_ZF_result (sz : wsize) (w : qword) (ea : EA) : pstate config unit := write_SF_ZF sz w >> ea.write' sz w def mask_shift : wsize → qword → ℕ | Sz64 w := (EXTZ w : bitvec 6).to_nat | _ w := (EXTZ w : bitvec 5).to_nat def write_binop (sz : wsize) (ea : EA) (a b : qword) : binop → pstate config unit | binop.add := let (w, c, o) := add_carry sz a b in write_CF_OF_result sz w c o ea | binop.sub := let (w, c, o) := sub_borrow sz a b in write_CF_OF_result sz w c o ea | binop.cmp := let (w, c, o) := sub_borrow sz a b in write_result_flags sz w c o | binop.tst := write_result_flags sz (a.and b) ff ff | binop.and := write_CF_OF_result sz (a.and b) ff ff ea | binop.xor := write_CF_OF_result sz (a.xor b) ff ff ea | binop.or := write_CF_OF_result sz (a.or b) ff ff ea | binop.rol := pstate.fail | binop.ror := pstate.fail | binop.rcl := pstate.fail | binop.rcr := pstate.fail | binop.shl := ea.write' sz (a.shl (mask_shift sz b)) >> erase_flags | binop.shr := ea.write' sz (a.ushr (mask_shift sz b)) >> erase_flags | binop.sar := ea.write' sz (a.fill_shr (mask_shift sz b) (MSB sz a)) >> erase_flags | binop.adc := do k ← pstate.get, let result := a + b + EXTZ (S k.flags.CF), let CF := 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea | binop.sbb := do k ← pstate.get, let carry : qword := EXTZ (S k.flags.CF), let result := a - (b + carry), let CF := a.to_nat < b.to_nat + carry.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea def write_unop (sz : wsize) (a : qword) (ea : EA) : unop → pstate config unit | unop.inc := do let (w, _, o) := add_carry sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.dec := do let (w, _, o) := sub_borrow sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.not := ea.write' sz a.not | unop.neg := do CF ← pstate.any, write_flags (λ k f, {CF := CF, ..f}), write_SF_ZF_result sz (-a) ea def pop_aux : pstate config qword := do k ← pstate.get, let sp := k.regs RSP, (EA.r RSP).write' Sz64 (sp + 8), (EA.m sp).read' Sz64 def pop (rm : RM) : pstate config unit := do k ← pstate.get, pop_aux >>= (rm.ea k).write' Sz64 def pop_rip : pstate config unit := pop_aux >>= write_rip def push_aux (w : qword) : pstate config unit := do k ← pstate.get, let sp := k.regs RSP - 8, (EA.r RSP).write' Sz64 sp, (EA.m sp).write' Sz64 w def push (i : imm_rm) : pstate config unit := do k ← pstate.get, (i.ea k).read' Sz64 >>= push_aux def push_rip : pstate config unit := do k ← pstate.get, push_aux k.rip def execute : ast → pstate config unit | (ast.unop op sz rm) := do k ← pstate.get, let ea := rm.ea k, w ← ea.read' sz, write_unop sz w ea op | (ast.binop op sz ds) := do (ea, d, s) ← dest_src.read' sz ds, write_binop sz ea d s op | (ast.mul sz r) := do eax ← (EA.r RAX).read' sz, k ← pstate.get, src ← (r.ea k).read' sz, match sz with | (Sz8 _) := (EA.r RAX).write' Sz16 (eax * src) | _ := do let hi := bitvec.of_nat sz.to_nat ((eax.to_nat * src.to_nat).shiftl sz.to_nat), (EA.r RAX).write' sz (eax * src), (EA.r RDX).write' sz (EXTZ hi) end, erase_flags | (ast.div sz r) := do eax ← (EA.r RAX).read' sz, edx ← (EA.r RDX).read' sz, let n := edx.to_nat * (2 ^ sz.to_nat) + eax.to_nat, k ← pstate.get, d ← bitvec.to_nat <$> (r.ea k).read' sz, pstate.assert $ λ _ (_:unit), d ≠ 0 ∧ n / d < 2 ^ sz.to_nat, (EA.r RAX).write' sz (bitvec.of_nat _ (n / d)), (EA.r RDX).write' sz (bitvec.of_nat _ (n % d)), erase_flags | (ast.lea sz ds) := do k ← pstate.get, (ea_dest k ds).write' sz (ea_src k ds).addr | (ast.movsx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ (EXTS w : bitvec sz2.to_nat)) | (ast.movzx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ w) | (ast.xchg sz r n) := do let src := EA.r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, dst.write' sz val_src | (ast.cmpxchg sz r n) := do let src := EA.r n, let acc := EA.r RAX, k ← pstate.get, let dst := r.ea k, val_dst ← dst.read' sz, val_acc ← acc.read' sz, write_binop sz src val_acc val_dst binop.cmp, if val_acc = val_dst then src.read' sz >>= dst.write' sz else acc.write' sz val_dst | (ast.xadd sz r n) := do let src := EA.r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, write_binop sz dst val_src val_dst binop.add | (ast.cmov c sz ds) := do k ← pstate.get, when (c.read k.flags) $ (ea_src k ds).read' sz >>= (ea_dest k ds).write' sz | (ast.setcc c b r) := do k ← pstate.get, (r.ea k).write' (Sz8 b) (EXTZ $ S $ c.read k.flags) | (ast.jump rm) := do k ← pstate.get, (rm.ea k).read' Sz64 >>= write_rip | (ast.jcc c i) := do k ← pstate.get, when (c.read k.flags) (write_rip (k.rip + i)) | (ast.call i) := do push_rip, pstate.lift $ λ k _, (i.ea k).jump k | (ast.ret i) := do pop_rip, sp ← (EA.r RSP).read' Sz64, (EA.r RSP).write' Sz64 (sp + i) | (ast.push i) := push i | (ast.pop r) := pop r | ast.leave := do (EA.r RBP).read' Sz64 >>= (EA.r RSP).write' Sz64, pop (RM.reg RBP) | ast.clc := write_flags $ λ _ f, {CF := ff, ..f} | ast.cmc := write_flags $ λ _ f, {CF := bnot f.CF, ..f} | ast.stc := write_flags $ λ _ f, {CF := tt, ..f} -- | (ast.int _) := pstate.fail | ast.syscall := pstate.fail inductive config.step (k : config) : config → Prop | mk {l a k'} : k.mem.readX k.rip l → decode a l → ((do write_rip (k.rip + bitvec.of_nat _ l.length), execute a) k).P () k' → config.step k' inductive config.isIO (k : config) : config → Prop | mk {l k'} : k.mem.readX k.rip l → decode ast.syscall l → ((do let rip := k.rip + bitvec.of_nat _ l.length, write_rip rip, (EA.r RCX).write' Sz64 rip, r11 ← pstate.any, (EA.r 11).write' Sz64 r11) k).P () k' → config.isIO k' structure kcfg := (input : list byte) (output : list byte) (k : config) inductive config.read_cstr (k : config) (a : qword) : string → Prop | mk {s : string} : (∀ c : char, c ∈ s.to_list → c.1 ≠ 0) → k.mem.read a s.to_cstr → config.read_cstr s inductive read_from_fd (fd : qword) : list byte → list byte → list byte → Prop | other {i buf} : fd ≠ 0 → read_from_fd i buf i | stdin {i' buf} : fd = 0 → (buf = [] → i' = []) → read_from_fd (buf ++ i') buf i' inductive exec_read (i : list byte) (k : config) (fd : qword) (count : ℕ) : list byte → config → qword → Prop | fail {ret} : MSB Sz32 ret → exec_read i k ret | success {i' dat k' ret} : ¬ MSB Sz32 ret → ret.to_nat ≤ count → read_from_fd fd i dat i' → k.write_mem (k.regs RSI) dat k' → exec_read i' k' ret inductive exec_io (i o : list byte) (k : config) (rax : qword) : list byte → list byte → config → qword → Prop | _open {pathname fd} : k.read_cstr (k.regs RDI) pathname → let flags := k.regs RSI in flags.to_nat ∈ [0, 0x241] → -- O_RDONLY, or O_WRONLY | O_CREAT | O_TRUNC rax = 2 → exec_io i o k fd | _read {buf i' k' ret} : let fd := k.regs RDI, count := (k.regs RDX).to_nat in k.mem.read (k.regs RSI) buf → buf.length = count → exec_read i k fd count i' k' ret → rax = 0 → exec_io i' o k' ret -- TODO: write, fstat, mmap inductive exec_exit (k : config) : qword → Prop | mk : k.regs RAX = 0x3c → exec_exit (k.regs RDI) def config.exit (k : config) (a : qword) : Prop := ∃ k', config.isIO k k' ∧ exec_exit k' a inductive kcfg.step : kcfg → kcfg → Prop | noio {i o k k'} : config.step k k' → kcfg.step ⟨i, o, k⟩ ⟨i, o, k'⟩ | io {i o k k₁ i' o' k' ret} : config.isIO k k₁ → exec_io i o k₁ (k₁.regs RAX) i' o' k' ret → kcfg.step ⟨i, o, k⟩ ⟨i', o', k'.set_reg RAX ret⟩ def kcfg.steps : kcfg → kcfg → Prop := relation.refl_trans_gen kcfg.step def kcfg.valid (k : kcfg) : Prop := (∃ k', k.step k') ∨ ∃ ret, k.k.exit ret def kcfg.safe (k : kcfg) : Prop := ∀ k', k.steps k' → k'.valid def terminates (k : config) (i o : list byte) := ∀ K', kcfg.steps ⟨i, [], k⟩ K' → ∃ i' o' k' ret, kcfg.steps K' ⟨i', o', k'⟩ ∧ k'.exit ret ∧ (ret = 0 → i' = [] ∧ o' = o) def succeeds (k : config) (i o : list byte) := ∃ i' k', kcfg.steps ⟨i, [], k⟩ ⟨i', o, k'⟩ ∧ k'.exit 0 inductive hoare_p (Q : kcfg → Prop) : kcfg → Prop | zero {{k}} : Q k → hoare_p k | step {{k}} : (∃ k', kcfg.step k k') → (∀ k', k.step k' → hoare_p k') → hoare_p k | exit (k : kcfg) (ret) : k.k.exit ret → (ret = 0 → Q k) → hoare_p k end x86
5211a83131a8df2707548dc4d869d2d88b10602f
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/linear_algebra/multilinear.lean
1fe3ef75de8d0936ce057e2281641c0647b83491
[ "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
53,708
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import algebra.algebra.basic import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ initialize_simps_projections multilinear_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) : ⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x := congr_arg (λ h : multilinear_map R M₁ M₂, h x) h theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y := congr_arg (λ x : Π i, M₁ i, f x) h theorem coe_inj ⦃f g : multilinear_map R M₁ M₂⦄ (h : ⇑f = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := coe_inj (funext H) theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Π i, M' i`. -/ @[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, semimodule R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Π i, M' i) := { to_fun := λ m i, f i m, map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _, map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] section variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, semimodule R (M₁' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) : multilinear_map R M₁ M₂ := { to_fun := λ m, g $ λ i, f i (m i), map_add' := λ m i x y, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this], map_smul' := λ m i c x, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) (m : Π i, M₁ i) : g.comp_linear_map f m = g (λ i, f i (m i)) := rfl end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ι] : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ι] [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), semimodule A (M₁ i)] [semimodule A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved semimodules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := λ v, m (λ i, v (σ i)), map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) : multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ m, by {ext, simp}, right_inv := λ m, by {ext, simp}, map_add' := λ a b, by {ext, simp} } end end semiring end multilinear_map namespace linear_map variables [semiring R] [Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] @[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃) (f : multilinear_map R (λ i : ι₁, M') M₂) : (g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Π i, semimodule A (M₁ i)] [distrib_mul_action R' M₂] [semimodule A M₂] [smul_comm_class A R' M₂] instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl instance : distrib_mul_action R' (multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section semimodule variables {R' A : Type*} [semiring R'] [semiring A] [Π i, semimodule A (M₁ i)] [semimodule A M₂] [add_comm_monoid M₃] [semimodule R' M₃] [semimodule A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [semimodule R' M₂] [smul_comm_class A R' M₂] : semimodule R' (multilinear_map A M₁ M₂) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variables (M₂ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ := { map_smul' := λ c f, by { ext, simp }, .. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+ multilinear_map A (λ i : ι₂, M₂) M₃) } end semimodule section dom_coprod open_locale tensor_product variables {ι₁ ι₂ ι₃ ι₄ : Type*} variables [decidable_eq ι₁] [decidable_eq ι₂][decidable_eq ι₃] [decidable_eq ι₄] variables {N₁ : Type*} [add_comm_monoid N₁] [semimodule R N₁] variables {N₂ : Type*} [add_comm_monoid N₂] [semimodule R N₂] variables {N : Type*} [add_comm_monoid N] [semimodule R N] /-- Given two multilinear maps `(ι₁ → N) → N₁` and `(ι₂ → N) → N₂`, this produces the map `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂` by taking the coproduct of the domain and the tensor product of the codomain. This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with `tensor_product.map`, noting that the two operations can't be separated as the intermediate result is not a `multilinear_map`. While this can be generalized to work for dependent `Π i : ι₁, N'₁ i` instead of `ι₁ → N`, doing so introduces `sum.elim N'₁ N'₂` types in the result which are difficult to work with and not defeq to the simple case defined here. See [this zulip thread]( https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619). -/ @[simps apply] def dom_coprod (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := { to_fun := λ v, a (λ i, v (sum.inl i)) ⊗ₜ b (λ i, v (sum.inr i)), map_add' := λ v i p q, by cases i; simp [tensor_product.add_tmul, tensor_product.tmul_add], map_smul' := λ v i c p, by cases i; simp [tensor_product.smul_tmul', tensor_product.tmul_smul] } /-- A more bundled version of `multilinear_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : multilinear_map R (λ _ : ι₁, N) N₁ ⊗[R] multilinear_map R (λ _ : ι₂, N) N₂ →ₗ[R] multilinear_map R (λ _ : ι₁ ⊕ ι₂, N) (N₁ ⊗[R] N₂) := tensor_product.lift $ linear_map.mk₂ R (dom_coprod) (λ m₁ m₂ n, by { ext, simp only [dom_coprod_apply, tensor_product.add_tmul, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.smul_tmul', smul_apply] }) (λ m n₁ n₂, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_add, add_apply] }) (λ c m n, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_smul, smul_apply] }) @[simp] lemma dom_coprod'_apply (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) : dom_coprod' (a ⊗ₜ[R] b) = dom_coprod a b := rfl /-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over `multilinear_map.dom_coprod`. -/ lemma dom_coprod_dom_dom_congr_sum_congr (a : multilinear_map R (λ _ : ι₁, N) N₁) (b : multilinear_map R (λ _ : ι₂, N) N₂) (σa : ι₁ ≃ ι₃) (σb : ι₂ ≃ ι₄) : (a.dom_coprod b).dom_dom_congr (σa.sum_congr σb) = (a.dom_dom_congr σa).dom_coprod (b.dom_dom_congr σb) := rfl end dom_coprod section variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A := { to_fun := λ m, ∏ i, m i, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] } variables {R A ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A := { to_fun := λ m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) : f.smul_right z m = f m • z := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := (multilinear_map.mk_pi_algebra R ι R).smul_right z variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f g : multilinear_map R M₁ M₂) instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ M₂) := ⟨λ f g, ⟨λ m, f m - g m, λ m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg] end range_add_comm_group section add_comm_group variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, semimodule R (M i)] [semimodule R M'] [semimodule R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by rw f.snoc_smul }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂} /-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := λ u, { to_fun := λ v, f (sum.elim u v), map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := λ u i x y, ext $ λ v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := λ u i c x, ext $ λ v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) (u : ι → M') (v : ι' → M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/ def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) : multilinear_map R (λ x : ι ⊕ ι', M') M₂ := { to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := λ u i x y, by cases i; simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := λ u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ι ι' R M₂ M') /-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R] multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := λ f, ext $ λ u, by simp, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl } } variables {ι ι' R M₂ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl variables (R M₂ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps on `λ i : fin l, M'`. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) : multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R] multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) := (dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) M₂ M' (fin l)) variables {R M₂ M'} @[simp] lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (mk : fin k → M') (ml : fin l → M') : curry_fin_finset R M₂ M' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (m : fin n → M') : (curry_fin_finset R M₂ M' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') : (curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') : (curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') : curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying section submodule variables {R M M₂} [ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M'] [semimodule R M₂] namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : sub_mul_action R M₂ := { carrier := f '' { v | ∀ i, v i ∈ p i}, smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by { refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : (map f p : set M₂).nonempty := ⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := f.map (λ i, ⊤) end multilinear_map end submodule
00d30c5966da06324df4d8c154610b42426df520
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/dbgMacros.lean
16072bd084e9691a786dbc95cdcf9acd997398bd
[ "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
397
lean
new_frontend def f (x : Nat) := if x = 0 then panic! "unexpected zero" else x - 1 #eval f 0 #eval f 10 def g (x : Nat) := if x = 0 then unreachable! else x - 1 #eval g 0 def h (x : Nat) := assert! x != 0; x - 1 #eval h 1 #eval h 0 def f2 (x : Nat) := dbgTrace! "f2, x: " ++ toString x; x + 1 #eval f2 10 def g2 (x : Nat) : IO Nat := do IO.println "g2 started"; pure (x + 1) #eval g2 10
5c0fa72ad8a389e11f5eb6d63c04bc38798e9294
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/polyhedral_lattice.lean
4d8338ad757fa3cadf702f3a10662a1d800bdfd9
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
572
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.polyhedron import combinatorics.simplicial_complex.polytope open set affine poly variables {E : Type*} [normed_group E] [normed_space ℝ E] {x : E} {X Y : finset E} {C : set E} /-- Faces of a polytope form a complete lattice. -/ def complete_lattice_faces (P : poly.polytope E) : complete_lattice (polytope.to_simplicial_complex P).faces := sorry
b64a9af066a0263e9216f2503d24de3e6629b0cc
7b9ff28673cd3dd7dd3dcfe2ab8449f9244fe05a
/src/floris/lecture-library-building.lean
920031faf88f7a55e8aec1d6b4d4857d7d1141f0
[]
no_license
jesse-michael-han/hanoi-lean-2019
ea2f0e04f81093373c48447065765a964ee82262
a5a9f368e394d563bfcc13e3773863924505b1ce
refs/heads/master
1,591,320,223,247
1,561,022,886,000
1,561,022,886,000
192,264,820
1
1
null
null
null
null
UTF-8
Lean
false
false
6,355
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn. A lecture on library-building. -/ import algebra.group order.boolean_algebra tactic.library_search data.vector set_option old_structure_cmd true universe variable u /- Best practices: -/ /- Use good names: https://github.com/leanprover-community/mathlib/blob/master/docs/contribute/naming.md -/ #print nat.succ_ne_zero #print mul_zero -- the name could be mul_zero_eq, but we shorten it #print mul_one #print le_iff_lt_or_eq #print neg_neg #print add_lt_add_of_lt_of_le #print mul_assoc example {p q : Prop} (h : p ∧ q) : p := h.left -- and.left h open nat example (n : ℕ) : succ n > 0 := by library_search -- library_search is useful to find a lemma in the library. You need to know the exact conclusion of the lemma (and import tactic.library_search). /- Use good style: https://github.com/leanprover-community/mathlib/blob/master/docs/contribute/style.md -/ /- Good proving practice * Try to work in great generality (c.f. Fréchet derivative) * Use bi-implications whenever possible * Write equations and bi-implications so that the RHS is simpler than the LHS (if possible) -/ /- IMPORTANT: Copy-paste from a similar development: - The existing library probably used the right explicit/implicit arguments - The existing library probably used the right style - The existing library probably made good design decisions -/ /- Look through mathlib to see what parts already exists -/ /- After you complete a lemma, clean up the proof afterwards: * replace `intro x, intro y` by `intros x y` * remove `simp` (or other automation) if it didn't close goal * If the proof fits on one line, replace `begin ... end` with `by { ... }` * etc. -/ /- As a demo, let's build a little library of quasigroups: https://en.wikipedia.org/wiki/Quasigroup -/ /- From Wikipedia: A quasigroup (Q, ∗, \, /) is a type (2,2,2) algebra (i.e., equipped with three binary operations) satisfying the identities: y = x ∗ (x \ y), y = x \ (x ∗ y), y = (y / x) ∗ x, y = (y ∗ x) / x. -/ #print semigroup -- we use a definition similar to semigroup -- \ is left division, abbreviated as ldiv -- / right division, abbreviated as rdiv class quasigroup (α : Type u) extends has_mul α, has_div α, has_sdiff α := (mul_ldiv : ∀ x y : α, x * (x \ y) = y) (ldiv_mul : ∀ x y : α, x \ (x * y) = y) (rdiv_mul : ∀ x y : α, (x / y) * y = x) (mul_rdiv : ∀ x y : α, (x * y) / y = x) -- x \ y is the unique element z such that x * z = y variables {α : Type u} [quasigroup α] lemma mul_ldiv (x y : α) : x * (x \ y) = y := quasigroup.mul_ldiv x y lemma ldiv_mul (x y : α) : x \ (x * y) = y := quasigroup.ldiv_mul x y lemma mul_rdiv (x y : α) : (x * y) / y = x := quasigroup.mul_rdiv x y lemma rdiv_mul (x y : α) : (x / y) * y = x := quasigroup.rdiv_mul x y @[simp] lemma ldiv_eq_iff_mul_eq {x y z : α} : x \ y = z ↔ x * z = y := begin split, { intro h, rw [← h, mul_ldiv] }, { intro h, rw [← h, ldiv_mul] } end @[simp] lemma rdiv_eq_iff_mul_eq {x y z : α} : x / y = z ↔ z * y = x := begin split, { intro h, rw [← h, rdiv_mul] }, { intro h, rw [← h, mul_rdiv] } end /- Given an abelian group, (A, +), taking its subtraction operation as quasigroup multiplication yields a quasigroup (A, −) -/ @[simp] lemma add_add_neg_cancel {α} [add_comm_group α] (x y : α) : x + (y + -x) = y := by { rw [add_comm], simp } def sub_quasigroup (α : Type u) := α instance {α} [add_comm_group α] : quasigroup (sub_quasigroup α) := { mul := λ x y, (x - y : α), div := λ x y, (x + y : α), sdiff := λ x y, (x - y : α), ldiv_mul := by { intros, simp }, mul_ldiv := by { intros, simp }, mul_rdiv := by { intros, simp }, rdiv_mul := by { intros, simp } } /- A loop is a quasigroup with an identity element; that is, an element, e, such that x ∗ e = x and e ∗ x = x for all x in Q. It follows that the identity element, e, is unique, and that every element of Q has unique left and right inverses (which need not be the same). -/ #print monoid -- we use a definition similar to monoid. class loop (α : Type u) extends quasigroup α, has_one α := (one_mul : ∀ a : α, 1 * a = a) (mul_one : ∀ a : α, a * 1 = a) /- Every group is a loop. -/ #print group instance group.to_loop {α : Type u} [h : group α] : loop α := { mul := (*), div := λ x y, x * y⁻¹, sdiff := λ x y, x⁻¹ * y, mul_ldiv := by { intros, simp }, ldiv_mul := by { intros, simp }, rdiv_mul := by { intros, simp }, mul_rdiv := by { intros, simp }, ..h } /- A loop that is associative is a group -/ def loop.to_group {α} [h : loop α] (h_assoc : ∀ x y z : α, (x * y) * z = x * (y * z)) : group α := { mul := (*), mul_assoc := h_assoc, inv := λ x, 1 / x, mul_left_inv := λ x, by apply rdiv_mul, ..h } ------------- Q&A ------------- /- It is better not to put `quasigroup α` as an argument. If we did that, we would have to specify two arguments to state that α has a loop structure -/ class loop' (α : Type u) [quasigroup α] extends has_one α := (one_mul : ∀ a : α, 1 * a = a) (mul_one : ∀ a : α, a * 1 = a) def loop'.to_group {α} [quasigroup α] [h : loop' α] (h_assoc : ∀ x y z : α, (x * y) * z = x * (y * z)) : group α := sorry instance group.to_quasigroup {α : Type u} [h : group α] : quasigroup α := sorry /- The following instance doesn't type-check if we remove the previous instance. -/ instance group.to_loop' {α : Type u} [h : group α] : loop' α := sorry /- If you want to use the notation * for an operation of type α → α → α (for some α), you can should make an instance of has_mul. Example: -/ instance list.has_mul {α : Type u} : has_mul (list α) := { mul := list.append } /- If you want to make it a local notation (for only this file), use: -/ def list.has_mul' {α : Type u} : has_mul (list α) := { mul := list.append } local attribute [instance] list.has_mul' /- if you have an operation with a different type, define (local) notation for it, and use a symbol other than * -/ constant inner_product {n : ℕ} : vector ℕ n → vector ℕ n → ℕ local infix ⬝ := inner_product
def83b3f966243b40c88d70b9f59fcbc166da1ad
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/SyntheticMVars.lean
457cded06d5dc8bac96b8b0122d4b0751071dce9
[ "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
18,042
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 withTacticInfoContext) open Meta /-- 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 (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx <| withMVarContext mvarId do let s ← get try withSavedContext savedContext 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 /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/ if (← occursCheck mvarId result) then assignExprMVar mvarId result return true else return false catch | ex@(Exception.internal id _) => if id == postponeExceptionId then set s return false else throw ex | ex@(Exception.error _ _) => if postponeOnError then set s return false else logException ex return 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; return true | _ => unreachable! /-- Similar to `synthesizePendingInstMVar`, but generates type mismatch error message. Remark: `eNew` is of the form `@coe ... mvar`, where `mvar` is the metavariable for the `CoeT ...` instance. If `mvar` can be synthesized, then assign `auxMVarId := (expandCoe eNew)`. -/ private def synthesizePendingCoeInstMVar (auxMVarId : MVarId) (errorMsgHeader? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Bool := do let instMVarId := eNew.appArg!.mvarId! withMVarContext instMVarId do if (← isDefEq expectedType eType) then /- This case may seem counterintuitive since we created the coercion because the `isDefEq expectedType eType` test failed before. However, it may succeed here because we have more information, for example, metavariables occurring at `expectedType` and `eType` may have been assigned. -/ if (← occursCheck auxMVarId e) then assignExprMVar auxMVarId e return true else return false try if (← synthesizeCoeInstMVarCore instMVarId) then let eNew ← expandCoe eNew if (← occursCheck auxMVarId eNew) then assignExprMVar auxMVarId eNew return true return false catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => unreachable! /-- Try to synthesize a value for `mvarId` using the given default instance. Return `some (val, mvarDecls)` if successful, where `val` is the value assigned to `mvarId`, and `mvarDecls` is a list of new type class instances that need to be synthesized. -/ private def tryToSynthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM (Option (Expr × List SyntheticMVarDecl)) := commitWhenSome? do let candidate ← mkConstWithFreshMVarLevels defaultInstance 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 (candidate, result) else return none private def tryToSynthesizeUsingDefaultInstances (mvarId : MVarId) (prio : Nat) : TermElabM (Option (Expr × 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 result => return some result | 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 (val, newMVarDecls) => for newMVarDecl in newMVarDecls do -- Register that `newMVarDecl.mvarId`s are implicit arguments of the value assigned to `mvarDecl.mvarId` registerMVarErrorImplicitArgInfo newMVarDecl.mvarId (← getRef) val 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. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. -/ private def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do let syntheticMVars ← modifyGet fun s => (s.syntheticMVars, { s with syntheticMVars := [] }) for mvarSyntheticDecl in syntheticMVars do withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | SyntheticMVarKind.typeClass => unless ignoreStuckTC do withMVarContext mvarSyntheticDecl.mvarId do let mvarDecl ← getMVarDecl mvarSyntheticDecl.mvarId unless (← get).messages.hasErrors do throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}" | SyntheticMVarKind.coe header eNew expectedType eType e f? => let mvarId := eNew.appArg!.mvarId! withMVarContext mvarId do let mvarDecl ← getMVarDecl 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 => return mvarDecl.stx | none => return Syntax.missing mutual partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := do /- Recall, `tacticCode` is the whole `by ...` expression. -/ let byTk := tacticCode[0] let code := tacticCode[1] modifyThe Meta.State fun s => { s with mctx := s.mctx.instantiateMVarDeclMVars mvarId } let remainingGoals ← withInfoHole mvarId <| Tactic.run mvarId do withTacticInfoContext tacticCode (evalTactic code) synthesizeSyntheticMVars (mayPostpone := false) unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals /-- Try to synthesize the given pending synthetic metavariable. -/ private partial 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? eNew expectedType eType e f? => synthesizePendingCoeInstMVar mvarSyntheticDecl.mvarId header? eNew expectedType eType e f? -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | SyntheticMVarKind.postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarSyntheticDecl.mvarId postponeOnError | SyntheticMVarKind.tactic tacticCode savedContext => withSavedContext savedContext do if runTactics then runTactic mvarSyntheticDecl.mvarId tacticCode return true else return false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private partial 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 syntheticMVars := (← get).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 format "succeeded" else format "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 } return numSyntheticMVars != remainingSyntheticMVars.length /-- 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. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then, pending TC problems become implicit parameters for the simp theorem. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := let rec loop (u : Unit) : TermElabM Unit := do withRef (← getSomeSynthethicMVarsRef) <| withIncRecDepth do unless (← get).syntheticMVars.isEmpty do if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := 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 (postponeOnError := true) (runTactics := false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then loop () else reportStuckSyntheticMVars ignoreStuckTC loop () end def synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := false) : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := ignoreStuckTC) /- 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 private partial def withSynthesizeImp {α} (k : TermElabM α) (mayPostpone : Bool) (synthesizeDefault : Bool) : TermElabM α := do let syntheticMVarsSaved := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone && synthesizeDefault then synthesizeUsingDefaultLoop return a finally modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved } /-- 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` -/ @[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m α) (mayPostpone := false) : m α := monadMap (m := TermElabM) (withSynthesizeImp . mayPostpone (synthesizeDefault := true)) k /-- Similar to `withSynthesize`, but sets `mayPostpone` to `true`, and do not use `synthesizeUsingDefault` -/ @[inline] def withSynthesizeLight [MonadFunctorT TermElabM m] [Monad m] (k : m α) : m α := monadMap (m := TermElabM) (withSynthesizeImp . (mayPostpone := true) (synthesizeDefault := false)) k /-- 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 instantiateMVars (← withSynthesize <| elabTerm stx expectedType?) builtin_initialize registerTraceClass `Elab.resume end Lean.Elab.Term
5c4fdeb526355f1f53719ba0930299560da5e827
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/interactive.lean
2ed42a8f7dcb9db3adc9efa3ae4a949400475485
[ "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
23,437
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators namespace interactive namespace types /- The parser treats constants in the tactic.interactive namespace specially. The following argument types have special parser support when interactive tactics are used inside `begin ... end` blocks. - ident : make sure the next token is an identifier, and produce the quoted name `t, where t is the next identifier. - opt_ident : parse (identifier)? - using_ident - raw_ident_list : parse identifier* and produce a list of quoted identifiers. Example: a b c produces [`a, `b, `c] - with_ident_list : parse (`with` identifier+)? and produce a list of quoted identifiers - assign_tk : parse the token `:=` and produce the unit () - colon_tk : parse the token `:` and produce the unit () - comma_tk : parse the token `,` and produce the unit () - location : parse (`at` identifier+)? and produce a list of quoted identifiers - qexpr : parse an expression e and produce the quoted expression `e - qexpr_list : parse `[` (expr (`,` expr)*)? `]` and produce a list of quoted expressions. - opt_qexpr_list : parse (`[` (expr (`,` expr)*)? `]`)? and produce a list of quoted expressions. - qexpr0 : parse an expression e using 0 as the right-binding-power, and produce the quoted expression `e - qexpr_list_or_qexpr0 : parse `[` (expr (`,` expr)*)? `]` or expr and produce a list of quoted expressions - qexpr_list_with_pos - qexpr_list_or_qexpr0_with_pos : parse `[` (expr (`,` expr)*)? `]` or expr and produce a list of quoted expressions with position information -/ def pos : Type := nat × nat def ident : Type := name def opt_ident : Type := option ident def using_ident : Type := option ident def raw_ident_list : Type := list ident def with_ident_list : Type := list ident def without_ident_list : Type := list ident def location : Type := list ident @[reducible] meta def qexpr : Type := pexpr @[reducible] meta def qexpr0 : Type := pexpr meta def qexpr_list : Type := list qexpr meta def qexpr_list_with_pos : Type := list (qexpr × pos) meta def opt_qexpr_list : Type := list qexpr meta def qexpr_list_or_qexpr0 : Type := list qexpr meta def qexpr_list_or_qexpr0_with_pos : Type := list (qexpr × pos) meta def assign_tk : Type := unit meta def colon_tk : Type := unit end types end interactive namespace tactic meta def report_resolve_name_failure {α : Type} (e : expr) (n : name) : tactic α := if e^.is_choice_macro then fail ("failed to resolve name '" ++ to_string n ++ "', it is overloaded") else fail ("failed to resolve name '" ++ to_string n ++ "', unexpected result") namespace interactive open interactive.types expr /- itactic: parse a nested "interactive" tactic. That is, parse `(` tactic `)` -/ meta def itactic : Type := tactic unit /-- This tactic applies to a goal that is either a Pi/forall or starts with a let binder. If the current goal is a Pi/forall `∀ x:T, U` (resp `let x:=t in U`) then intro puts `x:T` (resp `x:=t`) in the local context. The new subgoal target is `U`. If the goal is an arrow `T → U`, then it puts in the local context either `h:T`, and the new goal target is `U`. If the goal is neither a Pi/forall nor starting with a let definition, the tactic `intro` applies the tactic `whnf` until the tactic `intro` can be applied or the goal is not `head-reducible`. -/ meta def intro : opt_ident → tactic unit | none := intro1 >> skip | (some h) := tactic.intro h >> skip /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h_1 ... h_n` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : raw_ident_list → tactic unit | [] := tactic.intros >> skip | hs := intro_lst hs >> skip /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` into `h₂` in the current local context. -/ meta def rename : ident → ident → tactic unit := tactic.rename /-- This tactic applies to any goal. The argument term is a term well-formed in the local context of the main goal. The tactic apply tries to match the current goal against the conclusion of the type of term. If it succeeds, then the tactic returns as many subgoals as the number of non-dependent premises that have not been fixed by type inference or type class resolution. The tactic `apply` uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : qexpr0) : tactic unit := to_expr q >>= tactic.apply /-- Similar to the `apply` tactic, but it also creates subgoals for dependent premises that have not been fixed by type inference or type class resolution. -/ meta def fapply (q : qexpr0) : tactic unit := to_expr q >>= tactic.fapply /-- This tactic tries to close the main goal `... |- U` using type class resolution. It succeeds if it generates a term of type `U` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic applies to any goal. It behaves like `exact` with a big difference: the user can leave some holes `_` in the term. `refine` will generate as many subgoals as there are holes in the term. Note that some holes may be implicit. The type of holes must be either synthesized by the system or declared by an explicit type ascription like (e.g., `(_ : nat → Prop)`). -/ meta def refine : qexpr0 → tactic unit := tactic.refine /-- This tactic looks in the local context for an hypothesis which type is equal to the goal target. If it is the case, the subgoal is proved. Otherwise, it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- This tactic applies to any goal. `change U` replaces the main goal target `T` with `U` providing that `U` is well-formed with respect to the main goal local context, and `T` and `U` are definitionally equal. -/ meta def change (q : qexpr0) : tactic unit := to_expr q >>= tactic.change /-- This tactic applies to any goal. It gives directly the exact proof term of the goal. Let `T` be our goal, let `p` be a term of type `U` then `exact p` succeeds iff `T` and `U` are definitionally equal. -/ meta def exact (q : qexpr0) : tactic unit := do tgt : expr ← target, to_expr_strict `(%%q : %%tgt) >>= tactic.exact private meta def get_locals : list name → tactic (list expr) | [] := return [] | (n::ns) := do h ← get_local n, hs ← get_locals ns, return (h::hs) /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and its dependencies to the goal target. This tactic is the inverse of `intro`. -/ meta def revert (ids : raw_ident_list) : tactic unit := do hs ← get_locals ids, revert_lst hs, skip /- Return (some a) iff p is of the form (- a) -/ private meta def is_neg (p : pexpr) : option pexpr := /- Remark: we use the low-level to_raw_expr and of_raw_expr to be able to pattern match pre-terms. This is a low-level trick (aka hack). -/ match pexpr.to_raw_expr p with | (app (const c []) arg) := if c = `neg then some (pexpr.of_raw_expr arg) else none | _ := none end private meta def resolve_name' (n : name) : tactic expr := do { e ← resolve_name n, match e with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := return e end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ private meta def to_expr' (p : pexpr) : tactic expr := let e := pexpr.to_raw_expr p in match e with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e e, return new_e | _ := to_expr p end private meta def to_symm_expr_list : list (pexpr × pos) → tactic (list (bool × expr × pos)) | [] := return [] | ((p, pos)::ps) := match is_neg p with | some a := do r ← to_expr' a, rs ← to_symm_expr_list ps, return ((tt, r, pos) :: rs) | none := do r ← to_expr' p, rs ← to_symm_expr_list ps, return ((ff, r, pos) :: rs) end private meta def rw_goal : transparency → list (bool × expr × pos) → tactic unit | m [] := return () | m ((symm, e, pos)::es) := save_info pos.1 pos.2 >> rewrite_core m tt tt occurrences.all symm e >> rw_goal m es private meta def rw_hyp : transparency → list (bool × expr × pos) → name → tactic unit | m [] hname := return () | m ((symm, e, pos)::es) hname := do h ← get_local hname, save_info pos.1 pos.2, rewrite_at_core m tt tt occurrences.all symm e h, rw_hyp m es hname private meta def rw_hyps : transparency → list (bool × expr × pos) → list name → tactic unit | m es [] := return () | m es (h::hs) := rw_hyp m es h >> rw_hyps m es hs private meta def rw_core (m : transparency) (hs : qexpr_list_or_qexpr0_with_pos) (loc : location) : tactic unit := do hlist ← to_symm_expr_list hs, match loc with | [] := rw_goal m hlist >> try (reflexivity_core reducible) | hs := rw_hyps m hlist hs >> try (reflexivity_core reducible) end meta def rewrite : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rw_core reducible meta def rw : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rewrite /- rewrite followed by assumption -/ meta def rwa (q : qexpr_list_or_qexpr0_with_pos) (l : location) : tactic unit := rewrite q l >> try assumption meta def erewrite : qexpr_list_or_qexpr0_with_pos → location → tactic unit := rw_core semireducible meta def erw : qexpr_list_or_qexpr0_with_pos → location → tactic unit := erewrite private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type | failed, return I meta def induction (p : qexpr0) (rec_name : using_ident) (ids : with_ident_list) : tactic unit := do e ← to_expr p, match rec_name with | some n := induction_core semireducible e n ids | none := do I ← get_type_name e, induction_core semireducible e (I <.> "rec") ids end meta def cases (p : qexpr0) (ids : with_ident_list) : tactic unit := do e ← to_expr p, if e^.is_local_constant then cases_core semireducible e ids else do x ← mk_fresh_name, tactic.generalize e x <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, cases_core semireducible h ids meta def destruct (p : qexpr0) : tactic unit := to_expr p >>= tactic.destruct meta def generalize (p : qexpr) (x : ident) : tactic unit := do e ← to_expr p, tactic.generalize e x meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- This tactic applies to any goal. The contradiction tactic attempts to find in the current local context an hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction meta def repeat : itactic → tactic unit := tactic.repeat meta def try : itactic → tactic unit := tactic.try meta def solve1 : itactic → tactic unit := tactic.solve1 /-- This tactic applies to any goal. `assert h : T` adds a new hypothesis of name `h` and type `T` to the current goal and opens a new subgoal with target `T`. The new subgoal becomes the main goal. -/ meta def assert (h : ident) (c : colon_tk) (q : qexpr0) : tactic unit := do e ← to_expr_strict q, tactic.assert h e meta def define (h : ident) (c : colon_tk) (q : qexpr0) : tactic unit := do e ← to_expr_strict q, tactic.define h e /-- This tactic applies to any goal. `assertv h : T := p` adds a new hypothesis of name `h` and type `T` to the current goal if `p` a term of type `T`. -/ meta def assertv (h : ident) (c : colon_tk) (q₁ : qexpr0) (a : assign_tk) (q₂ : qexpr0) : tactic unit := do t ← to_expr_strict q₁, v ← to_expr_strict `(%%q₂ : %%t), tactic.assertv h t v meta def definev (h : ident) (c : colon_tk) (q₁ : qexpr0) (a : assign_tk) (q₂ : qexpr0) : tactic unit := do t ← to_expr_strict q₁, v ← to_expr_strict `(%%q₂ : %%t), tactic.definev h t v meta def note (h : ident) (a : assign_tk) (q : qexpr0) : tactic unit := do p ← to_expr_strict q, tactic.note h p meta def pose (h : ident) (a : assign_tk) (q : qexpr0) : tactic unit := do p ← to_expr_strict q, tactic.pose h p /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a meta def existsi (e : qexpr0) : tactic unit := to_expr e >>= tactic.existsi /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := tactic.constructor meta def left : tactic unit := tactic.left meta def right : tactic unit := tactic.right meta def split : tactic unit := tactic.split meta def exfalso : tactic unit := tactic.exfalso /-- The injection tactic is based on the fact that constructors of inductive datatypes are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds to new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` an `h₂` to name the new hypotheses. -/ meta def injection (q : qexpr0) (hs : with_ident_list) : tactic unit := do e ← to_expr q, tactic.injection_with e hs private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s^.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail ("invalid simplification lemma '" ++ to_string n ++ "' (use command 'set_option trace.simp_lemmas true' for more details)") private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (n : name) (ref : expr) : tactic simp_lemmas := do e ← resolve_name n, match e with | expr.const n _ := (do b ← is_valid_simp_lemma_cnst reducible n, guard b, save_const_type_info n ref, s^.add_simp n) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns^.length > 0), save_const_type_info n ref, add_simps s eqns) <|> report_invalid_simp_lemma n | _ := (do b ← is_valid_simp_lemma reducible e, guard b, try (save_type_info e ref), s^.add e) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (p : pexpr) : tactic simp_lemmas := let e := pexpr.to_raw_expr p in match e with | (const c []) := simp_lemmas.resolve_and_add s c e | (local_const c _ _ _) := simp_lemmas.resolve_and_add s c e | _ := do new_e ← to_expr p, s^.add new_e end private meta def simp_lemmas.append_pexprs : simp_lemmas → list pexpr → tactic simp_lemmas | s [] := return s | s (l::ls) := do new_s ← simp_lemmas.add_pexpr s l, simp_lemmas.append_pexprs new_s ls private meta def mk_simp_set (attr_names : list name) (hs : list qexpr) (ex : list name) : tactic simp_lemmas := do s₀ ← join_user_simp_lemmas attr_names, s₁ ← simp_lemmas.append_pexprs s₀ hs, return $ simp_lemmas.erase s₁ ex private meta def simp_goal (cfg : simplify_config) : simp_lemmas → tactic unit | s := do (new_target, Heq) ← target >>= simplify_core cfg s `eq, tactic.assert `Htarget new_target, swap, Ht ← get_local `Htarget, mk_eq_mpr Heq Ht >>= tactic.exact private meta def simp_hyp (cfg : simplify_config) (s : simp_lemmas) (h_name : name) : tactic unit := do h ← get_local h_name, htype ← infer_type h, (new_htype, eqpr) ← simplify_core cfg s `eq htype, tactic.assert (expr.local_pp_name h) new_htype, mk_eq_mp eqpr h >>= tactic.exact, try $ tactic.clear h private meta def simp_hyps (cfg : simplify_config) : simp_lemmas → location → tactic unit | s [] := skip | s (h::hs) := simp_hyp cfg s h >> simp_hyps s hs private meta def simp_core (cfg : simplify_config) (ctx : list expr) (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := do s ← mk_simp_set attr_names hs ids, s ← s^.append ctx, match loc : _ → tactic unit with | [] := simp_goal cfg s | _ := simp_hyps cfg s loc end, try tactic.triv, try (tactic.reflexivity_core reducible) /-- This tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. - `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. - `simp [h_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `simp without id_1 ... id_n` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id_i`s. - `simp at h` simplifies the non dependent hypothesis `h : T`. The tactic fails if the target or another hypothesis depends on `h`. - `simp with attr` simplifies the main goal target using the lemmas tagged with the attribute `[attr]`. -/ meta def simp (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := simp_core {} [] hs attr_names ids loc /-- Similar to the `simp` tactic, but uses contextual simplification. For example, when simplifying `t = s → p`, the equation `t = s` is automatically added to the set of simplification rules when simplifying `p`. -/ meta def ctx_simp (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) (loc : location) : tactic unit := simp_core {contextual := tt} [] hs attr_names ids loc /-- Similar to the `simp` tactic, but adds all applicable hypotheses as simplification rules. -/ meta def simp_using_hs (hs : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) : tactic unit := do ctx ← collect_ctx_simps, simp_core {} ctx hs attr_names ids [] private meta def dsimp_hyps (s : simp_lemmas) : location → tactic unit | [] := skip | (h::hs) := get_local h >>= dsimp_at_core s meta def dsimp (es : opt_qexpr_list) (attr_names : with_ident_list) (ids : without_ident_list) : location → tactic unit | [] := do s ← mk_simp_set attr_names es ids, tactic.dsimp_core s | hs := do s ← mk_simp_set attr_names es ids, dsimp_hyps s hs /-- This tactic applies to a goal that has the form `t ~ u` where `~` is a reflexive relation. That is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity meta def symmetry : tactic unit := tactic.symmetry meta def transitivity : tactic unit := tactic.transitivity meta def ac_reflexivity : tactic unit := tactic.ac_refl meta def ac_refl : tactic unit := tactic.ac_refl meta def cc : tactic unit := tactic.cc meta def subst (q : qexpr0) : tactic unit := to_expr q >>= tactic.subst >> try (reflexivity_core reducible) meta def clear : raw_ident_list → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env^.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env^.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) private meta def dunfold_hyps : list name → location → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= dunfold_at cs >> dunfold_hyps cs hs meta def dunfold : raw_ident_list → location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.dunfold new_cs | cs hs := do new_cs ← to_qualified_names cs, dunfold_hyps new_cs hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold : raw_ident_list → location → tactic unit := dunfold private meta def dunfold_hyps_occs : name → occurrences → location → tactic unit | c occs [] := skip | c occs (h::hs) := get_local h >>= dunfold_core_at occs [c] >> dunfold_hyps_occs c occs hs meta def dunfold_occs : ident → list nat → location → tactic unit | c ps [] := do new_c ← to_qualified_name c, tactic.dunfold_occs_of ps new_c | c ps hs := do new_c ← to_qualified_name c, dunfold_hyps_occs new_c (occurrences.pos ps) hs /- TODO(Leo): add support for non-refl lemmas -/ meta def unfold_occs : ident → list nat → location → tactic unit := dunfold_occs private meta def delta_hyps : list name → location → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_at cs >> dunfold_hyps cs hs meta def delta : raw_ident_list → location → tactic unit | cs [] := do new_cs ← to_qualified_names cs, tactic.delta new_cs | cs hs := do new_cs ← to_qualified_names cs, delta_hyps new_cs hs end interactive end tactic
e2b11ac890a4b1f73b40d835af5a9b5fc50aadfb
a45212b1526d532e6e83c44ddca6a05795113ddc
/test/finish3.lean
ab6e2fc9fba0c29f5ed78b5db5b8b56bb4bbf48d
[ "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
2,994
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Examples from the tutorial. -/ import tactic.finish open auto section variables p q r s : Prop -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := by finish example : p ∨ q ↔ q ∨ p := by finish -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := by finish example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by finish -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by finish [iff_def] example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := by finish [iff_def] -- other properties example : (p → (q → r)) ↔ (p ∧ q → r) := by finish [iff_def] example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := by finish [iff_def] example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := by finish example : ¬p ∨ ¬q → ¬(p ∧ q) := by finish example : ¬(p ∧ ¬ p) := by finish example : p ∧ ¬q → ¬(p → q) := by finish example : ¬p → (p → q) := by finish example : (¬p ∨ q) → (p → q) := by finish example : p ∨ false ↔ p := by finish example : p ∧ false ↔ false := by finish example : ¬(p ↔ ¬p) := by finish example : (p → q) → (¬q → ¬p) := by finish -- these require classical reasoning example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := by finish example : ¬(p ∧ q) → ¬p ∨ ¬q := by finish example : ¬(p → q) → p ∧ ¬q := by finish example : (p → q) → (¬p ∨ q) := by finish example : (¬q → ¬p) → (p → q) := by finish example : p ∨ ¬p := by finish example : (((p → q) → p) → p) := by finish end section variables (A : Type) (p q : A → Prop) variable a : A variable r : Prop example : (∃ x : A, r) → r := by finish -- TODO(Jeremy): can we get these automatically? example (a : A) : r → (∃ x : A, r) := begin safe; apply a_2; assumption end example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := by finish theorem foo': (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := by finish [iff_def] example (h : ∀ x, ¬ ¬ p x) : p a := by finish example (h : ∀ x, ¬ ¬ p x) : ∀ x, p x := by finish example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := by finish example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := by finish example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := by finish example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := by finish example : (∃ x, ¬ p x) → (¬ ∀ x, p x) := by finish example : (∀ x, p x → r) ↔ (∃ x, p x) → r := by finish [iff_def] -- TODO(Jeremy): can we get these automatically? example (a : A) : (∃ x, p x → r) ↔ (∀ x, p x) → r := begin safe [iff_def]; exact h a end example (a : A) : (∃ x, r → p x) ↔ (r → ∃ x, p x) := begin safe [iff_def]; exact h a end example : (∃ x, p x → r) → (∀ x, p x) → r := by finish example : (∃ x, r → p x) → (r → ∃ x, p x) := by finish end
2b58b2ad9f20dc4351ec3591c248be4b3bed46f3
1446f520c1db37e157b631385707cc28a17a595e
/src/Init/Lean/Meta/Message.lean
fde90ecc3283909fcbfba33d1999bbde6ce7c22e
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,899
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Basic namespace Lean def indentExpr (msg : MessageData) : MessageData := MessageData.nest 2 (Format.line ++ msg) namespace Meta namespace Exception private def run? {α} (ctx : ExceptionContext) (x : MetaM α) : Option α := match x { lctx := ctx.lctx, currRecDepth := 0, maxRecDepth := getMaxRecDepth ctx.opts } { env := ctx.env, mctx := ctx.mctx, ngen := { namePrefix := `_meta_exception } } with | EStateM.Result.ok a _ => some a | EStateM.Result.error _ _ => none private def inferType? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (inferType e) private def inferDomain? (ctx : ExceptionContext) (f : Expr) : Option Expr := run? ctx $ do fType ← inferType f; fType ← whnf fType; match fType with | Expr.forallE _ d _ _ => pure d | _ => throw $ Exception.other "unexpected" private def whnf? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (whnf e) def mkAppTypeMismatchMessage (f a : Expr) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ let e := mkApp f a; match inferType? ctx a, inferDomain? ctx f with | some aType, some expectedType => "application type mismatch" ++ indentExpr e ++ Format.line ++ "argument" ++ indentExpr a ++ Format.line ++ "has type" ++ indentExpr aType ++ Format.line ++ "but is expected to have type" ++ indentExpr expectedType | _, _ => "application type mismatch" ++ indentExpr e def mkLetTypeMismatchMessage (fvarId : FVarId) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ match ctx.lctx.find? fvarId with | some (LocalDecl.ldecl _ n t v b) => match inferType? ctx v with | some vType => "invalid let declaration, term" ++ indentExpr v ++ Format.line ++ "has type " ++ indentExpr vType ++ Format.line ++ "but is expected to have type" ++ indentExpr t | none => "type mismatch at let declaration for " ++ n | _ => unreachable! /-- Convert to `MessageData` that is supposed to be displayed in user-friendly error messages. -/ def toMessageData : Exception → MessageData | unknownConst c ctx => mkCtx ctx $ "unknown constant " ++ c | unknownFVar fvarId ctx => mkCtx ctx $ "unknown free variable " ++ fvarId | unknownExprMVar mvarId ctx => mkCtx ctx $ "unknown metavariable " ++ mvarId | unknownLevelMVar mvarId ctx => mkCtx ctx $ "unknown universe level metavariable " ++ mvarId | unexpectedBVar bvarIdx => "unexpected bound variable " ++ mkBVar bvarIdx | functionExpected f a ctx => mkCtx ctx $ "function expected " ++ mkApp f a | typeExpected t ctx => mkCtx ctx $ "type expected " ++ t | incorrectNumOfLevels c lvls ctx => mkCtx ctx $ "incorrect number of universe levels " ++ mkConst c lvls | invalidProjection s i e ctx => mkCtx ctx $ "invalid projection" ++ indentExpr (mkProj s i e) | revertFailure xs decl ctx => mkCtx ctx $ "revert failure" | readOnlyMVar mvarId ctx => mkCtx ctx $ "tried to update read only metavariable " ++ mkMVar mvarId | isLevelDefEqStuck u v ctx => mkCtx ctx $ "stuck at universe level constraint " ++ u ++ " =?= " ++ v | isExprDefEqStuck t s ctx => mkCtx ctx $ "stuck at constraint " ++ t ++ " =?= " ++ s | letTypeMismatch fvarId ctx => mkLetTypeMismatchMessage fvarId ctx | appTypeMismatch f a ctx => mkAppTypeMismatchMessage f a ctx | notInstance i ctx => mkCtx ctx $ "not a type class instance " ++ i | appBuilder op msg args ctx => mkCtx ctx $ "application builder failure " ++ op ++ " " ++ args ++ " " ++ msg | synthInstance inst ctx => mkCtx ctx $ "failed to synthesize" ++ indentExpr inst | tactic tacName mvarId msg ctx => mkCtx ctx $ "tactic '" ++ tacName ++ "' failed, " ++ msg ++ Format.line ++ MessageData.ofGoal mvarId | bug _ _ => "internal bug" -- TODO improve | other s => s end Exception instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (MetaM α) := ⟨fun env opts x => do match x { config := { opts := opts }, currRecDepth := 0, maxRecDepth := getMaxRecDepth opts } { env := env } with | EStateM.Result.ok a s => do s.traceState.traces.forM $ fun m => IO.println $ format m; MetaHasEval.eval s.env opts a | EStateM.Result.error err s => do s.traceState.traces.forM $ fun m => IO.println $ format m; throw (IO.userError (toString (format err.toMessageData)))⟩ end Meta namespace KernelException private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData := MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg def toMessageData (e : KernelException) (opts : Options) : MessageData := match e with | unknownConstant env constName => mkCtx env {} opts $ "(kernel) unknown constant " ++ constName | alreadyDeclared env constName => mkCtx env {} opts $ "(kernel) constant has already been declared " ++ constName | declTypeMismatch env decl givenType => let process (n : Name) (expectedType : Expr) : MessageData := "(kernel) declaration type mismatch " ++ n ++ Format.line ++ "has type" ++ indentExpr givenType ++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType; match decl with | Declaration.defnDecl { name := n, type := type, .. } => process n type | Declaration.thmDecl { name := n, type := type, .. } => process n type | _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information | declHasMVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has metavariables " ++ constName | declHasFVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has free variables " ++ constName | funExpected env lctx e => mkCtx env lctx opts $ "(kernel) function expected" ++ indentExpr e | typeExpected env lctx e => mkCtx env lctx opts $ "(kernel) type expected" ++ indentExpr e | letTypeMismatch env lctx n _ _ => mkCtx env lctx opts $ "(kernel) let-declaration type mismatch " ++ n | exprTypeMismatch env lctx e _ => mkCtx env lctx opts $ "(kernel) type mismatch at " ++ indentExpr e | appTypeMismatch env lctx e _ _ => match e with | Expr.app f a _ => "(kernel) " ++ Meta.Exception.mkAppTypeMismatchMessage f a { env := env, lctx := lctx, mctx := {}, opts := opts } | _ => "(kernel) application type mismatch at" ++ indentExpr e | invalidProj env lctx e => mkCtx env lctx opts $ "(kernel) invalid projection" ++ indentExpr e | other msg => "(kernel) " ++ msg end KernelException end Lean
80d0dbe56058f6f07702ceae99ca0f099c6fc6a2
dce2ec26258c35f21c8a5318a7a2ed297ddba7c6
/src/Problems/1_1.lean
1306a9a93bb72b9f8586c180e20928af7c0069e2
[]
no_license
nedsu/lean-category-theory-pr
c151c4f95d58a2d3b33e8f38ff7734d85d82e5ee
8d72f4645d83c72d15afaee7a2df781b952417e9
refs/heads/master
1,625,444,569,743
1,597,056,476,000
1,597,056,476,000
145,738,350
0
0
null
1,534,957,201,000
1,534,957,201,000
null
UTF-8
Lean
false
false
8,348
lean
import category_theory.isomorphism import ncategory_theory.Ndefs open category_theory open category_theory.isomorphism open category_theory.functor open tactic --delaration of universes and variables universes u v u₁ v₁ variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 -- 1a Show that identities in a category are unique theorem uniq_id (X : C) (id' : X ⟶ X) : (∀ {A : C} (g : X ⟶ A), id' ≫ g = g) → (∀ {A : C} (g : A ⟶ X), g ≫ id' = g) → (id' = 𝟙X) := begin intros hl hr, transitivity, symmetry, exact category.comp_id C id', exact hl(𝟙X) end -- 1b Show that a morphism with both a left inverse and right inverse is an isomorphism theorem landr_id (X Y Z : C) (f : X ⟶ Y) : (∃ gl : Y ⟶ X, gl ≫ f = 𝟙Y) → (∃ gr : Y ⟶ X, f ≫ gr = 𝟙X) → (is_iso' f) := begin intros, cases (classical.indefinite_description _ a) with gl hl, cases (classical.indefinite_description _ a_1) with gr hr, apply nonempty.intro (⟨gr, hr, begin simp, symmetry, exact calc 𝟙Y = gl ≫ f : eq.symm hl ... = gl ≫ 𝟙X ≫ f : by rw category.id_comp C f ... = (gl ≫ 𝟙X) ≫ f : by rw category.assoc ... = (gl ≫ (f ≫ gr)) ≫ f : by rw hr ... = ((gl ≫ f) ≫ gr) ≫ f : by rw category.assoc C gl f gr ... = (𝟙Y ≫ gr) ≫ f : by rw hl ... = gr ≫ f : by rw category.id_comp C gr end⟩ : is_iso f) end -- 1c Consider f : X ⟶ Y and g : Y ⟶ Z. Show that if two out of f, g and gf are isomorphisms,then so is the third. section Two_Out_Of_Three variables (X Y Z : C) variables (f : X ⟶ Y) (g : Y ⟶ Z) theorem tootfirsec : is_iso' f → is_iso' g → is_iso' (f ≫ g) := begin intros hf hg, apply hf.elim, apply hg.elim, intros Ig If, exact nonempty.intro ⟨Ig.1 ≫ If.1, begin simp, exact calc f ≫ g ≫ Ig.1 ≫ If.1 = f ≫ (g ≫ Ig.1) ≫ If.1 : by rw category.assoc ... = f ≫ 𝟙Y ≫ If.1 : by rw is_iso.hom_inv_id g ... = f ≫ If.1 : by rw category.id_comp ... = 𝟙X : by rw is_iso.hom_inv_id end, begin simp, exact calc Ig.1 ≫ If.1 ≫ f ≫ g = Ig.1 ≫ (If.1 ≫ f) ≫ g : by rw category.assoc ... = Ig.1 ≫ 𝟙Y ≫ g : by rw is_iso.inv_hom_id ... = Ig.1 ≫ g : by rw category.id_comp ... = 𝟙Z : by rw is_iso.inv_hom_id end⟩ end theorem tootsecthi : is_iso' g → is_iso' (f ≫ g) → is_iso' f := begin intros hg hfg, apply hg.elim, apply hfg.elim, intros Ifg Ig, exact nonempty.intro ⟨g ≫ Ifg.1, begin simp, exact calc f ≫ g ≫ Ifg.1 = (f ≫ g) ≫ Ifg.1 : by rw category.assoc ... = 𝟙X : by rw is_iso.hom_inv_id end, begin simp, exact calc g ≫ Ifg.1 ≫ f = (g ≫ Ifg.1 ≫ f) ≫ 𝟙Y : by rw category.comp_id ... = g ≫ (Ifg.1 ≫ f) ≫ 𝟙Y : by rw category.assoc ... = g ≫ Ifg.1 ≫ f ≫ 𝟙Y : by rw category.assoc ... = g ≫ Ifg.1 ≫ f ≫ g ≫ Ig.1 : by rw is_iso.hom_inv_id ... = g ≫ (Ifg.1 ≫ ((f ≫ g) ≫ Ig.1)) : by rw category.assoc ... = g ≫ (Ifg.1 ≫ (f ≫ g)) ≫ Ig.1 : by rw (category.assoc C Ifg.1 (f ≫ g) Ig.1) ... = g ≫ 𝟙Z ≫ Ig.1 : by rw is_iso.inv_hom_id ... = g ≫ Ig.1 : by rw category.id_comp ... = 𝟙Y : by rw is_iso.hom_inv_id end⟩ end theorem tootfirthi : is_iso' f → is_iso' (f ≫ g) → is_iso' g := begin intros hf hfg, apply hf.elim, apply hfg.elim, intros Ifg If, exact nonempty.intro ⟨Ifg.1 ≫ f, begin simp, exact calc g ≫ Ifg.1 ≫ f = 𝟙Y ≫ g ≫ Ifg.1 ≫ f : by rw category.id_comp ... = (If.1 ≫ f) ≫ g ≫ Ifg.1 ≫ f : by rw is_iso.inv_hom_id ... = ((If.1 ≫ f) ≫ g) ≫ Ifg.1 ≫ f : by rw (category.assoc C (If.1 ≫ f) g (Ifg.1 ≫ f)) ... = (If.1 ≫ (f ≫ g)) ≫ Ifg.1 ≫ f : by rw (category.assoc C If.1 f g) ... = If.1 ≫ (f ≫ g) ≫ Ifg.1 ≫ f : by rw category.assoc ... = If.1 ≫ ((f ≫ g) ≫ Ifg.1) ≫ f : by rw (category.assoc C (f ≫ g) Ifg.1 f) ... = If.1 ≫ 𝟙X ≫ f : by rw is_iso.hom_inv_id ... = If.1 ≫ f : by rw category.id_comp ... = 𝟙Y : by rw is_iso.inv_hom_id end, begin simp end⟩ end end Two_Out_Of_Three variables {D : Type u} [𝒟 : category.{v} D] include 𝒟 -- 1d Show functors preserve isomorphisms theorem fun_id (F : C ⥤ D) (X Y : C) (f : X ⟶ Y) : (is_iso' f) → (is_iso' (F.map f)) := begin intro hf, apply hf.elim, intro If, exact nonempty.intro /- ⟨F.map If.1, begin simp, exact calc (F.map f) ≫ (F.map If.1) = F.map (f ≫ If.1) : by rw functor.functoriality_lemma ... = F.map 𝟙X : by rw is_iso.hom_inv_id ... = 𝟙 (F X) : by rw functor.identities end, begin simp, exact calc (F.map If.1) ≫ (F.map f) = F.map (If.1 ≫ f) : by rw functor.functoriality_lemma ... = F.map 𝟙Y : by rw is_iso.inv_hom_id ... = 𝟙 (F Y) : by rw functor.identities end⟩ -/ (is_iso.of_iso (F.on_iso ⟨f , If.1, by simp, by simp⟩)) end -- 1e Show that if F : C ⥤ D is full and faithful, and F.map f : F A ⟶ F B is an isomorphism in 𝒟, then f : A ⟶ B is an isomorphism in 𝒞 theorem reflecting_isomorphisms (F : C ⥤ D) (X Y : C) (f : X ⟶ Y) : is_Full_Functor F → is_Faithful_Functor F → is_iso' (F.map f) → is_iso' f := begin intros hfu hfa hFf, apply hFf.elim, intro IFf, cases (classical.indefinite_description _ (hfu IFf.1)) with g hg, apply nonempty.intro (⟨g, begin simp, exact hfa (calc F.map (f ≫ g) = (F.map f) ≫ (F.map g) : by rw functor.map_comp ... = 𝟙(F X) : by rw [hg, is_iso.hom_inv_id] ... = F.map (𝟙X) : by rw functor.map_id ) end, begin simp, exact hfa (calc F.map (g ≫ f) = (F.map g) ≫ (F.map f) : by rw functor.map_comp ... = 𝟙(F Y) : by rw [hg, is_iso.inv_hom_id] ... = F.map (𝟙Y) : by rw functor.map_id ) end⟩ : is_iso f) end
5df48ec46e2691592477497e8ed0af14feebeceb
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/smt/ematch.lean
d8f3d4e8a49bb24bd57b0e585f82d07a55a3cc14
[ "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
7,193
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s.fold (return format.nil) (λ h tac, do hpp ← h.pp, r ← tac, if r.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic private meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas := do h ← hinst_lemma.mk_from_decl_core m h as_simp, return $ hs.add h meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add n | _ := do p ← is_prop_decl n, if p then add n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do let t := ```(caching_user_attribute hinst_lemmas), let b := if as_simp then ```(tt) else ```(ff), v ← to_expr ``({name := %%(quote attr_name), descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible %%b ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), let expected := ```(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, let t := ```(caching_user_attribute hinst_lemmas), let l1 := quote attr_names, let l2 := quote simp_attr_names, v ← to_expr ``({name := %%(quote attr_name), descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := %%l1, aux2 : list name := %%l2 in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ %%l1 ++ %%l2 } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
9f50cac76a15bc758fca397e8584c10f4c6e7bee
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/mk_inhabited_instance.lean
225a37d070ba15d100691c713d56d9218170befe
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,685
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics namespace tactic open expr environment list /- Retrieve the name of the type we are building an inhabitant instance for. -/ private meta def get_inhabited_type_name : tactic name := do { (app (const n ls) t) ← target >>= whnf, when (n ≠ `inhabited) failed, (const I ls) ← return (get_app_fn t), return I } <|> fail "mk_inhabited_instance tactic failed, target type is expected to be of the form (inhabited ...)" /- Try to synthesize constructor argument using type class resolution -/ private meta def mk_inhabited_arg : tactic unit := do tgt ← target, inh ← mk_app `inhabited [tgt], inst ← mk_instance inh, mk_app `inhabited.default [inst] >>= exact private meta def try_constructors : nat → nat → tactic unit | 0 n := failed | (i+1) n := do {constructor_idx (n - i), all_goals mk_inhabited_arg, done} <|> try_constructors i n meta def mk_inhabited_instance : tactic unit := do I ← get_inhabited_type_name, env ← get_env, let n := length (constructors_of env I), when (n = 0) (fail $ "mk_inhabited_instance failed, type '" ++ to_string I ++ "' does not have constructors"), constructor, (try_constructors n n) <|> (fail $ "mk_inhabited_instance failed, failed to build instance using all constructors of '" ++ to_string I ++ "'") end tactic
f71432949aa7496a14332998310d74006c400129
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/continued_fractions/computation/terminates_iff_rat.lean
a559d3f7650163a36dc6437c2d92a02e116c48aa
[ "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
14,325
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.approximations import algebra.continued_fractions.computation.correctness_terminating import data.rat.floor /-! # Termination of Continued Fraction Computations (`gcf.of`) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Summary We show that the continued fraction for a value `v`, as defined in `algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a rational number, that is `↑v = q` for some `q : ℚ`. ## Main Theorems - `generalized_continued_fraction.coe_of_rat` shows that `generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that `↑v = q` and `q : ℚ`. - `generalized_continued_fraction.terminates_iff_rat` shows that `generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`. ## Tags rational, continued fraction, termination -/ namespace generalized_continued_fraction open stream.seq as seq open generalized_continued_fraction (of) variables {K : Type*} [linear_ordered_field K] [floor_ring K] /- We will have to constantly coerce along our structures in the following proofs using their provided map functions. -/ local attribute [simp] pair.map int_fract_pair.mapFr section rat_of_terminates /-! ### Terminating Continued Fractions Are Rational We want to show that the computation of a continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right. We first show that every finite convergent corresponds to a rational number `q` and then use the finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to show that `v = ↑q`. -/ variables (v : K) (n : ℕ) lemma exists_gcf_pair_rat_eq_of_nth_conts_aux : ∃ (conts : pair ℚ), (of v).continuants_aux n = (conts.map coe : pair K) := nat.strong_induction_on n begin clear n, let g := of v, assume n IH, rcases n with _|_|n, -- n = 0 { suffices : ∃ (gp : pair ℚ), pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux], use (pair.mk 1 0), simp }, -- n = 1 { suffices : ∃ (conts : pair ℚ), pair.mk g.h 1 = conts.map coe, by simpa [continuants_aux], use (pair.mk ⌊v⌋ 1), simp }, -- 2 ≤ n { cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH cases s_ppred_nth_eq : (g.s.nth n) with gp_n, -- option.none { use pred_conts, have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq, simp only [this, pred_conts_eq] }, -- option.some { -- invoke the IH a second time cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1) with ppred_conts ppred_conts_eq, obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq, -- finally, unfold the recurrence to obtain the required rational value. simp only [a_eq_one, b_eq_z, (continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)], use (next_continuants 1 (z : ℚ) ppred_conts pred_conts), cases ppred_conts, cases pred_conts, simp [next_continuants, next_numerator, next_denominator] } } end lemma exists_gcf_pair_rat_eq_nth_conts : ∃ (conts : pair ℚ), (of v).continuants n = (conts.map coe : pair K) := by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) } lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (of v).numerators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩, use a, simp [num_eq_conts_a, nth_cont_eq], end lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (of v).denominators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩, use b, simp [denom_eq_conts_b, nth_cont_eq] end /-- Every finite convergent corresponds to a rational number. -/ lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (of v).convergents n = (q : K) := begin rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩, rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩, use (Aₙ / Bₙ), simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom] end variable {v} /-- Every terminating continued fraction corresponds to a rational number. -/ theorem exists_rat_eq_of_terminates (terminates : (of v).terminates) : ∃ (q : ℚ), v = ↑q := begin obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (of v).convergents n, from of_correctness_of_terminates terminates, obtain ⟨q, conv_eq_q⟩ : ∃ (q : ℚ), (of v).convergents n = (↑q : K), from exists_rat_eq_nth_convergent v n, have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q, use [q, this] end end rat_of_terminates section rat_translation /-! ### Technical Translation Lemmas Before we can show that the continued fraction of a rational number terminates, we have to prove some technical translation lemmas. More precisely, in this section, we show that, given a rational number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide. In particular, we show that ```lean (↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ) : generalized_continued_fraction K) = generalized_continued_fraction.of v` ``` in `generalized_continued_fraction.coe_of_rat`. To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in the computation first and then lift the results step-by-step. -/ /- The lifting works for arbitrary linear ordered fields with a floor function. -/ variables {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ) include v_eq_q /-! First, we show the correspondence for the very basic functions in `generalized_continued_fraction.int_fract_pair`. -/ namespace int_fract_pair lemma coe_of_rat_eq : ((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v := by simp [int_fract_pair.of, v_eq_q] lemma coe_stream_nth_rat_eq : ((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K) = int_fract_pair.stream v n := begin induction n with n IH, case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] }, case nat.succ : { rw v_eq_q at IH, cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n, case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] }, case option.some : { cases ifp_n with b fr, cases decidable.em (fr = 0) with fr_zero fr_ne_zero, { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] }, { replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by rwa [stream_q_nth_eq] at IH, have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast, have coe_of_fr := (coe_of_rat_eq this), simpa [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero] } } } end lemma coe_stream_rat_eq : ((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) = int_fract_pair.stream v := by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) } end int_fract_pair /-! Now we lift the coercion results to the continued fraction computation. -/ lemma coe_of_h_rat_eq : (↑((of q).h : ℚ) : K) = (of v).h := begin unfold of int_fract_pair.seq1, rw ←(int_fract_pair.coe_of_rat_eq v_eq_q), simp end lemma coe_of_s_nth_rat_eq : (((of q).s.nth n).map (pair.map coe) : option $ pair K) = (of v).s.nth n := begin simp only [of, int_fract_pair.seq1, seq.map_nth, seq.nth_tail], simp only [seq.nth], rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)], rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩; simp [stream.map, stream.nth, succ_nth_stream_eq] end lemma coe_of_s_rat_eq : (((of q).s).map (pair.map coe) : seq $ pair K) = (of v).s := by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl } /-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/ lemma coe_of_rat_eq : (⟨(of q).h, (of q).s.map (pair.map coe)⟩ : generalized_continued_fraction K) = of v := begin cases gcf_v_eq : (of v) with h s, subst v, obtain rfl : ↑⌊↑q⌋ = h, by { injection gcf_v_eq }, simp [coe_of_h_rat_eq rfl, coe_of_s_rat_eq rfl, gcf_v_eq] end lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) : (of v).terminates ↔ (of q).terminates := begin split; intro h; cases h with n h; use n; simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢; cases ((of q).s.nth n); trivial end end rat_translation section terminates_of_rat /-! ### Continued Fractions of Rationals Terminate Finally, we show that the continued fraction of a rational number terminates. The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `int.fract q` is smaller than the numerator of `q`. As the continued fraction computation recursively operates on the fractional part of a value `v` and `0 ≤ int.fract v < 1`, we infer that the numerator of the fractional part in the computation decreases by at least one in each step. As `0 ≤ int.fract v`, this process must stop after finite number of steps, and the computation hence terminates. -/ namespace int_fract_pair variables {q : ℚ} {n : ℕ} /-- Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of `int_fract_pair.of q⁻¹` is smaller than the numerator of `q`. -/ lemma of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) : (int_fract_pair.of q⁻¹).fr.num < q.num := rat.fract_inv_num_lt_num_of_pos q_pos /-- Shows that the sequence of numerators of the fractional parts of the stream is strictly antitone. -/ lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ} (stream_nth_eq : int_fract_pair.stream q n = some ifp_n) (stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) : ifp_succ_n.fr.num < ifp_n.fr.num := begin obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ : ∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0 ∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq, have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'), cases this, rw [←int_fract_pair.of_eq_ifp_succ_n], cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one, have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm), exact (of_inv_fr_num_lt_num_of_pos this) end lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ}, int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n := begin induction n with n IH, case nat.zero { assume ifp_zero stream_zero_eq, have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq, simp [le_refl, this.symm] }, case nat.succ { assume ifp_succ_n stream_succ_nth_eq, suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by { rw [int.coe_nat_succ, sub_add_eq_sub_sub], solve_by_elim [le_sub_right_of_add_le] }, rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, -⟩, have : ifp_succ_n.fr.num < ifp_n.fr.num, from stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq, have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this, exact (le_trans this (IH stream_nth_eq)) } end lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none := begin let fract_q_num := (int.fract q).num, let n := fract_q_num.nat_abs + 1, cases stream_nth_eq : (int_fract_pair.stream q n) with ifp, { use n, exact stream_nth_eq }, { -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional -- value is nonnegative. have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq, have : fract_q_num - n = -1, by { have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (int.fract_nonneg q), simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] }, have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n, have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left, have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this, linarith } end end int_fract_pair /-- The continued fraction of a rational number terminates. -/ theorem terminates_of_rat (q : ℚ) : (of q).terminates := exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q) ( assume n stream_nth_eq_none, exists.intro n ( have int_fract_pair.stream q (n + 1) = none, from int_fract_pair.stream_is_seq q stream_nth_eq_none, (of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) ) end terminates_of_rat /-- The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. -/ theorem terminates_iff_rat (v : K) : (of v).terminates ↔ ∃ (q : ℚ), v = (q : K) := iff.intro ( assume terminates_v : (of v).terminates, show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v ) ( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K), exists.elim exists_q_eq_v ( assume q, assume v_eq_q : v = ↑q, have (of q).terminates, from terminates_of_rat q, (of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) ) end generalized_continued_fraction
89b4e71cda3e81b147067faa76d481028f176c8d
8cd4726d66eec7673bcc0325fed07d5ba5bf17c4
/hw1.lean
a73fb968f29c7011883c889abee972b3b51b2ab1
[]
no_license
justinqcai/CS2102
8c5fddedffa6147fedd4b6ee7d5d39fc21f0ddab
d309f0db3f1df52eb77206ee1e8665a3b49d7a0c
refs/heads/master
1,590,108,991,894
1,557,610,044,000
1,557,610,044,000
186,064,169
0
0
null
null
null
null
UTF-8
Lean
false
false
1,253
lean
/- Justin Cai, jc5pz -/ section hw1 /- 1a. (10 pts) Define a binding from the name "seven" to the value 7. -/ def seven := 7 /- 1b. (10 pts) Use #check to determine the type of "seven" -/ #check seven /- 2a. (15 pts) Define a function in "C Style" (see section 2.4.6.2) called "cube" that takes a single argument, x, and returns the value x^3 -/ def cube (x: nat) : nat := x^3 /- 2b. (5 pts) Use #check to determine the type of "cube" -/ #check cube /- 3a. (15 pts) Define a function in "Lambda Style" (see section 2.4.6.1) called "cube'" that takes a single argument, x, and returns the value x^3 -/ def cube' : ℕ -> ℕ := λ x, x^3 /- 3b. (5 pts) Use #check to determine the type of "cube'" -/ #check cube' /- 4. (20 pts) First read the short sections in the notes that we skipped on "Tactic Style" development. Then replace the underscore in the following "Tactic Style" function definition to create "cube''" so that it returns the value x^3, computed using a combination of x and sq_x. -/ def cube'': ℕ → ℕ := begin assume x, have sq_x := x * x, exact x*sq_x end /- 5. (20 pts) Use #reduce three times, once with each version of the cube function to calculate 3^3. -/ #reduce cube 3 #reduce cube' 3 #reduce cube'' 3 end hw1
65e773b2eddcb241222b035e62f070d0ae576ecb
8cd4726d66eec7673bcc0325fed07d5ba5bf17c4
/hw3a.lean
ad16d3cd57041b3de7eedd25291d64f9d8a118ea
[]
no_license
justinqcai/CS2102
8c5fddedffa6147fedd4b6ee7d5d39fc21f0ddab
d309f0db3f1df52eb77206ee1e8665a3b49d7a0c
refs/heads/master
1,590,108,991,894
1,557,610,044,000
1,557,610,044,000
186,064,169
0
0
null
null
null
null
UTF-8
Lean
false
false
1,775
lean
/- Justin Cai, jc5pz /- Complete each of the following partial definitions in Lean by replacing the underscore characters with code to define functions of the specified types using lambda notation. We only care that you define some function of each required type, not what particular function you define. In preparation, note that if you hover your mouse over an underscore, Lean will tell you what type of term you is needed to fill that hole. The type that Lean requires appears after the "turnstile" symbol, |-, in the message Lean will give you. Even more interestingly, if you fill in a hole with a term of the right type that itself has one or more remaining holes, Lean will tell you what types of terms are needed to fill in those holes! You can thus fill a hole in an incremental manner, refining a partial solution at each step until all holes are filled, guided by the types that Lean tells you are needed for any given hole. We recommend that you try developing your answers in this "top-down structured" style of programming. That said, we will grade you only on your answers and not on how you developed them. -/ -/ -- 9. def hw2_1: ℕ → ℕ := λ(x: ℕ), x * x -- 10. def hw2_2: ℕ → ℕ → ℕ := λ (x: ℕ), λ (y: ℕ ), x * y -- 11. def hw2_3: (ℕ → ℕ) → (ℕ → ℕ) := λ (x: ℕ → ℕ ), λ (y: ℕ ), x y -- 12. def hw2_4: (ℕ → ℕ) → ((ℕ → ℕ) → ℕ) := λ (x: ℕ → ℕ ), λ (y: ℕ → ℕ), x (y 1) -- 13. def hw2_5: (ℕ → ℕ) → ((ℕ → ℕ) → (ℕ → ℕ)) := λ (x: ℕ → ℕ ), λ (y: ℕ → ℕ ), λ (z: ℕ ), x (y z)
1e20fc8b73396df9865589d595e76db81a4c4735
43390109ab88557e6090f3245c47479c123ee500
/src/chris_hughes_various/exponential/exponential.lean
b9679ca0795fc99cb89471bf1a78c05944408955
[ "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
23,316
lean
import tactic.norm_num data.nat.basic tactic.ring algebra.archimedean .limits data.nat.choose section a open real nat is_absolute_value finset noncomputable theory local attribute [instance, priority 0] classical.prop_decidable lemma pow_inv' {α : Type*} [discrete_field α] (a : α) (n : ℕ) : (a ^ n)⁻¹ = a⁻¹ ^ n := by induction n; simp [_root_.pow_succ, *, mul_inv', mul_comm] lemma pow_incrs_of_gt_one {α : Type*} [linear_ordered_semiring α] {x : α} {n m : ℕ} (h1x : 1 < x) (hnm : n < m) : x ^ n < x ^ m := begin rw [← nat.sub_add_cancel hnm, _root_.pow_add, _root_.pow_succ, ← mul_assoc], refine (lt_mul_iff_one_lt_left (pow_pos (lt_trans (by norm_num) h1x) _)).2 _, rw ← one_mul (1 : α), refine mul_lt_mul' (one_le_pow_of_one_le (le_of_lt h1x) _) h1x (by norm_num) (pow_pos (lt_trans (by norm_num) h1x) _) end lemma pow_dcrs_of_lt_one_of_pos {α : Type*} [discrete_linear_ordered_field α] {x : α} {n m : ℕ} (hx1 : x < 1) (h0x : 0 < x) (hnm : n < m) : x ^ m < x ^ n := begin refine (inv_lt_inv _ _).1 _, { exact pow_pos h0x _ }, { exact pow_pos h0x _ }, { rw [pow_inv', pow_inv'], refine pow_incrs_of_gt_one (one_lt_inv h0x hx1) hnm } end open finset @[simp] lemma sum_range_zero {α : Type*} [add_comm_monoid α] (f : ℕ → α) : (range 0).sum f = 0 := rfl lemma sum_range_succ {α : Type*} [add_comm_monoid α] (f : ℕ → α) (n : ℕ) : (range (succ n)).sum f = f n + (range n).sum f := by simp lemma sum_range_succ' {α : Type*} [add_comm_monoid α] (f : ℕ → α) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 | 0 := by simp | (n + 1) := by rw [sum_range_succ (λ m, f (nat.succ m)), add_assoc, ← sum_range_succ']; exact sum_range_succ _ _ /-- The binomial theorem -/ theorem add_pow {α : Type*} [comm_semiring α] (x y : α) : ∀ n : ℕ, (x + y) ^ n = (range (succ n)).sum (λ m, x ^ m * y ^ (n - m) * choose n m) | 0 := by simp | (succ n) := have h₁ : x * (x ^ n * y ^ (n - n) * choose n n) = x ^ succ n * y ^ (succ n - succ n) * choose (succ n) (succ n), by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0, by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (range n).sum (λ m, x * (x ^ m * y ^ (n - m) * choose n m) + y * (x ^ succ m * y ^ (n - succ m) * choose n (succ m))) = (range n).sum (λ m, x ^ succ m * y ^ (succ n - succ m) * ↑(choose (succ n) (succ m))), from finset.sum_congr rfl $ λ m hm, begin simp only [mul_assoc, mul_left_comm y, mul_left_comm (y ^ (n - succ m)), mul_comm y], rw [← _root_.pow_succ', add_one, ← succ_sub (mem_range.1 hm)], simp [choose_succ_succ, mul_comm, mul_assoc, mul_left_comm, add_mul, mul_add, _root_.pow_succ] end, by rw [_root_.pow_succ, add_pow, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc ((range n).sum _), ← finset.sum_add_distrib, h₁, h₂, h₃] lemma geo_series_eq {α : Type*} [field α] {x : α} (n : ℕ) (hx1 : x ≠ 1) : (range n).sum (λ m, x ^ m) = (1 - x ^ n) / (1 - x) := have 1 - x ≠ 0 := mt sub_eq_zero_iff_eq.1 hx1.symm, begin induction n with n ih, { simp }, { rw [sum_range_succ, ← mul_div_cancel (x ^ n) this, ih, ← add_div, _root_.pow_succ], refine congr_fun (congr_arg _ _) _, ring } end variables {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f (succ n) ≤ f n) : ∀ l, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end lemma is_cau_of_dcrs_bounded {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f (succ n) ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - add_monoid.smul (pred l) ε : hi.2 ... = a - add_monoid.smul l ε + ε : by conv {to_rhs, rw [← succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_incrs_bounded {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f (succ n)) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_dcrs_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma series_cau_of_abv_le_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {f : ℕ → β} {g : ℕ → α} {abv : β → α} [is_absolute_value abv] (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0,cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw abs_sub ((range (max n i)).sum g) at this, rw add_halves ε at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k,clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk,rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, rw [succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma pow_abv {α β : Type*} [discrete_linear_ordered_field α] [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, _root_.pow_succ, abv_one abv, *] lemma series_cau_of_abv_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {abv : β → α} {f : ℕ → β} [is_absolute_value abv] : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := λ h, series_cau_of_abv_le_cau 0 (λ n h, le_refl _) h lemma geo_series_cau {α β : Type*} [discrete_linear_ordered_field α] [archimedean α] [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, series_cau_of_abv_cau begin simp only [pow_abv abv, geo_series_eq _ hx1'] {eta := ff}, refine @is_cau_of_incrs_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg , refine div_le_div_of_le_of_pos (sub_le_self _ (pow_abv abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (pow_abv abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma geo_series_const_cau {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (a x : α) : abs x < 1 → is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := λ hx1, begin have : is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, geo_series_cau x hx1⟩).2, simpa only [mul_sum] using this end -- The form of ratio test with 0 ≤ r < 1, and abv (f (succ m)) ≤ r * abv (f m) handled zero terms of series the best lemma series_ratio_test {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] [archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) : 0 ≤ r → r < 1 → (∀ m, n ≤ m → abv (f (succ m)) ≤ r * abv (f m)) → is_cau_seq abv (λ m, (range m).sum f) := begin assume r0 r1 h, refine series_cau_of_abv_le_cau (succ n) _ (geo_series_const_cau (abv (f (succ n)) * r⁻¹ ^ (succ n)) r _), assume m mn, generalize hk : m - (succ n) = k,rw nat.sub_eq_iff_eq_add mn at hk, cases classical.em (r = 0) with r_zero r_pos,have m_pos := lt_of_lt_of_le (succ_pos n) mn, have := pred_le_pred mn,simp at this, have := h (pred m) this,simp[r_zero,succ_pred_eq_of_pos m_pos] at this, refine le_trans this _,refine mul_nonneg _ _, refine mul_nonneg (abv_nonneg _ _) (pow_nonneg (inv_nonneg.mpr r0) _),exact pow_nonneg r0 _, replace r_pos : 0 < r,cases lt_or_eq_of_le r0 with h h,exact h,exact absurd h.symm r_pos, revert m n, induction k with k' hi,assume m n h mn hk, rw [hk,zero_add,mul_right_comm,←pow_inv',←div_eq_mul_inv,mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm, assume m n h mn hk,rw [hk,succ_add], have kn : k' + (succ n) ≥ (succ n), rw ←zero_add (succ n),refine add_le_add _ _,exact zero_le _,simp, replace hi := hi (k' + (succ n)) n h kn rfl, rw [(by simp [_root_.pow_succ'] : r ^ (succ (k' + succ n)) = r ^ (k' + succ n) * r),←mul_assoc], replace h := h (k' + succ n) (le_of_succ_le kn),rw mul_comm at h, exact le_trans h (mul_le_mul_of_nonneg_right hi r0), rwa abs_of_nonneg r0, end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 ((nat.lt_sub_right_iff_add_lt (le_of_lt ha.1)).1 ha.2), mem_range.2 (lt_succ_of_le (le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {α β γ : Type*} [discrete_linear_ordered_field α] [ring β] (abv : β → α) [is_absolute_value abv] (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := finset.induction_on s (by simp [abv_zero abv]) $ λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _) lemma sum_nonneg {α β : Type*} [ordered_comm_monoid α] {f : β → α} {s : finset β} : (∀ x ∈ s, 0 ≤ f x) → 0 ≤ s.sum f := finset.induction_on s (by simp) $ λ a s has ih h, begin rw [sum_insert has], exact add_nonneg' (h a (by simp)) (ih (λx hx, by simp *)), end lemma neg_sum {α β : Type*} [add_comm_group α] {f : β → α} {s : finset β} : -s.sum f = s.sum (λ x, -f x) := finset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] lemma filter_true {α : Type*} (s : finset α) : s.filter (λ _, true) = s := finset.ext.2 $ by simp lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end lemma series_cauchy_prod {α β : Type*} [discrete_linear_ordered_field α] [ring β] {a b : ℕ → β} {abv : β → α} [is_absolute_value abv] : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n))) → is_cau_seq abv (λ m, (range m).sum b) → ∀ ε : α, 0 < ε → ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m))) ) < ε := begin -- slightly adapted version of theorem 9.4.7 from "The Real Numbers and Real Analysis", Ethan D. Bloch assume ha hb ε ε0, cases cau_seq.bounded ⟨_, hb⟩ with Q hQ,simp at hQ, cases cau_seq.bounded ⟨_, ha⟩ with P hP,simp at hP, have P0 : 0 < P,exact lt_of_le_of_lt (abs_nonneg _) (hP 0), have Pε0 := div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) P0), cases cau_seq.cauchy₂ ⟨_, hb⟩ Pε0 with N hN,simp at hN, have Qε0 := div_pos ε0 (mul_pos (show (4 : α) > 0, from by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), cases cau_seq.cauchy₂ ⟨_, ha⟩ Qε0 with M hM,simp at hM, existsi 2 * (max N M + 1), assume K hK, have := sum_range_diag_flip K (λ m n, a m * b n), dsimp at this, rw this, have : (λ (i : ℕ), (range (K - i)).sum (λ (k : ℕ), a i * b k)) = (λ (i : ℕ), a i * (range (K - i)).sum b), by simp [finset.mul_sum], rw this,clear this, have : (range K).sum (λ (i : ℕ), a i * (range (K - i)).sum b) = (range K).sum (λ (i : ℕ), a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), {rw ←sum_add_distrib,simp[(mul_add _ _ _).symm]}, rw this, clear this, rw sum_mul, simp, rw abv_neg abv, refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _ _) _, simp [abv_mul abv], suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { simp [(div_div_eq_div_mul _ _ _).symm] at this, rwa[div_mul_cancel _ (ne_of_lt P0).symm,(by norm_num : (4 : α) = 2 * 2),←div_div_eq_div_mul,mul_comm (2 : α),←_root_.mul_assoc, div_mul_cancel _ (ne_of_lt (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).symm,div_mul_cancel,add_halves] at this, norm_num}, refine add_lt_add _ _, {have : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * (ε / (2 * P))) := by {refine sum_le_sum _,assume m mJ,refine mul_le_mul_of_nonneg_left _ _, {refine le_of_lt (hN (K - m) K _ _),{ refine nat.le_sub_left_of_add_le (le_trans _ hK), rw[succ_mul,_root_.one_mul], exact add_le_add (le_of_lt (mem_range.1 mJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))}, {refine le_trans _ hK,rw ←_root_.one_mul N, refine mul_le_mul (by norm_num) (by rw _root_.one_mul;exact le_trans (le_max_left _ _) (le_of_lt (lt_add_one _))) (zero_le _) (zero_le _)}}, exact abv_nonneg abv _}, refine lt_of_le_of_lt this _, rw [← sum_mul, mul_comm], specialize hP (max N M + 1),rwa abs_of_nonneg at hP, exact (mul_lt_mul_left Pε0).mpr hP, exact sum_nonneg (λ x h, abv_nonneg abv _)}, {have hNMK : max N M + 1 < K := by {refine lt_of_lt_of_le _ hK, rw [succ_mul,_root_.one_mul,←add_zero (max N M + 1)], refine add_lt_add_of_le_of_lt (le_refl _) _,rw add_zero, refine add_pos_of_nonneg_of_pos (zero_le _) (by norm_num)}, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc sum (filter (λ (k : ℕ), max N M + 1 ≤ k) (range K)) (λ (i : ℕ), abv (a i) * abv (sum (range (K - i)) b - sum (range K) b)) ≤ sum (filter (λ (k : ℕ), max N M + 1 ≤ k) (range K)) (λ i, abv (a i) * (2 * Q)) : sum_le_sum (begin assume n hn, refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], refine add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < _ : begin rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)], refine (mul_lt_mul_right _).2 _, rw two_mul, refine add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)), refine lt_of_le_of_lt (le_abs_self _) _, refine hM _ _ (le_trans (le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (le_succ_of_le (le_max_right _ _)) end } end end a open nat finset lemma complex.exp_series_abs_cau (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, complex.abs (z ^ m / fact m))) := begin cases exists_nat_gt (complex.abs z) with n hn, have n_pos : (0 : ℝ) < n := lt_of_le_of_lt (complex.abs_nonneg _) hn, refine series_ratio_test n (complex.abs z / n) _ _ _,exact div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) n_pos,rwa [div_lt_iff n_pos,one_mul], assume m mn,rw [abs_of_nonneg (complex.abs_nonneg _),abs_of_nonneg (complex.abs_nonneg _)], unfold fact,simp only [_root_.pow_succ, complex.abs_div,complex.abs_mul,div_eq_mul_inv,mul_inv', nat.cast_mul,complex.abs_inv], have : complex.abs z * complex.abs (z ^ m) * ((complex.abs ↑(fact m))⁻¹ * (complex.abs ↑(succ m))⁻¹) = complex.abs z * complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹ * (complex.abs ↑(succ m))⁻¹,ring,rw this, have : complex.abs z * (↑n)⁻¹ * (complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹) = complex.abs z * complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹ * (↑n)⁻¹,ring, rw this, rw[(by simp : (succ m : ℂ) = ((succ m : ℝ) : ℂ)),complex.abs_of_nonneg], refine mul_le_mul_of_nonneg_left _ _, rw [inv_le_inv,nat.cast_le],exact le_succ_of_le mn, rw [←nat.cast_zero,nat.cast_lt],exact succ_pos _,exact n_pos,rw[←complex.abs_inv,←complex.abs_mul,←complex.abs_mul], exact complex.abs_nonneg _,rw[←nat.cast_zero,nat.cast_le],exact zero_le _, end lemma complex.exp_series_cau (z : ℂ) : is_cau_seq complex.abs (λ n, (range n).sum (λ m, z ^ m / fact m)) := series_cau_of_abv_cau (complex.exp_series_abs_cau z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨_, complex.exp_series_cau z⟩ open complex def exp (z : ℂ) : ℂ := complex.lim (exp' z) def sin (z : ℂ) : ℂ := (exp (I * z) - exp (-I * z)) / (2 * I) def cos (z : ℂ) : ℂ := (exp (I * z) + exp (-I * z)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z @[simp] lemma exp_zero : exp 0 = 1 := begin unfold exp exp', refine lim_eq_of_equiv_const _, assume ε ε0, existsi 1, assume j hj, dsimp [exp'], suffices : complex.abs (sum (range j) (λ (m : ℕ), 0 ^ m / ↑(fact m)) + -1) = 0, rwa this, cases j, { exact absurd hj (by norm_num) }, { induction j, { simpa }, { rw ← j_ih dec_trivial, simp only [sum_range_succ, _root_.pow_succ], simp } } end lemma exp_add (x y : ℂ) : exp (x + y) = exp x * exp y := show complex.lim (⟨_, complex.exp_series_cau (x + y)⟩ : cau_seq ℂ abs) = complex.lim ⇑(show cau_seq ℂ abs, from ⟨_, complex.exp_series_cau x⟩) * complex.lim (show cau_seq ℂ abs, from ⟨_, complex.exp_series_cau y⟩), begin have hxa := complex.exp_series_abs_cau x, have hx := complex.exp_series_cau x, have hy := complex.exp_series_cau y, have hxy := complex.exp_series_cau (x + y), rw complex.lim_mul_lim, have hj : ∀ j : ℕ, (range j).sum (λ (m : ℕ), (x + y) ^ m / ↑(fact m)) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / fact k * (y ^ (i - k) / fact (i - k)))), { assume j, refine finset.sum_congr rfl (λ m hm, _), rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have := choose_mul_fact_mul_fact (le_of_lt_succ $ finset.mem_range.1 hi), rw [← this, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (choose m i : ℂ), mul_assoc, mul_left_comm (choose m i : ℂ)⁻¹, mul_comm (choose m i : ℂ)], have : (choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (λ h, by have := choose_pos (le_of_lt_succ (mem_range.1 hi)); simpa [h, lt_irrefl] using this), rw inv_mul_cancel this, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] }, have hf := funext hj, have hxy1 := hxy, rw hf at hxy1, have := series_cauchy_prod hxa hy, refine eq.symm (lim_eq_lim_of_equiv _), assume ε ε0, dsimp, simp only [hj], exact this ε ε0, end
bfe5989cb568b61982dfddb15474425780482604
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Control/MonadFail.lean
877af50dff744a555eb4b93db7ff69ec2c79b774
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
601
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Lift import Init.Data.String.Basic universes u v class MonadFail (m : Type u → Type v) := (fail {} : ∀ {a}, String → m a) def matchFailed {α : Type u} {m : Type u → Type v} [MonadFail m] : m α := MonadFail.fail "match failed" instance monadFailLift (m n : Type u → Type v) [HasMonadLift m n] [MonadFail m] [Monad n] : MonadFail n := { fail := fun α s => monadLift (MonadFail.fail s : m α) }
1c410975c4286cc8dfa8b7f2b4ddac39108f13b3
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Meta/GeneralizeTelescope.lean
43e64107fce211afa53100370d0f90192381f705
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,107
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 -/ prelude import Init.Lean.Meta.KAbstract namespace Lean namespace Meta namespace GeneralizeTelescope structure Entry := (expr : Expr) (type : Expr) (modified : Bool) partial def updateTypes (e newE : Expr) : Array Entry → Nat → MetaM (Array Entry) | entries, i => if h : i < entries.size then let entry := entries.get ⟨i, h⟩; match entry with | ⟨_, type, _⟩ => do typeAbst ← kabstract type e; if typeAbst.hasLooseBVars then do let typeNew := typeAbst.instantiate1 newE; let entries := entries.set ⟨i, h⟩ { entry with type := typeNew, modified := true }; updateTypes entries (i+1) else updateTypes entries (i+1) else pure entries partial def generalizeTelescopeAux {α} (prefixForNewVars : Name) (k : Array Expr → MetaM α) : Array Entry → Nat → Nat → Array Expr → MetaM α | entries, i, nextVarIdx, fvars => if h : i < entries.size then let replace (e : Expr) (type : Expr) : MetaM α := do { let userName := prefixForNewVars.appendIndexAfter nextVarIdx; withLocalDecl userName type BinderInfo.default $ fun x => do entries ← updateTypes e x entries (i+1); generalizeTelescopeAux entries (i+1) (nextVarIdx+1) (fvars.push x) }; match entries.get ⟨i, h⟩ with | ⟨e@(Expr.fvar fvarId _), type, false⟩ => do localDecl ← getLocalDecl fvarId; match localDecl with | LocalDecl.cdecl _ _ _ _ _ => generalizeTelescopeAux entries (i+1) nextVarIdx (fvars.push e) | LocalDecl.ldecl _ _ _ _ _ => replace e type | ⟨e, type, modified⟩ => do when modified $ unlessM (isTypeCorrect type) $ throwEx $ Exception.generalizeTelescope (entries.map Entry.expr); replace e type else k fvars end GeneralizeTelescope open GeneralizeTelescope /-- Given expressions `es := #[e_1, e_2, ..., e_n]`, execute `k` with the free variables `(x_1 : A_1) (x_2 : A_2 [x_1]) ... (x_n : A_n [x_1, ... x_{n-1}])`. Moreover, - type of `e_1` is definitionally equal to `A_1`, - type of `e_2` is definitionally equal to `A_2[e_1]`. - ... - type of `e_n` is definitionally equal to `A_n[e_1, ..., e_{n-1}]`. This method tries to avoid the creation of new free variables. For example, if `e_i` is a free variable `x_i` and it is not a let-declaration variable, and its type does not depend on previous `e_j`s, the method will just use `x_i`. The telescope `x_1 ... x_n` can be used to create lambda and forall abstractions. Moreover, for any type correct lambda abstraction `f` constructed using `mkForall #[x_1, ..., x_n] ...`, The application `f e_1 ... e_n` is also type correct. The parameter `prefixForNewVars` is used to create new user facing names for the (new) variables `x_i`. The `kabstract` method is used to "locate" and abstract forward dependencies. That is, an occurrence of `e_i` in the of `e_j` for `j > i`. The method checks whether the abstract types `A_i` are type correct. Here is an example where `generalizeTelescope` fails to create the telescope `x_1 ... x_n`. Assume the local context contains `(n : Nat := 10) (xs : Vec Nat n) (ys : Vec Nat 10) (h : xs = ys)`. Then, assume we invoke `generalizeTelescope` with `es := #[10, xs, ys, h]` and `prefixForNewVars := aux`. A type error is detected when processing `h`'s type. At this point, the method had successfully produced ``` (aux_1 : Nat) (xs : Vec Nat n) (aux_2 : Vec Nat aux_1) ``` and the type for the new variable abstracting `h` is `xs = aux_2` which is not type correct. -/ def generalizeTelescope {α} (es : Array Expr) (prefixForNewVars : Name) (k : Array Expr → MetaM α) : MetaM α := do es ← es.mapM $ fun e => do { type ← inferType e; type ← instantiateMVars type; pure { expr := e, type := type, modified := false : Entry } }; generalizeTelescopeAux prefixForNewVars k es 0 1 #[] end Meta end Lean
c662c1f6f20c80fa007268d6ed3c03ff5531c732
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/PreDefinition/Structural/BRecOn.lean
2cbd5be35430c62620fa317f1de4631353d79e6f
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
9,987
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.Match import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta private def throwToBelowFailed : MetaM α := throwError "toBelow failed" /- See toBelow -/ private partial def toBelowAux (C : Expr) : Expr → Expr → Expr → MetaM Expr | belowDict, arg, F => do let belowDict ← whnf belowDict trace[Elab.definition.structural] "belowDict: {belowDict}, arg: {arg}" match belowDict with | Expr.app (Expr.app (Expr.const `PProd _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `PProd.fst #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `PProd.snd #[F])) | Expr.app (Expr.app (Expr.const `And _ _) d1 _) d2 _ => (do toBelowAux C d1 arg (← mkAppM `And.left #[F])) <|> (do toBelowAux C d2 arg (← mkAppM `And.right #[F])) | _ => forallTelescopeReducing belowDict fun xs belowDict => do let argArgs := arg.getAppArgs unless argArgs.size >= xs.size do throwToBelowFailed let n := argArgs.size let argTailArgs := argArgs.extract (n - xs.size) n let belowDict := belowDict.replaceFVars xs argTailArgs match belowDict with | Expr.app belowDictFun belowDictArg _ => unless belowDictFun.getAppFn == C do throwToBelowFailed unless ← isDefEq belowDictArg arg do throwToBelowFailed pure (mkAppN F argTailArgs) | _ => throwToBelowFailed /- See toBelow -/ private def withBelowDict (below : Expr) (numIndParams : Nat) (k : Expr → Expr → MetaM α) : MetaM α := do let belowType ← inferType below trace[Elab.definition.structural] "belowType: {belowType}" belowType.withApp fun f args => do let motivePos := numIndParams + 1 unless motivePos < args.size do throwError "unexpected 'below' type{indentExpr belowType}" let pre := mkAppN f (args.extract 0 numIndParams) let preType ← inferType pre forallBoundedTelescope preType (some 1) fun x _ => do let motiveType ← inferType x[0] let C ← mkFreshUserName `C withLocalDeclD C motiveType fun C => let belowDict := mkApp pre C let belowDict := mkAppN belowDict (args.extract (numIndParams + 1) args.size) k C belowDict /- `below` is a free variable with type of the form `I.below indParams motive indices major`, where `I` is the name of an inductive datatype. For example, when trying to show that the following function terminates using structural recursion ```lean def addAdjacent : List Nat → List Nat | [] => [] | [a] => [a] | a::b::as => (a+b) :: addAdjacent as ``` when we are visiting `addAdjacent as` at `replaceRecApps`, `below` has type `@List.below Nat (fun (x : List Nat) => List Nat) (a::b::as)` The motive `fun (x : List Nat) => List Nat` depends on the actual function we are trying to compute. So, we first replace it with a fresh variable `C` at `withBelowDict`. Recall that `brecOn` implements course-of-values recursion, and `below` can be viewed as a dictionary of the "previous values". We search this dictionary using the auxiliary function `toBelowAux`. The dictionary is built using the `PProd` (`And` for inductive predicates). We keep searching it until we find `C recArg`, where `C` is the auxiliary fresh variable created at `withBelowDict`. -/ private partial def toBelow (below : Expr) (numIndParams : Nat) (recArg : Expr) : MetaM Expr := do withBelowDict below numIndParams fun C belowDict => toBelowAux C belowDict recArg below private partial def replaceRecApps (recFnName : Name) (recArgInfo : RecArgInfo) (below : Expr) (e : Expr) : M Expr := let rec loop (below : Expr) (e : Expr) : M Expr := do match e with | Expr.lam n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkLambdaFVars #[x] (← loop below (b.instantiate1 x)) | Expr.forallE n d b c => withLocalDecl n c.binderInfo (← loop below d) fun x => do mkForallFVars #[x] (← loop below (b.instantiate1 x)) | Expr.letE n type val body _ => withLetDecl n (← loop below type) (← loop below val) fun x => do mkLetFVars #[x] (← loop below (body.instantiate1 x)) | Expr.mdata d e _ => return mkMData d (← loop below e) | Expr.proj n i e _ => return mkProj n i (← loop below e) | Expr.app _ _ _ => let processApp (e : Expr) : M Expr := e.withApp fun f args => do if f.isConstOf recFnName then let numFixed := recArgInfo.fixedParams.size let recArgPos := recArgInfo.fixedParams.size + recArgInfo.pos if recArgPos >= args.size then throwError "insufficient number of parameters at recursive application {indentExpr e}" let recArg := args[recArgPos] -- For reflexive type, we may have nested recursive applications in recArg let recArg ← loop below recArg let f ← try toBelow below recArgInfo.indParams.size recArg catch _ => throwError "failed to eliminate recursive application{indentExpr e}" -- Recall that the fixed parameters are not in the scope of the `brecOn`. So, we skip them. let argsNonFixed := args.extract numFixed args.size -- The function `f` does not explicitly take `recArg` and its indices as arguments. So, we skip them too. let mut fArgs := #[] for i in [:argsNonFixed.size] do if recArgInfo.pos != i && !recArgInfo.indicesPos.contains i then let arg := argsNonFixed[i] let arg ← replaceRecApps recFnName recArgInfo below arg fArgs := fArgs.push arg return mkAppN f fArgs else return mkAppN (← loop below f) (← args.mapM (loop below)) let matcherApp? ← matchMatcherApp? e match matcherApp? with | some matcherApp => if !recArgHasLooseBVarsAt recFnName recArgInfo.recArgPos e then processApp e else /- Here is an example we currently not handle ``` def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 1 | _::_::zs => g zs + 1 | zs => g ys + 2 ``` We are matching on `ys`, but still using `ys` in the third alternative. If we push the `below` argument over the dependent match it will be able to eliminate recursive call using `zs`. To make it work, users have to write the third alternative as `| zs => g zs + 2` If this is too annoying in practice, we may replace `ys` with the matching term, but this may generate weird error messages, when it doesn't work. -/ trace[Elab.definition.structural] "below before matcherApp.addArg: {below} : {← inferType below}" let matcherApp ← mapError (matcherApp.addArg below) (fun msg => "failed to add `below` argument to 'matcher' application" ++ indentD msg) let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) => lambdaTelescope alt fun xs altBody => do trace[Elab.definition.structural] "altNumParams: {numParams}, xs: {xs}" unless xs.size >= numParams do throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}" let belowForAlt := xs[numParams - 1] mkLambdaFVars xs (← loop belowForAlt altBody) pure { matcherApp with alts := altsNew }.toExpr | none => processApp e | e => ensureNoRecFn recFnName e loop below e def mkBRecOn (recFnName : Name) (recArgInfo : RecArgInfo) (value : Expr) : M Expr := do let type := (← inferType value).headBeta let major := recArgInfo.ys[recArgInfo.pos] let otherArgs := recArgInfo.ys.filter fun y => y != major && !recArgInfo.indIndices.contains y trace[Elab.definition.structural] "fixedParams: {recArgInfo.fixedParams}, otherArgs: {otherArgs}" let motive ← mkForallFVars otherArgs type let mut brecOnUniv ← getLevel motive trace[Elab.definition.structural] "brecOn univ: {brecOnUniv}" let useBInductionOn := recArgInfo.reflexive && brecOnUniv == levelZero if recArgInfo.reflexive && brecOnUniv != levelZero then brecOnUniv ← decLevel brecOnUniv let motive ← mkLambdaFVars (recArgInfo.indIndices.push major) motive trace[Elab.definition.structural] "brecOn motive: {motive}" let brecOn := if useBInductionOn then Lean.mkConst (mkBInductionOnName recArgInfo.indName) recArgInfo.indLevels else Lean.mkConst (mkBRecOnName recArgInfo.indName) (brecOnUniv :: recArgInfo.indLevels) let brecOn := mkAppN brecOn recArgInfo.indParams let brecOn := mkApp brecOn motive let brecOn := mkAppN brecOn recArgInfo.indIndices let brecOn := mkApp brecOn major check brecOn let brecOnType ← inferType brecOn trace[Elab.definition.structural] "brecOn {brecOn}" trace[Elab.definition.structural] "brecOnType {brecOnType}" forallBoundedTelescope brecOnType (some 1) fun F _ => do let F := F[0] let FType ← inferType F trace[Elab.definition.structural] "FType: {FType}" let FType ← instantiateForall FType recArgInfo.indIndices let FType ← instantiateForall FType #[major] forallBoundedTelescope FType (some 1) fun below _ => do let below := below[0] let valueNew ← replaceRecApps recFnName recArgInfo below value let Farg ← mkLambdaFVars (recArgInfo.indIndices ++ #[major, below] ++ otherArgs) valueNew let brecOn := mkApp brecOn Farg return mkAppN brecOn otherArgs end Lean.Elab.Structural
7779c6b5de4d18aee5e7dd0575a5d3fc347e90ea
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/Reid1.lean
a8f860b1eb73b9abe704128613be7f14d427b964
[ "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
701
lean
new_frontend structure ConstantFunction (α β : Type) := (f : α → β) (h : ∀ a₁ a₂, f a₁ = f a₂) instance constFunCoe {α β : Type} : CoeFun (ConstantFunction α β) (fun _ => α → β) := { coe := fun c => c.f } def myFun {α : Type} : ConstantFunction α (Option α) := { f := fun a => none, h := fun a₁ a₂ => rfl } def myFun' (α : Type) : ConstantFunction α (Option α) := { f := fun a => none, h := fun a₁ a₂ => rfl } set_option pp.all true #check myFun 3 -- works #check @myFun Nat 3 -- works #check myFun' _ 3 -- works #check myFun' Nat 3 -- works variable (c : ConstantFunction Nat Nat) #check c 3 -- works #check (fun c => c 3) myFun -- works
60658611821400c0cb1f840b78e6b2f23bdcc219
c5e5ea6e7fc63b895c31403f68dd2f7255916f14
/src/entrypoint.lean
689b233ad95ab69117e2c4406571ea84c5e58a61
[ "Apache-2.0", "OFL-1.1" ]
permissive
leanprover-community/doc-gen
c974f9d91ef6c1c51bbcf8e4b9cc9aa7cfb72307
097cc0926bb86982318cabde7e7cc7d5a4c3a9e4
refs/heads/master
1,679,268,657,882
1,677,623,140,000
1,677,623,140,000
223,945,837
20
20
Apache-2.0
1,693,407,722,000
1,574,685,636,000
Python
UTF-8
Lean
false
false
135
lean
import all import .export_json open_all_locales -- note that `main` is executed by `lean --run`, which handles stderr vs stdout better
d22d1973254ab3b3c7311ac3264cb3f8ae3380d4
4727251e0cd73359b15b664c3170e5d754078599
/src/data/qpf/multivariate/constructions/const.lean
113adf4a31bb3012ac0b762cb5e6da09f97848c8
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,914
lean
/- Copyright (c) 2020 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor.multivariate import data.qpf.multivariate.basic /-! # Constant functors are QPFs Constant functors map every type vectors to the same target type. This is a useful device for constructing data types from more basic types that are not actually functorial. For instance `const n nat` makes `nat` into a functor that can be used in a functor-based data type specification. -/ universes u namespace mvqpf open_locale mvfunctor variables (n : ℕ) /-- Constant multivariate functor -/ @[nolint unused_arguments] def const (A : Type*) (v : typevec.{u} n) : Type* := A instance const.inhabited {A α} [inhabited A] : inhabited (const n A α) := ⟨ (default : A) ⟩ namespace const open mvfunctor mvpfunctor variables {n} {A : Type u} {α β : typevec.{u} n} (f : α ⟹ β) /-- Constructor for constant functor -/ protected def mk (x : A) : (const n A) α := x /-- Destructor for constant functor -/ protected def get (x : (const n A) α) : A := x @[simp] protected lemma mk_get (x : (const n A) α) : const.mk (const.get x) = x := rfl @[simp] protected lemma get_mk (x : A) : const.get (const.mk x : const n A α) = x := rfl /-- `map` for constant functor -/ protected def map : (const n A) α → (const n A) β := λ x, x instance : mvfunctor (const n A) := { map := λ α β f, const.map } lemma map_mk (x : A) : f <$$> const.mk x = const.mk x := rfl lemma get_map (x : (const n A) α) : const.get (f <$$> x) = const.get x := rfl instance mvqpf : @mvqpf _ (const n A) (mvqpf.const.mvfunctor) := { P := mvpfunctor.const n A, abs := λ α x, mvpfunctor.const.get x, repr := λ α x, mvpfunctor.const.mk n x, abs_repr := by intros; simp, abs_map := by intros; simp; refl, } end const end mvqpf
c6575a4da937a51d5e6a40cb8c08e3ddc2f24cfc
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/meta/expr.lean
91594263e1d5e2a7a3f4efd24d1b82ad75458c68
[ "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
46,435
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, Floris van Doorn -/ import data.string.defs import meta.rb_map import 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 @[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α := ⟨λ b, pexpr.of_expr (reflect b)⟩ 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 /-- Auxiliary 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 /-- Auxiliary 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 /-- Update the last component of a name. -/ def update_last (f : string → string) : name → name | (mk_string s n) := mk_string (f s) n | n := n /-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`, either as prefix or as suffix (specified by `is_prefix`), separated by `_`. Used by `simps_add_projections`. -/ def append_to_last (nm : name) (s : string) (is_prefix : bool) : name := nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s /-- 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 (= '.') /-- In surface Lean, we can write anonymous Π binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type | intro : unit → test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `ᾰ`: ```lean test.intro : ∀ (ᾰ : unit), test ``` When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type | intro : ∀ (ᾰ : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `ᾰ`, `ᾰ_1`, etc. -/ library_note "likely generated binder names" /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_simple_name : string → bool | "ᾰ" := tt | n := match n.get_rest "ᾰ_" with | none := ff | some suffix := suffix.is_nat end /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_name (n : name) : bool := match n with | mk_string s anonymous := is_likely_generated_binder_simple_name s | _ := ff end 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 /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f /-- `l.params` is the set of parameters occuring in `l`. For example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`. -/ protected meta def params (u : level) : name_set := u.fold mk_name_set $ λ v l, match v with | (param nm) := l.insert nm | _ := l end 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) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) 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 /-- Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`. -/ protected meta def to_list {α} (f : expr → option α) : expr → option (list α) | `(list.nil) := some [] | `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list | _ := none /-- `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 /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `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 /-- Implementation of `expr.mreplace`. -/ meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) : expr → ℕ → m expr | (app f x) n := option.mget_or_else (R (app f x) n) (do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx) | (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd) | (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd) | (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n) (do Rty ← mreplace_aux ty n, Ra ← mreplace_aux a n, Rb ← mreplace_aux b n, return $ elet nm Rty Ra Rb) | (macro c es) n := option.mget_or_else (R (macro c es) n) $ macro c <$> es.mmap (λ e, mreplace_aux e n) | e n := option.mget_or_else (R e n) (return e) /-- Monadic analogue of `expr.replace`. The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where `n` is the number of binders above `e`. If `R s n` fails, the whole replacement fails. If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit its subexpressions). If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`. WARNING: This function performs exponentially worse on large terms than `expr.replace`, if a subexpression occurs more than once in an expression, `expr.replace` visits them only once, but this function will visit every occurence of it. Do not use this on large expressions. -/ meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) : m expr := mreplace_aux R e 0 /-- Match a variable. -/ meta def match_var {elab} : expr elab → option ℕ | (var n) := some n | _ := none /-- Match a sort. -/ meta def match_sort {elab} : expr elab → option level | (sort u) := some u | _ := none /-- Match a constant. -/ meta def match_const {elab} : expr elab → option (name × list level) | (const n lvls) := some (n, lvls) | _ := none /-- Match a metavariable. -/ meta def match_mvar {elab} : expr elab → option (name × name × expr elab) | (mvar unique pretty type) := some (unique, pretty, type) | _ := none /-- Match a local constant. -/ meta def match_local_const {elab} : expr elab → option (name × name × binder_info × expr elab) | (local_const unique pretty bi type) := some (unique, pretty, bi, type) | _ := none /-- Match an application. -/ meta def match_app {elab} : expr elab → option (expr elab × expr elab) | (app t u) := some (t, u) | _ := none /-- Match an application of `coe_fn`. -/ meta def match_app_coe_fn : expr → option (expr × expr × expr × expr) | (app `(@coe_fn %%α %%inst %%fexpr) x) := some (α, inst, fexpr, x) | _ := none /-- Match an abstraction. -/ meta def match_lam {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (lam var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a Π type. -/ meta def match_pi {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (pi var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a let. -/ meta def match_elet {elab} : expr elab → option (name × expr elab × expr elab × expr elab) | (elet var_name type assignment body) := some (var_name, type, assignment, body) | _ := none /-- Match a macro. -/ meta def match_macro {elab} : expr elab → option (macro_def × list (expr elab)) | (macro df args) := some (df, args) | _ := none /-- 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 /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- 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 the set of all local constants in an expression. -/ meta def list_local_consts' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es) /-- Returns the unique names of all local constants in an expression. -/ meta def list_local_const_unique_names (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name 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) /-- Returns the set of all meta-variables in an expression. -/ meta def list_meta_vars' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- 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) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `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 × name_set) := 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 /-- 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 /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst 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. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ 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 /-- Auxiliary 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) /-- Auxiliary 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 | (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 /-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`. Does not check whether the result remains type-correct. -/ meta def instantiate_pis : list expr → expr → expr | (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v) | _ e := e /-- `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 /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff /-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier. This also works if `x1, ... xn` contain free variables. -/ protected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do (@const tt n ls, es) ← return e.get_app_fn_args | exceptional.fail "expression is not a constant applied to arguments", d ← env.get n, return $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls /-- Auxilliary function for `head_eta_expand`. -/ meta def head_eta_expand_aux : ℕ → expr → expr → expr | (n+1) e (pi x bi d b) := lam x bi d $ head_eta_expand_aux n e b | _ e _ := e /-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained by its type `t`. -/ meta def head_eta_expand (n : ℕ) (e t : expr) : expr := ((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t /-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in `dict`. They are expanded until they are applied to one more argument than the maximum in `dict.find n`. -/ protected meta def eta_expand (env : environment) (dict : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, do let (e0, es) := e.get_app_fn_args, let ns := (dict.find e0.const_name).iget, guard (bnot ns.empty), let e' := e0.mk_app $ es.map eta_expand, let needed_n := ns.foldr max 0 + 1, if needed_n ≤ es.length then some e' else do e'_type ← (e'.simple_infer_type env).to_option, some $ head_eta_expand (needed_n - es.length) e' e'_type /-- `e.apply_replacement_fun f test` applies `f` to each identifier (inductive type, defined function etc) in an expression, unless * The identifier occurs in an application with first argument `arg`; and * `test arg` is false. However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f` is tested, instead of the first argument. Reorder contains the information about what arguments to reorder: e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorder.find g = some [1]`. We assume that all functions where we want to reorder arguments are fully applied. This can be done by applying `expr.eta_expand` first. -/ protected meta def apply_replacement_fun (f : name → name) (test : expr → bool) (relevant : name_map ℕ) (reorder : name_map $ list ℕ) : expr → expr | e := e.replace $ λ e _, match e with | const n ls := some $ const (f n) $ -- if the first two arguments are reordered, we also reorder the first two universe parameters if 1 ∈ (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls | app g x := let f := g.get_app_fn, nm := f.const_name, n_args := g.get_app_num_args in -- this might be inefficient if n_args ∈ (reorder.find nm).iget ∧ test g.get_app_args.head then -- interchange `x` and the last argument of `g` some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $ apply_replacement_fun g.app_arg else if n_args = (relevant.find nm).lhoare 0 ∧ f.is_constant ∧ ¬ test x then some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else none | _ := none end end expr /-! ### Declarations about `environment` -/ namespace environment /-- 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 resulting 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 /-- `declaration.update_with_fun f test tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and `expr.apply_replacement_fun` to the value and type of `decl`. -/ protected meta def update_with_fun (env : environment) (f : name → name) (test : expr → bool) (relevant : name_map ℕ) (reorder : name_map $ list ℕ) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ (decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in decl.update_value $ (decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder /-- 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 /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
952ae74858ae09d122ddd2b474aea48c121d97de
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/prime_spectrum/maximal.lean
4cbe42e75ea5ce70f95a8753058789082f32301c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,310
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import algebraic_geometry.prime_spectrum.basic import ring_theory.localization.as_subring /-! # Maximal spectrum of a commutative ring > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The maximal spectrum of a commutative ring is the type of all maximal ideals. It is naturally a subset of the prime spectrum endowed with the subspace topology. ## Main definitions * `maximal_spectrum R`: The maximal spectrum of a commutative ring `R`, i.e., the set of all maximal ideals of `R`. ## Implementation notes The Zariski topology on the maximal spectrum is defined as the subspace topology induced by the natural inclusion into the prime spectrum to avoid API duplication for zero loci. -/ noncomputable theory open_locale classical universes u v variables (R : Type u) [comm_ring R] /-- The maximal spectrum of a commutative ring `R` is the type of all maximal ideals of `R`. -/ @[ext] structure maximal_spectrum := (as_ideal : ideal R) (is_maximal : as_ideal.is_maximal) attribute [instance] maximal_spectrum.is_maximal variable {R} namespace maximal_spectrum instance [nontrivial R] : nonempty $ maximal_spectrum R := let ⟨I, hI⟩ := ideal.exists_maximal R in ⟨⟨I, hI⟩⟩ /-- The natural inclusion from the maximal spectrum to the prime spectrum. -/ def to_prime_spectrum (x : maximal_spectrum R) : prime_spectrum R := ⟨x.as_ideal, x.is_maximal.is_prime⟩ lemma to_prime_spectrum_injective : (@to_prime_spectrum R _).injective := λ ⟨_, _⟩ ⟨_, _⟩ h, by simpa only [mk.inj_eq] using (prime_spectrum.ext_iff _ _).mp h open prime_spectrum set lemma to_prime_spectrum_range : set.range (@to_prime_spectrum R _) = {x | is_closed ({x} : set $ prime_spectrum R)} := begin simp only [is_closed_singleton_iff_is_maximal], ext ⟨x, _⟩, exact ⟨λ ⟨y, hy⟩, hy ▸ y.is_maximal, λ hx, ⟨⟨x, hx⟩, rfl⟩⟩ end /-- The Zariski topology on the maximal spectrum of a commutative ring is defined as the subspace topology induced by the natural inclusion into the prime spectrum. -/ instance zariski_topology : topological_space $ maximal_spectrum R := prime_spectrum.zariski_topology.induced to_prime_spectrum instance : t1_space $ maximal_spectrum R := ⟨λ x, is_closed_induced_iff.mpr ⟨{to_prime_spectrum x}, (is_closed_singleton_iff_is_maximal _).mpr x.is_maximal, by simpa only [← image_singleton] using preimage_image_eq {x} to_prime_spectrum_injective⟩⟩ lemma to_prime_spectrum_continuous : continuous $ @to_prime_spectrum R _ := continuous_induced_dom variables (R) [is_domain R] (K : Type v) [field K] [algebra R K] [is_fraction_ring R K] /-- An integral domain is equal to the intersection of its localizations at all its maximal ideals viewed as subalgebras of its field of fractions. -/ theorem infi_localization_eq_bot : (⨅ v : maximal_spectrum R, localization.subalgebra.of_field K _ v.as_ideal.prime_compl_le_non_zero_divisors) = ⊥ := begin ext x, rw [algebra.mem_bot, algebra.mem_infi], split, { apply imp_of_not_imp_not, intros hrange hlocal, let denom : ideal R := (submodule.span R {1} : submodule R K).colon (submodule.span R {x}), have hdenom : (1 : R) ∉ denom := begin intro hdenom, rcases submodule.mem_span_singleton.mp (submodule.mem_colon.mp hdenom x $ submodule.mem_span_singleton_self x) with ⟨y, hy⟩, exact hrange ⟨y, by rw [← mul_one $ algebra_map R K y, ← algebra.smul_def, hy, one_smul]⟩ end, rcases denom.exists_le_maximal (λ h, (h ▸ hdenom) submodule.mem_top) with ⟨max, hmax, hle⟩, rcases hlocal ⟨max, hmax⟩ with ⟨n, d, hd, rfl⟩, apply hd (hle $ submodule.mem_colon.mpr $ λ _ hy, _), rcases submodule.mem_span_singleton.mp hy with ⟨y, rfl⟩, exact submodule.mem_span_singleton.mpr ⟨y * n, by rw [algebra.smul_def, mul_one, map_mul, smul_comm, algebra.smul_def, algebra.smul_def, mul_comm $ algebra_map R K d, inv_mul_cancel_right₀ $ (map_ne_zero_iff _ $ no_zero_smul_divisors.algebra_map_injective R K).mpr $ λ h, (h ▸ hd) max.zero_mem]⟩ }, { rintro ⟨y, rfl⟩ ⟨v, hv⟩, exact ⟨y, 1, v.ne_top_iff_one.mp hv.ne_top, by rw [map_one, inv_one, mul_one]⟩ } end end maximal_spectrum namespace prime_spectrum variables (R) [is_domain R] (K : Type v) [field K] [algebra R K] [is_fraction_ring R K] /-- An integral domain is equal to the intersection of its localizations at all its prime ideals viewed as subalgebras of its field of fractions. -/ theorem infi_localization_eq_bot : (⨅ v : prime_spectrum R, localization.subalgebra.of_field K _ $ v.as_ideal.prime_compl_le_non_zero_divisors) = ⊥ := begin ext x, rw [algebra.mem_infi], split, { rw [← maximal_spectrum.infi_localization_eq_bot, algebra.mem_infi], exact λ hx ⟨v, hv⟩, hx ⟨v, hv.is_prime⟩ }, { rw [algebra.mem_bot], rintro ⟨y, rfl⟩ ⟨v, hv⟩, exact ⟨y, 1, v.ne_top_iff_one.mp hv.ne_top, by rw [map_one, inv_one, mul_one]⟩ } end end prime_spectrum
2819be134f0e7194590cf22afc42644848327277
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/mutwf1.lean
aa7886e1cb8e0f8cf66685de4a7ac3bbe8a8e8d4
[ "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
951
lean
namespace Ex1 mutual def f : Nat → Bool → Nat | n, true => 2 * f n false | 0, false => 1 | n, false => n + g n def g (n : Nat) : Nat := if h : n ≠ 0 then f (n-1) true else n end termination_by' invImage (fun | PSum.inl ⟨n, true⟩ => (n, 2) | PSum.inl ⟨n, false⟩ => (n, 1) | 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.pred_lt | apply Prod.Lex.right decide done -- should fail end Ex1 namespace Ex2 mutual def f : Nat → Bool → Nat | n, true => 2 * f n false | 0, false => 1 | n, false => n + g (n+1) -- Error def g (n : Nat) : Nat := if h : n ≠ 0 then f (n-1) true else n end termination_by f n b => (n, if b then 2 else 1) g n => (n, 0) end Ex2
4db506f6b056c32ce793d36a34bf3b7a6de411b7
69bc7d0780be17e452d542a93f9599488f1c0c8e
/9-17-2019.lean
eaaeba93d43ef2cf42ada192495274459fb1cbe6
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
2,730
lean
/- Kinds of terms that we've encountered thus far: - literal terms, including lambda abstractions - identifier terms - application expressions Terms are syntactic expressions that represent values. How do we get from a term to its value? Evaluation. (This should all be familiar and already be in the notes) In a language like Lean, all values have types. -/ /- Lean's standard library provides implementations with a set of built-in types like nat, bool, or string. -/ #check nat -- ℕ is of type Type /- How might we define types like bool, etc. without a standard library? -/ namespace ex1 -- In general, the constructors of some datatype are functions that take arguments. -- But we don't necessarily *need* to take arguments. inductive mybool : Type | ttt : mybool -- here, ttt and fff are constructors of unique values. In more precise terms, constructors are *injective.* | fff : mybool -- this is Lean's concept of an enumerated type (enum in java, rust, etc., etc.) -- note that this is an exhaustive list: mybool is defined as either being ttt or fff -- injective functions ensure that each distinct x produces a distinct y. open mybool def neg_mybool : mybool → mybool := λ (b : mybool), match b with | ttt := fff | fff := ttt end def neg_mybool'' : mybool → mybool | ttt := fff | fff := ttt end ex1 namespace foo def x := 5 -- foo.x namespace bar def x := 6 -- foo.bar.x #eval x -- refers to foo.bar.x end bar #eval x -- refers to foo.x end foo #eval foo.x #eval foo.bar.x open foo #eval x /- Referential transparency - we can replace any kind of reference with its value without changing the functionality Pure functions have referential transparency—we can always replace (+ 3 4) with 7.#check If our + function somehow was non-pure and wasn't guaranteed to return 7 when (+ 3 4) is called, we lose referential transparency. -/ inductive day : Type | sunday : day | monday : day | tuesday : day | wednesday : day | thursday : day | friday : day | saturday : day open day def myrepr : day → string | sunday := "sunday" | monday := "monday" | tuesday := "tuesday" | wednesday := "wednesday" | thursday := "thursday" | friday := "friday" | saturday := "saturday" def next_day : day → day | sunday := monday | monday := tuesday | tuesday := wednesday | wednesday := thursday | thursday := friday | friday := saturday | saturday := sunday def is_weekday : day → bool | sunday := ff | saturday := ff | _ := tt inductive mynat | zero : mynat | succ : mynat → mynat -- give me the succ, kevin sullivan. -- reductive types #reduce (mynat.succ (mynat.succ mynat.zero))
e80a37f7269617c4ba928763f56b0d588b0d61e3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/hausdorff_distance.lean
07e80930c57275ec23029e6ecf56a4edec43f7f5
[ "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
64,214
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.specific_limits.basic import topology.metric_space.isometry import topology.instances.ennreal /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist` * `thickening δ s`, the open thickening by radius `δ` of a set `s` in a pseudo emetric space. * `cthickening δ s`, the closed thickening by radius `δ` of a set `s` in a pseudo emetric space. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter variables {ι : Sort*} {α : Type u} {β : Type v} namespace emetric section inf_edist variables [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union @[simp] lemma inf_edist_Union (f : ι → set α) (x : α) : inf_edist x (⋃ i, f i) = ⨅ i, inf_edist x (f i) := infi_Union f _ /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := infi₂_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is antitone with respect to inclusion. -/ lemma inf_edist_anti (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- The edist to a set is `< r` iff there exists a point in the set at edistance `< r` -/ lemma inf_edist_lt_iff {r : ℝ≥0∞} : inf_edist x s < r ↔ ∃ y ∈ s, edist x y < r := by simp_rw [inf_edist, infi_lt_iff] /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : infi₂_mono $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] lemma inf_edist_le_edist_add_inf_edist : inf_edist x s ≤ edist x y + inf_edist y s := by { rw add_comm, exact inf_edist_le_inf_edist_add_edist } lemma edist_le_inf_edist_add_ediam (hy : y ∈ s) : edist x y ≤ inf_edist x s + diam s := begin simp_rw [inf_edist, ennreal.infi_add], refine le_infi (λ i, le_infi (λ hi, _)), calc edist x y ≤ edist x i + edist i y : edist_triangle _ _ _ ... ≤ edist x i + diam s : add_le_add le_rfl (edist_le_diam_of_mem hi hy) end /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_anti subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have ε0 : 0 < (ε / 2 : ℝ≥0∞) := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2, from ennreal.lt_add_right h.ne ε0.ne', rcases inf_edist_lt_iff.mp this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) ε0 with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λ h, by { rw ← inf_edist_closure, exact inf_edist_zero_of_mem h }, λ h, emetric.mem_closure_iff.2 $ λ ε εpos, inf_edist_lt_iff.mp $ by rwa h⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end /-- The infimum edistance of a point to a set is positive if and only if the point is not in the closure of the set. -/ lemma inf_edist_pos_iff_not_mem_closure {x : α} {E : set α} : 0 < inf_edist x E ↔ x ∉ closure E := by rw [mem_closure_iff_inf_edist_zero, pos_iff_ne_zero] lemma inf_edist_closure_pos_iff_not_mem_closure {x : α} {E : set α} : 0 < inf_edist x (closure E) ↔ x ∉ closure E := by rw [inf_edist_closure, inf_edist_pos_iff_not_mem_closure] lemma exists_real_pos_lt_inf_edist_of_not_mem_closure {x : α} {E : set α} (h : x ∉ closure E) : ∃ (ε : ℝ), 0 < ε ∧ ennreal.of_real ε < inf_edist x E := begin rw [← inf_edist_pos_iff_not_mem_closure, ennreal.lt_iff_exists_real_btwn] at h, rcases h with ⟨ε, ⟨_, ⟨ε_pos, ε_lt⟩⟩⟩, exact ⟨ε, ⟨ennreal.of_real_pos.mp ε_pos, ε_lt⟩⟩, end lemma disjoint_closed_ball_of_lt_inf_edist {r : ℝ≥0∞} (h : r < inf_edist x s) : disjoint (closed_ball x r) s := begin rw disjoint_left, assume y hy h'y, apply lt_irrefl (inf_edist x s), calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem h'y ... ≤ r : by rwa [mem_closed_ball, edist_comm] at hy ... < inf_edist x s : h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ monotone F := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, have : inf_edist x Uᶜ ≠ 0 := ((ennreal.pow_pos a_pos _).trans_le hx).ne', contrapose! this, exact inf_edist_zero_of_mem this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed hU.is_closed_compl at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end lemma _root_.is_compact.exists_inf_edist_eq_edist (hs : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_edist x s = edist x y := begin have A : continuous (λ y, edist x y) := continuous_const.edist continuous_id, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, ∀ z, z ∈ s → edist x y ≤ edist x z := hs.exists_forall_le hne A.continuous_on, exact ⟨y, ys, le_antisymm (inf_edist_le_edist_of_mem ys) (by rwa le_inf_edist)⟩ end lemma exists_pos_forall_lt_edist (hs : is_compact s) (ht : is_closed t) (hst : disjoint s t) : ∃ r : ℝ≥0, 0 < r ∧ ∀ (x ∈ s) (y ∈ t), (r : ℝ≥0∞) < edist x y := begin rcases s.eq_empty_or_nonempty with rfl|hne, { use 1, simp }, obtain ⟨x, hx, h⟩ : ∃ x ∈ s, ∀ y ∈ s, inf_edist x t ≤ inf_edist y t := hs.exists_forall_le hne continuous_inf_edist.continuous_on, have : 0 < inf_edist x t, from pos_iff_ne_zero.2 (λ H, hst.le_bot ⟨hx, (mem_iff_inf_edist_zero_of_closed ht).mpr H⟩), rcases ennreal.lt_iff_exists_nnreal_btwn.1 this with ⟨r, h₀, hr⟩, exact ⟨r, ennreal.coe_pos.mp h₀, λ y hy z hz, hr.trans_le $ le_inf_edist.1 (h y hy) z hz⟩ end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_supr₂ x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃ y ∈ t, edist x y < r := inf_edist_lt_iff.mp $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have ε0 : (ε / 2 : ℝ≥0∞) ≠ 0 := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1.ne ε0, rcases inf_edist_lt_iff.mp this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2.ne ε0, rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_anti h end /-- The minimal distance to a set is `< r` iff there exists a point in this set at distance `< r` -/ lemma inf_dist_lt_iff {r : ℝ} (hs : s.nonempty) : inf_dist x s < r ↔ ∃ y ∈ s, dist x y < r := by simp_rw [inf_dist, ← ennreal.lt_of_real_iff_to_real_lt (inf_edist_ne_top hs), inf_edist_lt_iff, ennreal.lt_of_real_iff_to_real_lt (edist_ne_top _ _), ← dist_edist] /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { exact inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end lemma not_mem_of_dist_lt_inf_dist (h : dist x y < inf_dist x s) : y ∉ s := λ hy, h.not_le $ inf_dist_le_dist_of_mem hy lemma disjoint_ball_inf_dist : disjoint (ball x (inf_dist x s)) s := disjoint_left.2 $ λ y hy, not_mem_of_dist_lt_inf_dist $ calc dist x y = dist y x : dist_comm _ _ ... < inf_dist x s : hy lemma ball_inf_dist_subset_compl : ball x (inf_dist x s) ⊆ sᶜ := disjoint_ball_inf_dist.subset_compl_right lemma ball_inf_dist_compl_subset : ball x (inf_dist x sᶜ) ⊆ s := ball_inf_dist_subset_compl.trans (compl_compl s).subset lemma disjoint_closed_ball_of_lt_inf_dist {r : ℝ} (h : r < inf_dist x s) : disjoint (closed_ball x r) s := disjoint_ball_inf_dist.mono_left $ closed_ball_subset_ball h lemma dist_le_inf_dist_add_diam (hs : bounded s) (hy : y ∈ s) : dist x y ≤ inf_dist x s + diam s := begin have A : inf_edist x s ≠ ∞, from inf_edist_ne_top ⟨y, hy⟩, have B : emetric.diam s ≠ ∞, from hs.ediam_ne_top, rw [inf_dist, diam, ← ennreal.to_real_add A B, dist_edist], apply (ennreal.to_real_le_to_real _ _).2, { exact edist_le_inf_edist_add_ediam hy }, { rw edist_dist, exact ennreal.of_real_ne_top }, { exact ennreal.add_ne_top.2 ⟨A, B⟩ } end variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- If a point belongs to the closure of `s`, then its infimum distance to `s` equals zero. The converse is true provided that `s` is nonempty, see `mem_closure_iff_inf_dist_zero`. -/ lemma inf_dist_zero_of_mem_closure (hx : x ∈ closure s) : inf_dist x s = 0 := by { rw ← inf_dist_eq_closure, exact inf_dist_zero_of_mem hx } /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.mem_iff_inf_dist_zero (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := by rw [←mem_closure_iff_inf_dist_zero hs, h.closure_eq] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.not_mem_iff_inf_dist_pos (h : is_closed s) (hs : s.nonempty) : x ∉ s ↔ 0 < inf_dist x s := begin rw ← not_iff_not, push_neg, simp [h.mem_iff_inf_dist_zero hs, le_antisymm_iff, inf_dist_nonneg], end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] lemma inf_dist_inter_closed_ball_of_mem (h : y ∈ s) : inf_dist x (s ∩ closed_ball x (dist y x)) = inf_dist x s := begin replace h : y ∈ s ∩ closed_ball x (dist y x) := ⟨h, mem_closed_ball.2 le_rfl⟩, refine le_antisymm _ (inf_dist_le_inf_dist_of_subset (inter_subset_left _ _) ⟨y, h⟩), refine not_lt.1 (λ hlt, _), rcases (inf_dist_lt_iff ⟨y, h.1⟩).mp hlt with ⟨z, hzs, hz⟩, cases le_or_lt (dist z x) (dist y x) with hle hlt, { exact hz.not_le (inf_dist_le_dist_of_mem ⟨hzs, hle⟩) }, { rw [dist_comm z, dist_comm y] at hlt, exact (hlt.trans hz).not_le (inf_dist_le_dist_of_mem h) } end lemma _root_.is_compact.exists_inf_dist_eq_dist (h : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := let ⟨y, hys, hy⟩ := h.exists_inf_edist_eq_edist hne x in ⟨y, hys, by rw [inf_dist, dist_edist, hy]⟩ lemma _root_.is_closed.exists_inf_dist_eq_dist [proper_space α] (h : is_closed s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := begin rcases hne with ⟨z, hz⟩, rw ← inf_dist_inter_closed_ball_of_mem hz, set t := s ∩ closed_ball x (dist z x), have htc : is_compact t := (is_compact_closed_ball x (dist z x)).inter_left h, have htne : t.nonempty := ⟨z, hz, mem_closed_ball.2 le_rfl⟩, obtain ⟨y, ⟨hys, hyx⟩, hyd⟩ : ∃ y ∈ t, inf_dist x t = dist x y := htc.exists_inf_dist_eq_dist htne x, exact ⟨y, hys, hyd⟩ end lemma exists_mem_closure_inf_dist_eq_dist [proper_space α] (hne : s.nonempty) (x : α) : ∃ y ∈ closure s, inf_dist x s = dist x y := by simpa only [inf_dist_eq_closure] using is_closed_closure.exists_inf_dist_eq_dist hne.closure x /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ne_top_of_le_ne_top ennreal.of_real_ne_top this end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, { rwa [Hausdorff_dist, h1, ennreal.top_to_real] }, cases s.eq_empty_or_nonempty with hs hs, { rwa [hs, Hausdorff_dist_empty'] }, cases t.eq_empty_or_nonempty with ht ht, { rwa [ht, Hausdorff_dist_empty] }, have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, { rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H }, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : lt_top_iff_ne_top.mpr $ ennreal.add_ne_top.mpr ⟨fin, h⟩, rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin Dtu.ne, ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma _root_.is_closed.Hausdorff_dist_zero_iff_eq (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [←Hausdorff_edist_zero_iff_eq_of_closed hs ht, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section section thickening variables [pseudo_emetric_space α] {δ : ℝ} {s : set α} {x : α} open emetric /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at distance less than `δ` from some point of `E`. -/ def thickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E < ennreal.of_real δ} lemma mem_thickening_iff_inf_edist_lt : x ∈ thickening δ s ↔ inf_edist x s < ennreal.of_real δ := iff.rfl /-- The (open) thickening equals the preimage of an open interval under `inf_edist`. -/ lemma thickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : thickening δ E = (λ x, inf_edist x E) ⁻¹' (Iio (ennreal.of_real δ)) := rfl /-- The (open) thickening is an open set. -/ lemma is_open_thickening {δ : ℝ} {E : set α} : is_open (thickening δ E) := continuous.is_open_preimage continuous_inf_edist _ is_open_Iio /-- The (open) thickening of the empty set is empty. -/ @[simp] lemma thickening_empty (δ : ℝ) : thickening δ (∅ : set α) = ∅ := by simp only [thickening, set_of_false, inf_edist_empty, not_top_lt] lemma thickening_of_nonpos (hδ : δ ≤ 0) (s : set α) : thickening δ s = ∅ := eq_empty_of_forall_not_mem $ λ x, ((ennreal.of_real_of_nonpos hδ).trans_le bot_le).not_lt /-- The (open) thickening `thickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma thickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ thickening δ₂ E := preimage_mono (Iio_subset_Iio (ennreal.of_real_le_of_real hle)) /-- The (open) thickening `thickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma thickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : thickening δ E₁ ⊆ thickening δ E₂ := λ _ hx, lt_of_le_of_lt (inf_edist_anti h) hx lemma mem_thickening_iff_exists_edist_lt {δ : ℝ} (E : set α) (x : α) : x ∈ thickening δ E ↔ ∃ z ∈ E, edist x z < ennreal.of_real δ := inf_edist_lt_iff variables {X : Type u} [pseudo_metric_space X] /-- A point in a metric space belongs to the (open) `δ`-thickening of a subset `E` if and only if it is at distance less than `δ` from some point of `E`. -/ lemma mem_thickening_iff {E : set X} {x : X} : x ∈ thickening δ E ↔ (∃ z ∈ E, dist x z < δ) := begin have key_iff : ∀ (z : X), edist x z < ennreal.of_real δ ↔ dist x z < δ, { intros z, rw dist_edist, have d_lt_top : edist x z < ∞, by simp only [edist_dist, ennreal.of_real_lt_top], have key := (@ennreal.of_real_lt_of_real_iff_of_nonneg ((edist x z).to_real) δ (ennreal.to_real_nonneg)), rwa ennreal.of_real_to_real d_lt_top.ne at key, }, simp_rw [mem_thickening_iff_exists_edist_lt, key_iff], end @[simp] lemma thickening_singleton (δ : ℝ) (x : X) : thickening δ ({x} : set X) = ball x δ := by { ext, simp [mem_thickening_iff] } /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a metric space equals the union of balls of radius `δ` centered at points of `E`. -/ lemma thickening_eq_bUnion_ball {δ : ℝ} {E : set X} : thickening δ E = ⋃ x ∈ E, ball x δ := by { ext x, rw mem_Union₂, exact mem_thickening_iff } lemma bounded.thickening {δ : ℝ} {E : set X} (h : bounded E) : bounded (thickening δ E) := begin refine bounded_iff_mem_bounded.2 (λ x hx, _), rcases h.subset_ball x with ⟨R, hR⟩, refine (bounded_iff_subset_ball x).2 ⟨R + δ, _⟩, assume y hy, rcases mem_thickening_iff.1 hy with ⟨z, zE, hz⟩, calc dist y x ≤ dist z x + dist y z : by { rw add_comm, exact dist_triangle _ _ _ } ... ≤ R + δ : add_le_add (hR zE) hz.le end /-- The frontier of the (open) thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_thickening_subset (E : set α) {δ : ℝ} : frontier (thickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := frontier_lt_subset_eq continuous_inf_edist continuous_const lemma frontier_thickening_disjoint (A : set X) : pairwise (disjoint on (λ (r : ℝ), frontier (thickening r A))) := begin refine (pairwise_disjoint_on _).2 (λ r₁ r₂ hr, _), cases le_total r₁ 0 with h₁ h₁, { simp [thickening_of_nonpos h₁] }, refine ((disjoint_singleton.2 $ λ h, hr.ne _).preimage _).mono (frontier_thickening_subset _) (frontier_thickening_subset _), apply_fun ennreal.to_real at h, rwa [ennreal.to_real_of_real h₁, ennreal.to_real_of_real (h₁.trans hr.le)] at h end end thickening --section section cthickening variables [pseudo_emetric_space α] {δ ε : ℝ} {s t : set α} {x : α} open emetric /-- The closed `δ`-thickening `cthickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at infimum distance at most `δ` from `E`. -/ def cthickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E ≤ ennreal.of_real δ} @[simp] lemma mem_cthickening_iff : x ∈ cthickening δ s ↔ inf_edist x s ≤ ennreal.of_real δ := iff.rfl lemma mem_cthickening_of_edist_le (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : edist x y ≤ ennreal.of_real δ) : x ∈ cthickening δ E := (inf_edist_le_edist_of_mem h).trans h' lemma mem_cthickening_of_dist_le {α : Type*} [pseudo_metric_space α] (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : dist x y ≤ δ) : x ∈ cthickening δ E := begin apply mem_cthickening_of_edist_le x y δ E h, rw edist_dist, exact ennreal.of_real_le_of_real h', end lemma cthickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : cthickening δ E = (λ x, inf_edist x E) ⁻¹' (Iic (ennreal.of_real δ)) := rfl /-- The closed thickening is a closed set. -/ lemma is_closed_cthickening {δ : ℝ} {E : set α} : is_closed (cthickening δ E) := is_closed.preimage continuous_inf_edist is_closed_Iic /-- The closed thickening of the empty set is empty. -/ @[simp] lemma cthickening_empty (δ : ℝ) : cthickening δ (∅ : set α) = ∅ := by simp only [cthickening, ennreal.of_real_ne_top, set_of_false, inf_edist_empty, top_le_iff] lemma cthickening_of_nonpos {δ : ℝ} (hδ : δ ≤ 0) (E : set α) : cthickening δ E = closure E := by { ext x, simp [mem_closure_iff_inf_edist_zero, cthickening, ennreal.of_real_eq_zero.2 hδ] } /-- The closed thickening with radius zero is the closure of the set. -/ @[simp] lemma cthickening_zero (E : set α) : cthickening 0 E = closure E := cthickening_of_nonpos le_rfl E lemma cthickening_max_zero (δ : ℝ) (E : set α) : cthickening (max 0 δ) E = cthickening δ E := by cases le_total δ 0; simp [cthickening_of_nonpos, *] /-- The closed thickening `cthickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma cthickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : cthickening δ₁ E ⊆ cthickening δ₂ E := preimage_mono (Iic_subset_Iic.mpr (ennreal.of_real_le_of_real hle)) @[simp] lemma cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) {δ : ℝ} (hδ : 0 ≤ δ) : cthickening δ ({x} : set α) = closed_ball x δ := by { ext y, simp [cthickening, edist_dist, ennreal.of_real_le_of_real_iff hδ] } lemma closed_ball_subset_cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ ({x} : set α) := begin rcases lt_or_le δ 0 with hδ|hδ, { simp only [closed_ball_eq_empty.mpr hδ, empty_subset] }, { simp only [cthickening_singleton x hδ] } end /-- The closed thickening `cthickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma cthickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : cthickening δ E₁ ⊆ cthickening δ E₂ := λ _ hx, le_trans (inf_edist_anti h) hx lemma cthickening_subset_thickening {δ₁ : ℝ≥0} {δ₂ : ℝ} (hlt : (δ₁ : ℝ) < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff (lt_of_le_of_lt δ₁.prop hlt)).mpr hlt) /-- The closed thickening `cthickening δ₁ E` is contained in the open thickening `thickening δ₂ E` if the radius of the latter is positive and larger. -/ lemma cthickening_subset_thickening' {δ₁ δ₂ : ℝ} (δ₂_pos : 0 < δ₂) (hlt : δ₁ < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff δ₂_pos).mpr hlt) /-- The open thickening `thickening δ E` is contained in the closed thickening `cthickening δ E` with the same radius. -/ lemma thickening_subset_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ cthickening δ E := by { intros x hx, rw [thickening, mem_set_of_eq] at hx, exact hx.le, } lemma thickening_subset_cthickening_of_le {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ cthickening δ₂ E := (thickening_subset_cthickening δ₁ E).trans (cthickening_mono hle E) lemma bounded.cthickening {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (h : bounded E) : bounded (cthickening δ E) := begin have : bounded (thickening (max (δ + 1) 1) E) := h.thickening, apply bounded.mono _ this, exact cthickening_subset_thickening' (zero_lt_one.trans_le (le_max_right _ _)) ((lt_add_one _).trans_le (le_max_left _ _)) _ end lemma thickening_subset_interior_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ interior (cthickening δ E) := (subset_interior_iff_is_open.mpr (is_open_thickening)).trans (interior_mono (thickening_subset_cthickening δ E)) lemma closure_thickening_subset_cthickening (δ : ℝ) (E : set α) : closure (thickening δ E) ⊆ cthickening δ E := (closure_mono (thickening_subset_cthickening δ E)).trans is_closed_cthickening.closure_subset /-- The closed thickening of a set contains the closure of the set. -/ lemma closure_subset_cthickening (δ : ℝ) (E : set α) : closure E ⊆ cthickening δ E := by { rw ← cthickening_of_nonpos (min_le_right δ 0), exact cthickening_mono (min_le_left δ 0) E, } /-- The (open) thickening of a set contains the closure of the set. -/ lemma closure_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : closure E ⊆ thickening δ E := by { rw ← cthickening_zero, exact cthickening_subset_thickening' δ_pos δ_pos E, } /-- A set is contained in its own (open) thickening. -/ lemma self_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : E ⊆ thickening δ E := (@subset_closure _ _ E).trans (closure_subset_thickening δ_pos E) /-- A set is contained in its own closed thickening. -/ lemma self_subset_cthickening {δ : ℝ} (E : set α) : E ⊆ cthickening δ E := subset_closure.trans (closure_subset_cthickening δ E) lemma thickening_mem_nhds_set (E : set α) {δ : ℝ} (hδ : 0 < δ) : thickening δ E ∈ 𝓝ˢ E := is_open_thickening.mem_nhds_set.2 $ self_subset_thickening hδ E lemma cthickening_mem_nhds_set (E : set α) {δ : ℝ} (hδ : 0 < δ) : cthickening δ E ∈ 𝓝ˢ E := mem_of_superset (thickening_mem_nhds_set E hδ) (thickening_subset_cthickening _ _) @[simp] lemma thickening_union (δ : ℝ) (s t : set α) : thickening δ (s ∪ t) = thickening δ s ∪ thickening δ t := by simp_rw [thickening, inf_edist_union, inf_eq_min, min_lt_iff, set_of_or] @[simp] lemma cthickening_union (δ : ℝ) (s t : set α) : cthickening δ (s ∪ t) = cthickening δ s ∪ cthickening δ t := by simp_rw [cthickening, inf_edist_union, inf_eq_min, min_le_iff, set_of_or] @[simp] lemma thickening_Union (δ : ℝ) (f : ι → set α) : thickening δ (⋃ i, f i) = ⋃ i, thickening δ (f i) := by simp_rw [thickening, inf_edist_Union, infi_lt_iff, set_of_exists] lemma ediam_cthickening_le (ε : ℝ≥0) : emetric.diam (cthickening ε s) ≤ emetric.diam s + 2 * ε := begin refine diam_le (λ x hx y hy, ennreal.le_of_forall_pos_le_add $ λ δ hδ _, _), rw [mem_cthickening_iff, ennreal.of_real_coe_nnreal] at hx hy, have hε : (ε : ℝ≥0∞) < ε + ↑(δ / 2) := ennreal.coe_lt_coe.2 (lt_add_of_pos_right _ $ half_pos hδ), rw [ennreal.coe_div two_ne_zero, ennreal.coe_two] at hε, replace hx := hx.trans_lt hε, replace hy := hy.trans_lt hε, rw inf_edist_lt_iff at hx hy, obtain ⟨x', hx', hxx'⟩ := hx, obtain ⟨y', hy', hyy'⟩ := hy, refine (edist_triangle_right _ _ _).trans ((add_le_add hxx'.le $ (edist_triangle _ _ _).trans $ add_le_add hyy'.le $ edist_le_diam_of_mem hy' hx').trans_eq _), -- Now we're done, but `ring` won't do it because we're on `ennreal` :( rw [←add_assoc, ←two_mul, mul_add, ennreal.mul_div_cancel' ennreal.two_ne_zero ennreal.two_ne_top], abel, end lemma ediam_thickening_le (ε : ℝ≥0) : emetric.diam (thickening ε s) ≤ emetric.diam s + 2 * ε := (emetric.diam_mono $ thickening_subset_cthickening _ _).trans $ ediam_cthickening_le _ lemma diam_cthickening_le {α : Type*} [pseudo_metric_space α] (s : set α) (hε : 0 ≤ ε) : diam (cthickening ε s) ≤ diam s + 2 * ε := begin by_cases hs : bounded (cthickening ε s), { replace hs := hs.mono (self_subset_cthickening _), have : (2 : ℝ≥0∞) * @coe ℝ≥0 _ _ ⟨ε, hε⟩ ≠ ⊤ := by simp, refine (ennreal.to_real_mono (ennreal.add_ne_top.2 ⟨hs.ediam_ne_top, this⟩) $ ediam_cthickening_le ⟨ε, hε⟩).trans_eq _, simp [ennreal.to_real_add hs.ediam_ne_top this, diam] }, { rw diam_eq_zero_of_unbounded hs, positivity } end lemma diam_thickening_le {α : Type*} [pseudo_metric_space α] (s : set α) (hε : 0 ≤ ε) : diam (thickening ε s) ≤ diam s + 2 * ε := begin by_cases hs : bounded s, { exact (diam_mono (thickening_subset_cthickening _ _) hs.cthickening).trans (diam_cthickening_le _ hε) }, obtain rfl | hε := hε.eq_or_lt, { simp [thickening_of_nonpos, diam_nonneg] }, { rw diam_eq_zero_of_unbounded (mt (bounded.mono $ self_subset_thickening hε _) hs), positivity } end @[simp] lemma thickening_closure : thickening δ (closure s) = thickening δ s := by simp_rw [thickening, inf_edist_closure] @[simp] lemma cthickening_closure : cthickening δ (closure s) = cthickening δ s := by simp_rw [cthickening, inf_edist_closure] open ennreal lemma _root_.disjoint.exists_thickenings (hst : disjoint s t) (hs : is_compact s) (ht : is_closed t) : ∃ δ, 0 < δ ∧ disjoint (thickening δ s) (thickening δ t) := begin obtain ⟨r, hr, h⟩ := exists_pos_forall_lt_edist hs ht hst, refine ⟨r / 2, half_pos (nnreal.coe_pos.2 hr), _⟩, rw disjoint_iff_inf_le, rintro z ⟨hzs, hzt⟩, rw mem_thickening_iff_exists_edist_lt at hzs hzt, rw [← nnreal.coe_two, ← nnreal.coe_div, ennreal.of_real_coe_nnreal] at hzs hzt, obtain ⟨x, hx, hzx⟩ := hzs, obtain ⟨y, hy, hzy⟩ := hzt, refine (h x hx y hy).not_le _, calc edist x y ≤ edist z x + edist z y : edist_triangle_left _ _ _ ... ≤ ↑(r / 2) + ↑(r / 2) : add_le_add hzx.le hzy.le ... = r : by rw [← ennreal.coe_add, nnreal.add_halves] end lemma _root_.disjoint.exists_cthickenings (hst : disjoint s t) (hs : is_compact s) (ht : is_closed t) : ∃ δ, 0 < δ ∧ disjoint (cthickening δ s) (cthickening δ t) := begin obtain ⟨δ, hδ, h⟩ := hst.exists_thickenings hs ht, refine ⟨δ / 2, half_pos hδ, h.mono _ _⟩; exact (cthickening_subset_thickening' hδ (half_lt_self hδ) _), end lemma _root_.is_compact.exists_cthickening_subset_open (hs : is_compact s) (ht : is_open t) (hst : s ⊆ t) : ∃ δ, 0 < δ ∧ cthickening δ s ⊆ t := (hst.disjoint_compl_right.exists_cthickenings hs ht.is_closed_compl).imp $ λ δ h, ⟨h.1, disjoint_compl_right_iff_subset.1 $ h.2.mono_right $ self_subset_cthickening _⟩ lemma _root_.is_compact.exists_thickening_subset_open (hs : is_compact s) (ht : is_open t) (hst : s ⊆ t) : ∃ δ, 0 < δ ∧ thickening δ s ⊆ t := let ⟨δ, h₀, hδ⟩ := hs.exists_cthickening_subset_open ht hst in ⟨δ, h₀, (thickening_subset_cthickening _ _).trans hδ⟩ lemma has_basis_nhds_set_thickening {K : set α} (hK : is_compact K) : (𝓝ˢ K).has_basis (λ δ : ℝ, 0 < δ) (λ δ, thickening δ K) := (has_basis_nhds_set K).to_has_basis' (λ U hU, hK.exists_thickening_subset_open hU.1 hU.2) $ λ _, thickening_mem_nhds_set K lemma has_basis_nhds_set_cthickening {K : set α} (hK : is_compact K) : (𝓝ˢ K).has_basis (λ δ : ℝ, 0 < δ) (λ δ, cthickening δ K) := (has_basis_nhds_set K).to_has_basis' (λ U hU, hK.exists_cthickening_subset_open hU.1 hU.2) $ λ _, cthickening_mem_nhds_set K lemma cthickening_eq_Inter_cthickening' {δ : ℝ} (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, cthickening ε E := begin apply subset.antisymm, { exact subset_Inter₂ (λ _ hε, cthickening_mono (le_of_lt (hsδ hε)) E), }, { unfold thickening cthickening, intros x hx, simp only [mem_Inter, mem_set_of_eq] at *, apply ennreal.le_of_forall_pos_le_add, intros η η_pos _, rcases hs (δ + η) (lt_add_of_pos_right _ (nnreal.coe_pos.mpr η_pos)) with ⟨ε, ⟨hsε, hε⟩⟩, apply ((hx ε hsε).trans (ennreal.of_real_le_of_real hε.2)).trans, rw ennreal.coe_nnreal_eq η, exact ennreal.of_real_add_le, }, end lemma cthickening_eq_Inter_cthickening {δ : ℝ} (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), cthickening ε E := begin apply cthickening_eq_Inter_cthickening' (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end lemma cthickening_eq_Inter_thickening' {δ : ℝ} (δ_nn : 0 ≤ δ) (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, thickening ε E := begin refine (subset_Inter₂ $ λ ε hε, _).antisymm _, { obtain ⟨ε', hsε', hε'⟩ := hs ε (hsδ hε), have ss := cthickening_subset_thickening' (lt_of_le_of_lt δ_nn hε'.1) hε'.1 E, exact ss.trans (thickening_mono hε'.2 E), }, { rw cthickening_eq_Inter_cthickening' s hsδ hs E, exact Inter₂_mono (λ ε hε, thickening_subset_cthickening ε E) } end lemma cthickening_eq_Inter_thickening {δ : ℝ} (δ_nn : 0 ≤ δ) (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), thickening ε E := begin apply cthickening_eq_Inter_thickening' δ_nn (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end lemma cthickening_eq_Inter_thickening'' (δ : ℝ) (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : max 0 δ < ε), thickening ε E := by { rw [←cthickening_max_zero, cthickening_eq_Inter_thickening], exact le_max_left _ _ } /-- The closure of a set equals the intersection of its closed thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_cthickening' (E : set α) (s : set ℝ) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, cthickening δ E := begin by_cases hs₀ : s ⊆ Ioi 0, { rw ← cthickening_zero, apply cthickening_eq_Inter_cthickening' _ hs₀ hs, }, obtain ⟨δ, hδs, δ_nonpos⟩ := not_subset.mp hs₀, rw [set.mem_Ioi, not_lt] at δ_nonpos, apply subset.antisymm, { exact subset_Inter₂ (λ ε _, closure_subset_cthickening ε E), }, { rw ← cthickening_of_nonpos δ_nonpos E, exact bInter_subset_of_mem hδs, }, end /-- The closure of a set equals the intersection of its closed thickenings of positive radii. -/ lemma closure_eq_Inter_cthickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), cthickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_cthickening E, } /-- The closure of a set equals the intersection of its open thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_thickening' (E : set α) (s : set ℝ) (hs₀ : s ⊆ Ioi 0) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, thickening δ E := by { rw ← cthickening_zero, apply cthickening_eq_Inter_thickening' le_rfl _ hs₀ hs, } /-- The closure of a set equals the intersection of its (open) thickenings of positive radii. -/ lemma closure_eq_Inter_thickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), thickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_thickening rfl.ge E, } /-- The frontier of the closed thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_cthickening_subset (E : set α) {δ : ℝ} : frontier (cthickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := frontier_le_subset_eq continuous_inf_edist continuous_const /-- The closed ball of radius `δ` centered at a point of `E` is included in the closed thickening of `E`. -/ lemma closed_ball_subset_cthickening {α : Type*} [pseudo_metric_space α] {x : α} {E : set α} (hx : x ∈ E) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ E := begin refine (closed_ball_subset_cthickening_singleton _ _).trans (cthickening_subset_of_subset _ _), simpa using hx, end /-- The closed thickening of a compact set `E` is the union of the balls `closed_ball x δ` over `x ∈ E`. -/ lemma _root_.is_compact.cthickening_eq_bUnion_closed_ball {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (hE : is_compact E) (hδ : 0 ≤ δ) : cthickening δ E = ⋃ x ∈ E, closed_ball x δ := begin rcases eq_empty_or_nonempty E with rfl|hne, { simp only [cthickening_empty, Union_false, Union_empty] }, refine subset.antisymm (λ x hx, _) (Union₂_subset $ λ x hx, closed_ball_subset_cthickening hx _), obtain ⟨y, yE, hy⟩ : ∃ y ∈ E, inf_edist x E = edist x y := hE.exists_inf_edist_eq_edist hne _, have D1 : edist x y ≤ ennreal.of_real δ := (le_of_eq hy.symm).trans hx, have D2 : dist x y ≤ δ, { rw edist_dist at D1, exact (ennreal.of_real_le_of_real_iff hδ).1 D1 }, exact mem_bUnion yE D2, end /-- For the equality, see `inf_edist_cthickening`. -/ lemma inf_edist_le_inf_edist_cthickening_add : inf_edist x s ≤ inf_edist x (cthickening δ s) + ennreal.of_real δ := begin refine le_of_forall_lt' (λ r h, _), simp_rw [←lt_tsub_iff_right, inf_edist_lt_iff, mem_cthickening_iff] at h, obtain ⟨y, hy, hxy⟩ := h, exact inf_edist_le_edist_add_inf_edist.trans_lt ((ennreal.add_lt_add_of_lt_of_le (hy.trans_lt ennreal.of_real_lt_top).ne hxy hy).trans_le (tsub_add_cancel_of_le $ le_self_add.trans (lt_tsub_iff_left.1 hxy).le).le), end /-- For the equality, see `inf_edist_thickening`. -/ lemma inf_edist_le_inf_edist_thickening_add : inf_edist x s ≤ inf_edist x (thickening δ s) + ennreal.of_real δ := inf_edist_le_inf_edist_cthickening_add.trans $ add_le_add_right (inf_edist_anti $ thickening_subset_cthickening _ _) _ /-- For the equality, see `thickening_thickening`. -/ @[simp] lemma thickening_thickening_subset (ε δ : ℝ) (s : set α) : thickening ε (thickening δ s) ⊆ thickening (ε + δ) s := begin obtain hε | hε := le_total ε 0, { simp only [thickening_of_nonpos hε, empty_subset] }, obtain hδ | hδ := le_total δ 0, { simp only [thickening_of_nonpos hδ, thickening_empty, empty_subset] }, intros x, simp_rw [mem_thickening_iff_exists_edist_lt, ennreal.of_real_add hε hδ], exact λ ⟨y, ⟨z, hz, hy⟩, hx⟩, ⟨z, hz, (edist_triangle _ _ _).trans_lt $ ennreal.add_lt_add hx hy⟩, end /-- For the equality, see `thickening_cthickening`. -/ @[simp] lemma thickening_cthickening_subset (ε : ℝ) (hδ : 0 ≤ δ) (s : set α) : thickening ε (cthickening δ s) ⊆ thickening (ε + δ) s := begin obtain hε | hε := le_total ε 0, { simp only [thickening_of_nonpos hε, empty_subset] }, intro x, simp_rw [mem_thickening_iff_exists_edist_lt, mem_cthickening_iff, ←inf_edist_lt_iff, ennreal.of_real_add hε hδ], rintro ⟨y, hy, hxy⟩, exact inf_edist_le_edist_add_inf_edist.trans_lt (ennreal.add_lt_add_of_lt_of_le (hy.trans_lt ennreal.of_real_lt_top).ne hxy hy), end /-- For the equality, see `cthickening_thickening`. -/ @[simp] lemma cthickening_thickening_subset (hε : 0 ≤ ε) (δ : ℝ) (s : set α) : cthickening ε (thickening δ s) ⊆ cthickening (ε + δ) s := begin obtain hδ | hδ := le_total δ 0, { simp only [thickening_of_nonpos hδ, cthickening_empty, empty_subset] }, intro x, simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ], exact λ hx, inf_edist_le_inf_edist_thickening_add.trans (add_le_add_right hx _), end /-- For the equality, see `cthickening_cthickening`. -/ @[simp] lemma cthickening_cthickening_subset (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (s : set α) : cthickening ε (cthickening δ s) ⊆ cthickening (ε + δ) s := begin intro x, simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ], exact λ hx, inf_edist_le_inf_edist_cthickening_add.trans (add_le_add_right hx _), end lemma frontier_cthickening_disjoint (A : set α) : pairwise (disjoint on (λ (r : ℝ≥0), frontier (cthickening r A))) := λ r₁ r₂ hr, ((disjoint_singleton.2 $ by simpa).preimage _).mono (frontier_cthickening_subset _) (frontier_cthickening_subset _) end cthickening --section end metric --namespace
c3c2ca41e2374667ee23d11bc4e55d25a1546397
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/exp/core.lean
4ce1fc82a905c17c2e88cbd0360e73e140a3520e
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,176
lean
import data.fresh import data.finset import occurs namespace tts ------------------------------------------------------------------ open occurs /-- Grammar of expressions -/ inductive exp (V : Type) : Type | var : occurs → tagged V → exp -- variable, bound or free | app : exp → exp → exp -- function application | lam : V → exp → exp -- lambda-abstraction | let_ : V → exp → exp → exp -- let-abstraction namespace exp ------------------------------------------------------------------ variables {V : Type} -- Type of variable names protected def repr [has_repr V] : exp V → string | (var bound x) := _root_.repr x.tag ++ "⟨" ++ _root_.repr x.val ++ "⟩" | (var free x) := _root_.repr x | (app ef ea) := "(" ++ ef.repr ++ ") (" ++ ea.repr ++ ")" | (lam v eb) := "λ " ++ _root_.repr v ++ " . " ++ eb.repr | (let_ v ed eb) := "let " ++ _root_.repr v ++ " = " ++ ed.repr ++ " in " ++ eb.repr instance [has_repr V] : has_repr (exp V) := ⟨exp.repr⟩ end /- namespace -/ exp -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
76011ab52690fcd51396509204bc5b9b96563de7
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/rquote.lean
caa0dc41ed24b7b35df072a4d5098dc9d20d8f22
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
375
lean
-- constant nat.gcd : nat → nat → nat namespace foo constant f : nat → nat constant g : nat → nat end foo namespace boo constant f : nat → nat end boo open foo boo #check ``f #check ``g open nat #check ``add #check ``gcd #check `f #check `foo.f namespace bla section parameter A : Type definition ID : A → A := λ x, x #check ``ID end end bla
81c95f475c4708ee9c18da7659b736b20e03afd9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed/order/lattice.lean
e9e8318dbba714ac617a382925d53fc0d2de44f1
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,008
lean
/- Copyright (c) 2021 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.order.lattice import analysis.normed.group.basic import algebra.order.lattice_group /-! # Normed lattice ordered groups Motivated by the theory of Banach Lattices, we then define `normed_lattice_add_comm_group` as a lattice with a covariant normed group addition satisfying the solid axiom. ## Main statements We show that a normed lattice ordered group is a topological lattice with respect to the norm topology. ## References * [Meyer-Nieberg, Banach lattices][MeyerNieberg1991] ## Tags normed, lattice, ordered, group -/ /-! ### Normed lattice orderd groups Motivated by the theory of Banach Lattices, this section introduces normed lattice ordered groups. -/ local notation (name := abs) `|`a`|` := abs a /-- Let `α` be a normed commutative group equipped with a partial order covariant with addition, with respect which `α` forms a lattice. Suppose that `α` is *solid*, that is to say, for `a` and `b` in `α`, with absolute values `|a|` and `|b|` respectively, `|a| ≤ |b|` implies `‖a‖ ≤ ‖b‖`. Then `α` is said to be a normed lattice ordered group. -/ class normed_lattice_add_comm_group (α : Type*) extends normed_add_comm_group α, lattice α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (solid : ∀ a b : α, |a| ≤ |b| → ‖a‖ ≤ ‖b‖) lemma solid {α : Type*} [normed_lattice_add_comm_group α] {a b : α} (h : |a| ≤ |b|) : ‖a‖ ≤ ‖b‖ := normed_lattice_add_comm_group.solid a b h instance : normed_lattice_add_comm_group ℝ := { add_le_add_left := λ _ _ h _, add_le_add le_rfl h, solid := λ _ _, id, } /-- A normed lattice ordered group is an ordered additive commutative group -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_to_ordered_add_comm_group {α : Type*} [h : normed_lattice_add_comm_group α] : ordered_add_comm_group α := { ..h } variables {α : Type*} [normed_lattice_add_comm_group α] open lattice_ordered_comm_group lemma dual_solid (a b : α) (h: b⊓-b ≤ a⊓-a) : ‖a‖ ≤ ‖b‖ := begin apply solid, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg a, rw ← neg_inf_eq_sup_neg, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg b, rwa [← neg_inf_eq_sup_neg, neg_le_neg_iff, @inf_comm _ _ _ b, @inf_comm _ _ _ a], end /-- Let `α` be a normed lattice ordered group, then the order dual is also a normed lattice ordered group. -/ @[priority 100] -- see Note [lower instance priority] instance : normed_lattice_add_comm_group αᵒᵈ := { solid := dual_solid, ..order_dual.ordered_add_comm_group, ..order_dual.normed_add_comm_group } lemma norm_abs_eq_norm (a : α) : ‖|a|‖ = ‖a‖ := (solid (abs_abs a).le).antisymm (solid (abs_abs a).symm.le) lemma norm_inf_sub_inf_le_add_norm (a b c d : α) : ‖a ⊓ b - c ⊓ d‖ ≤ ‖a - c‖ + ‖b - d‖ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊓ b - c ⊓ d| = |a ⊓ b - c ⊓ b + (c ⊓ b - c ⊓ d)| : by rw sub_add_sub_cancel ... ≤ |a ⊓ b - c ⊓ b| + |c ⊓ b - c ⊓ d| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_inf_sub_inf_le_abs _ _ _, }, { rw [@inf_comm _ _ c, @inf_comm _ _ c], exact abs_inf_sub_inf_le_abs _ _ _, } }, end lemma norm_sup_sub_sup_le_add_norm (a b c d : α) : ‖a ⊔ b - (c ⊔ d)‖ ≤ ‖a - c‖ + ‖b - d‖ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊔ b - (c ⊔ d)| = |a ⊔ b - (c ⊔ b) + (c ⊔ b - (c ⊔ d))| : by rw sub_add_sub_cancel ... ≤ |a ⊔ b - (c ⊔ b)| + |c ⊔ b - (c ⊔ d)| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_sup_sub_sup_le_abs _ _ _, }, { rw [@sup_comm _ _ c, @sup_comm _ _ c], exact abs_sup_sub_sup_le_abs _ _ _, } }, end lemma norm_inf_le_add (x y : α) : ‖x ⊓ y‖ ≤ ‖x‖ + ‖y‖ := begin have h : ‖x ⊓ y - 0 ⊓ 0‖ ≤ ‖x - 0‖ + ‖y - 0‖ := norm_inf_sub_inf_le_add_norm x y 0 0, simpa only [inf_idem, sub_zero] using h, end lemma norm_sup_le_add (x y : α) : ‖x ⊔ y‖ ≤ ‖x‖ + ‖y‖ := begin have h : ‖x ⊔ y - 0 ⊔ 0‖ ≤ ‖x - 0‖ + ‖y - 0‖ := norm_sup_sub_sup_le_add_norm x y 0 0, simpa only [sup_idem, sub_zero] using h, end /-- Let `α` be a normed lattice ordered group. Then the infimum is jointly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_inf : has_continuous_inf α := begin refine ⟨continuous_iff_continuous_at.2 $ λ q, tendsto_iff_norm_tendsto_zero.2 $ _⟩, have : ∀ p : α × α, ‖p.1 ⊓ p.2 - q.1 ⊓ q.2‖ ≤ ‖p.1 - q.1‖ + ‖p.2 - q.2‖, from λ _, norm_inf_sub_inf_le_add_norm _ _ _ _, refine squeeze_zero (λ e, norm_nonneg _) this _, convert (((continuous_fst.tendsto q).sub tendsto_const_nhds).norm).add (((continuous_snd.tendsto q).sub tendsto_const_nhds).norm), simp, end @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_sup {α : Type*} [normed_lattice_add_comm_group α] : has_continuous_sup α := order_dual.has_continuous_sup αᵒᵈ /-- Let `α` be a normed lattice ordered group. Then `α` is a topological lattice in the norm topology. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_topological_lattice : topological_lattice α := topological_lattice.mk lemma norm_abs_sub_abs (a b : α) : ‖ |a| - |b| ‖ ≤ ‖a-b‖ := solid (lattice_ordered_comm_group.abs_abs_sub_abs_le _ _) lemma norm_sup_sub_sup_le_norm (x y z : α) : ‖x ⊔ z - (y ⊔ z)‖ ≤ ‖x - y‖ := solid (abs_sup_sub_sup_le_abs x y z) lemma norm_inf_sub_inf_le_norm (x y z : α) : ‖x ⊓ z - (y ⊓ z)‖ ≤ ‖x - y‖ := solid (abs_inf_sub_inf_le_abs x y z) lemma lipschitz_with_sup_right (z : α) : lipschitz_with 1 (λ x, x ⊔ z) := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [nonneg.coe_one, one_mul, dist_eq_norm, dist_eq_norm], exact norm_sup_sub_sup_le_norm x y z, } lemma lipschitz_with_pos : lipschitz_with 1 (has_pos_part.pos : α → α) := lipschitz_with_sup_right 0 lemma continuous_pos : continuous (has_pos_part.pos : α → α) := lipschitz_with.continuous lipschitz_with_pos lemma continuous_neg' : continuous (has_neg_part.neg : α → α) := continuous_pos.comp continuous_neg lemma is_closed_nonneg {E} [normed_lattice_add_comm_group E] : is_closed {x : E | 0 ≤ x} := begin suffices : {x : E | 0 ≤ x} = has_neg_part.neg ⁻¹' {(0 : E)}, by { rw this, exact is_closed.preimage continuous_neg' is_closed_singleton, }, ext1 x, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_set_of_eq, neg_eq_zero_iff], end lemma is_closed_le_of_is_closed_nonneg {G} [ordered_add_comm_group G] [topological_space G] [has_continuous_sub G] (h : is_closed {x : G | 0 ≤ x}) : is_closed {p : G × G | p.fst ≤ p.snd} := begin have : {p : G × G | p.fst ≤ p.snd} = (λ p : G × G, p.snd - p.fst) ⁻¹' {x : G | 0 ≤ x}, by { ext1 p, simp only [sub_nonneg, set.preimage_set_of_eq], }, rw this, exact is_closed.preimage (continuous_snd.sub continuous_fst) h, end @[priority 100] -- See note [lower instance priority] instance normed_lattice_add_comm_group.order_closed_topology {E} [normed_lattice_add_comm_group E] : order_closed_topology E := ⟨is_closed_le_of_is_closed_nonneg is_closed_nonneg⟩
3fbc9a61728a8c3502e7f3f6094156d22767f87a
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/module/linear_map.lean
148d4b575fe38bc5783d7e0304b8e3f4555bacdb
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,733
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [semimodule R M] [semimodule R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance compatible_smul.is_scalar_tower {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [semimodule S M] [is_scalar_tower R S M] [has_scalar R M₂] [semimodule S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : (f.to_add_monoid_hom : M → M₂) = f := rfl variable (R) /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ def restrict_scalars {S : Type*} [semiring S] [semimodule S M] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] theorem ext_ring_iff {f g : R →ₗ[R] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [semimodule ℤ M] [semimodule S M] [semimodule ℤ M₂] [semimodule S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simpa [add_smul] using ih }, case hn : n ih { simpa [sub_smul] using ih } end⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma injective_to_equiv : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := injective_to_equiv.eq_iff lemma injective_to_linear_map : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, injective_to_equiv $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := injective_to_linear_map.eq_iff end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = ↑e := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₗ[R] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun [semimodule R M] [semimodule R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := injective_to_equiv e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := injective_to_equiv e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl end add_comm_monoid end linear_equiv
1c8ad4715ba1938055ab470600a1003d2090511d
93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2
/src/sep/primeSpec.lean
00f3f1a86d9b1da4ec8b47aaec2ccc104d4f47d1
[]
no_license
intoverflow/timesink
93f8535cd504bc128ba1b57ce1eda4efc74e5136
c25be4a2edb866ad0a9a87ee79e209afad6ab303
refs/heads/master
1,620,033,920,087
1,524,995,105,000
1,524,995,105,000
120,576,102
1
0
null
null
null
null
UTF-8
Lean
false
false
22,561
lean
/- The prime-spectrum of a separation algebra. - -/ import .basic import .rel import .ordalg import ..top.basic import ..extralib namespace Sep universes ℓ ℓ₁ ℓ₂ open Top structure OrdAlg.PrimeSpec (A : OrdAlg.{ℓ}) : Type.{ℓ} := (set : Set A.alg) (prime : set.Prime) (locl : A.ord.FnInv set = set) def PrimeSpec.eq {A : OrdAlg.{ℓ}} (p₁ p₂ : A.PrimeSpec) : p₁.set = p₂.set → p₁ = p₂ := begin intro E, cases p₁ with p₁ H₁, cases p₂ with p₂ H₂, simp at E, subst E end def PrimePres.InducedMap {X : OrdAlg.{ℓ₁}} {Y : OrdAlg.{ℓ₂}} {r : OrdRel X Y} (rPP : r.rel.PrimePres) : Y.PrimeSpec → X.PrimeSpec := λ p, { set := r.rel.FnInv p.set , prime := Rel.PrimePres_iff.2 @rPP p.prime , locl := begin apply funext, intro x₁, apply iff.to_eq, apply iff.intro, { intro H, cases H with x₂ H, cases H with H Lx, cases H with y₂ H, cases H with Hpy₂ R₂, have Q := r.incr _ _ _ R₂ Lx, cases Q with y₁ Q, cases Q with R₁ Ly, have Hpy₁ : y₁ ∈ p.set, from begin rw p.locl.symm, existsi y₂, exact and.intro Hpy₂ Ly end, existsi y₁, exact and.intro Hpy₁ R₁ }, { intro H, cases H with y₁ H, cases H with Hpy₁ R₁, existsi x₁, refine and.intro _ (X.refl _), existsi y₁, exact and.intro Hpy₁ R₁ } end --r.ConfinedPres p.locl } def PrimeSpec.BasicOpen {A : OrdAlg.{ℓ}} (S : Set A.alg) : set A.PrimeSpec := λ p, ∀ {s}, ¬ s ∈ S ∩ p.set def PrimePres.InducedMap.BasicPreImage {X : OrdAlg.{ℓ₁}} {Y : OrdAlg.{ℓ₂}} (r : OrdRel X Y) (rPP : r.rel.PrimePres) (xs : Set X.alg) : PreImage (PrimePres.InducedMap @rPP) (PrimeSpec.BasicOpen xs) = PrimeSpec.BasicOpen (r.rel.Fn xs) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intros H y Hy, apply Hy.1.elim, intros x Hxxs Rxy, refine H (and.intro Hxxs _), existsi y, exact and.intro Hy.2 Rxy }, { intros H x Hx, cases Hx.2 with y Hy, refine H (and.intro _ Hy.1), existsi x, exact and.intro Hx.1 Hy.2 } end def PrimeSpec.BasicOpen.intersection {A : OrdAlg.{ℓ}} (S₁ S₂ : Set A.alg) : PrimeSpec.BasicOpen S₁ ∩ PrimeSpec.BasicOpen S₂ = PrimeSpec.BasicOpen (S₁ ∪ S₂) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intros H x Hx, cases Hx with Sx Px, cases Sx with Sx Sx, { exact H.1 (and.intro Sx Px) }, { exact H.2 (and.intro Sx Px) } }, { intro H, apply and.intro, { intros x Hx, exact H (and.intro (or.inl Hx.1) Hx.2) }, { intros x Hx, exact H (and.intro (or.inr Hx.1) Hx.2) } } end def PrimeSpec.BasicOpen.intersection₀ {A : OrdAlg.{ℓ}} (S : set (Set A.alg)) : set.sInter (PrimeSpec.BasicOpen <$> S) = PrimeSpec.BasicOpen (set.sUnion S) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intros H x Hx, cases Hx.1 with T H, cases H with HTS HxT, refine H (PrimeSpec.BasicOpen T) _ (and.intro HxT Hx.2), existsi T, exact and.intro HTS rfl }, { intros H O HO, cases HO with T HO, cases HO with HTS E, have E' := E.symm, subst E', clear E, intros x Hx, refine H (and.intro _ Hx.2), existsi T, exact exists.intro HTS Hx.1 } end def OrdAlg.PrimeSpec.OpenBasis (A : OrdAlg.{ℓ}) : OpenBasis A.PrimeSpec := { OI := Set A.alg , Open := PrimeSpec.BasicOpen , Cover := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intro T, clear T, existsi (λ x, true), apply exists.intro, { apply exists.intro ∅, apply funext, intro p', apply iff.to_eq, apply iff.intro, { intro T, clear T, intros x Hx, exact Hx.1 }, { intro H, constructor } }, { constructor } }, { intro H, constructor } end , inter := λ S₁ S₂, S₁ ∪ S₂ , Ointer := begin intros U₁ U₂, apply funext, intro p, apply iff.to_eq, apply iff.intro, { intro H, apply and.intro, { intros x Hx, exact H (and.intro (or.inl Hx.1) Hx.2) }, { intros x Hx, exact H (and.intro (or.inr Hx.1) Hx.2) } }, { intro H, cases H with H₁ H₂, intros x Hx, cases Hx with Hx Hxp, cases Hx with Hx Hx, { exact H₁ (and.intro Hx Hxp) }, { exact H₂ (and.intro Hx Hxp) } } end } def OrdAlg.PrimeSpec.Topology (A : OrdAlg.{ℓ}) : Topology A.PrimeSpec := (OrdAlg.PrimeSpec.OpenBasis A).Topology def PrimePres.InducedMap.Continuous {X : OrdAlg.{ℓ₁}} {Y : OrdAlg.{ℓ₂}} (r : OrdRel X Y) (rPP : r.rel.PrimePres) : Continuous (OrdAlg.PrimeSpec.Topology Y) (OrdAlg.PrimeSpec.Topology X) (PrimePres.InducedMap @rPP) := begin let c : (OrdAlg.PrimeSpec.OpenBasis X).OI → (OrdAlg.PrimeSpec.Topology Y).OI := λ x y, y = r.rel.Fn x, apply OpenBasis.Continuous c, intro oix, apply funext, intro p, apply iff.to_eq, apply iff.intro, { intro H, existsi PreImage (PrimePres.InducedMap @rPP) (PrimeSpec.BasicOpen oix), refine exists.intro _ _, { existsi r.rel.Fn oix, apply and.intro rfl, rw PrimePres.InducedMap.BasicPreImage, trivial }, { intros x Hx, exact H Hx } }, { intro H, cases H with U H, cases H with H Hpu, cases H with V H, cases H with E₁ E₂, have E : V = r.rel.Fn oix := E₁, subst E, clear E₁, have E := E₂.symm, subst E, clear E₂, intros x Hx, cases Hx with Hx H, cases H with y H, apply Hpu (and.intro _ H.1), existsi x, exact and.intro Hx H.2 } end -- def Alg.PrimeSpec.OpenBasis (A : Alg.{ℓ}) : OpenBasis A.PrimeSpec -- := { Open := λ U, ∃ (xs : list A.τ), U = PrimeSpec.BasicOpen (λ x, x ∈ xs) -- , Cover := begin -- apply funext, intro p, -- apply iff.to_eq, -- apply iff.intro, -- { intro T, clear T, -- existsi (λ x, true), -- apply exists.intro, -- { existsi list.nil, -- apply funext, intro p', -- apply iff.to_eq, -- apply iff.intro, -- { intro T, clear T, -- intros x Hx, -- exact Hx.1 -- }, -- { intro H, constructor } -- }, -- { constructor } -- }, -- { intro H, constructor } -- end -- , Ointer := begin -- intros U₁ U₂ H₁ H₂, -- cases H₁ with L₁ E₁, -- cases H₂ with L₂ E₂, -- subst E₁, subst E₂, -- existsi list.append L₁ L₂, -- apply funext, intro p, -- apply iff.to_eq, -- apply iff.intro, -- { intros H x Hx, -- have Qx : x ∈ L₁ ∨ x ∈ L₂, from set.in_append Hx.1, -- cases Qx with Qx Qx, -- { exact H.1 (and.intro Qx Hx.2) }, -- { exact H.2 (and.intro Qx Hx.2) } -- }, -- { intro H, -- apply and.intro, -- { intros x Hx, -- have Qx : x ∈ list.append L₁ L₂, from set.in_append_left Hx.1, -- exact H (and.intro Qx Hx.2) -- }, -- { intros x Hx, -- have Qx : x ∈ list.append L₁ L₂, from set.in_append_right Hx.1, -- exact H (and.intro Qx Hx.2) -- } -- } -- end -- } -- def Alg.PrimeSpec.Topology (A : Alg.{ℓ}) : Topology A.PrimeSpec -- := (Alg.PrimeSpec.OpenBasis A).Topology -- def PrimePres.InducedMap.Continuous {X : Alg.{ℓ₁}} {Y : Alg.{ℓ₂}} (r : Rel X Y) -- (rPP : r.PrimePres) -- (rFI : r.FinIm) -- : Continuous (Alg.PrimeSpec.Topology Y) (Alg.PrimeSpec.Topology X) -- (PrimePres.InducedMap @rPP) -- := begin -- apply OpenBasis.Continuous, -- intros U Uopen, -- cases Uopen with xs E, subst E, -- have Q : ∃ (ys : list Y.τ) -- , (∀ {y}, y ∈ ys → ∃ x, x ∈ xs ∧ r x y) -- ∧ (∀ {x y}, x ∈ xs ∧ r x y → y ∈ ys) -- , from begin -- induction xs with x xs, -- { existsi list.nil, apply and.intro, -- { intros y Hy, exact false.elim Hy }, -- { intros x y Hx, exact false.elim Hx.1 } -- }, -- { cases ih_1 with ys' Hys' x xs, -- cases rFI x with ys Hys, -- existsi list.append ys ys', -- apply and.intro, -- { intros y Hy, -- have Hy' : y ∈ ys ∨ y ∈ ys', from set.in_append Hy, -- cases Hy' with Hy' Hy', -- { existsi x, -- apply and.intro, -- { exact or.inl rfl }, -- { exact (Hys _).2 Hy' } -- }, -- { cases Hys'.1 Hy' with x' Hx', -- existsi x', -- refine and.intro (or.inr Hx'.1) Hx'.2, -- } -- }, -- { intros x' y Hx'y, -- cases Hx'y with Hx' Rx'y, -- cases Hx' with Hx' Hx', -- { subst Hx', -- have Q : y ∈ ys := (Hys _).1 Rx'y, -- exact set.in_append_left Q -- }, -- { dsimp at Hx', -- have Q : y ∈ ys' := Hys'.2 (and.intro Hx' Rx'y), -- exact set.in_append_right Q -- } -- } -- } -- end, -- cases Q with ys Hys, -- let W : set Y.PrimeSpec := PrimeSpec.BasicOpen (λ y, y ∈ ys), -- existsi (eq W), -- apply and.intro, -- { intros W' E, -- have E' : W = W', from E, subst E', -- existsi ys, trivial -- }, -- { apply funext, intro p, -- apply iff.to_eq, -- apply iff.intro, -- { intro H, -- existsi W, -- apply exists.intro rfl, -- intros y Hy, -- cases (Hys.1 Hy.1) with x Hx, -- apply @H x, -- apply and.intro Hx.1, -- existsi y, -- exact and.intro Hy.2 Hx.2, -- }, -- { intros H x Hx, -- cases H with W' H, -- cases H with E Hp, -- have E' : W = W', from E, subst E', clear E, -- apply Rel.FnInv.elim Hx.2, -- intros y Hy Rxy, -- refine Hp (and.intro _ Hy), -- exact Hys.2 (and.intro Hx.1 Rxy) -- } -- } -- end -- Here we allow C to be an arbitrary set, but in practice the only -- sets worth considering are those which are intersections of prime -- sets. def PrimeSpec.BasicClosed {A : OrdAlg.{ℓ}} (C : Set A.alg) : set A.PrimeSpec := λ p, C ⊆ p.set -- When S is finite, BasicOpen S is an open set in the sense that -- it is a complement of a finite union of closed sets. def PrimeSpec.BasicOpen.IsOpen {A : OrdAlg.{ℓ}} (S : Set A.alg) : PrimeSpec.BasicOpen S = set.compl (set.sUnion ((λ s, PrimeSpec.BasicClosed (eq s)) <$> S)) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intros H Hp, cases Hp with T Hp, cases Hp with HT Hs, cases HT with t HT, refine H (and.intro HT.1 _), have E : T = PrimeSpec.BasicClosed (eq t) := HT.2.symm, subst E, exact Hs rfl }, { intros Hp x Hx, apply Hp, existsi (PrimeSpec.BasicClosed (eq x)), constructor, { existsi x, exact and.intro Hx.1 rfl }, { intros x' Hx', have E : x = x' := Hx', subst E, exact Hx.2 } } end -- BasicClosed I really is a closed set. def PrimeSpec.BasicClosed.IsClosed {A : OrdAlg.{ℓ}} (I : Set A.alg) : PrimeSpec.BasicClosed I = set.compl (set.sUnion ((λ i, PrimeSpec.BasicOpen (eq i)) <$> I)) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intros H Hp, cases Hp with U HU, cases HU with HU Hp, cases HU with i HU, cases HU with Hi E, subst E, exact Hp (and.intro rfl (H Hi)), }, { intros H x Ix, apply classical.by_contradiction, intro C, apply H, existsi (PrimeSpec.BasicOpen (eq x)), apply exists.intro, { existsi x, exact and.intro Ix rfl }, { intros x' Hx', refine C (cast _ Hx'.2), have E : x = x' := Hx'.1, subst E } } end def PrimeSpec.BasicClosed.intersection {A : OrdAlg.{ℓ}} (I₁ I₂ : Set A.alg) : PrimeSpec.BasicClosed (I₁ ∪ I₂) = PrimeSpec.BasicClosed I₁ ∩ PrimeSpec.BasicClosed I₂ := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intro H, apply and.intro, { intros a Ha, exact H (or.inl Ha) }, { intros a Ha, exact H (or.inr Ha) }, }, { intros H a Ha, cases Ha with Ha Ha, { exact H.1 Ha }, { exact H.2 Ha } } end def PrimeSpec.BasicClosed.union {A : OrdAlg.{ℓ}} (I₁ I₂ : Set A.alg) (I₁ideal : I₁.Ideal) (I₂ideal : I₂.Ideal) : PrimeSpec.BasicClosed I₁ ∪ PrimeSpec.BasicClosed I₂ = PrimeSpec.BasicClosed (I₁ ∩ I₂) ∩ (PrimeSpec.BasicClosed (I₁ <-> I₂) ∪ PrimeSpec.BasicClosed (I₂ <-> I₁)) := begin apply funext, intro p, apply iff.to_eq, apply iff.intro, { intro H, apply and.intro, { intros x Ix, cases H with H H, { exact H Ix.1 }, { exact H Ix.2 } }, { cases H with H H, { apply or.inl, intros x Hx, apply H, apply Hx.1 }, { apply or.inr, intros x Hx, apply H, apply Hx.1 } } }, { intro H, cases H with H₁ H₂, have Z : ¬ ((∃ x₁, x₁ ∈ set.diff I₁ p.set) ∧ (∃ x₂, x₂ ∈ set.diff I₂ p.set)), from begin intro Q, cases Q with Q₁ Q₂, cases Q₁ with x₁ Q₁, cases Q₂ with x₂ Q₂, cases classical.em (∃ z, A.alg.join x₁ x₂ z) with Jx Jx, { cases Jx with z Jx, have Hz : z ∈ p.set, from begin apply H₁, apply and.intro, { apply I₁ideal Q₁.1 Jx }, { apply I₂ideal Q₂.1 (A.alg.comm Jx) } end, cases p.prime _ _ _ Jx Hz with Z Z, { apply Q₁.2, assumption }, { apply Q₂.2, assumption } }, { cases H₂ with H₂ H₂, { apply Q₁.2, apply H₂, apply and.intro Q₁.1, existsi x₂, apply and.intro Q₂.1, intros z Jz, apply Jx, existsi z, exact Jz }, { apply Q₂.2, apply H₂, apply and.intro Q₂.1, existsi x₁, apply and.intro Q₁.1, intros z Jz, apply Jx, existsi z, exact (A.alg.comm Jz) } } end, clear H₁ H₂, have Helper : ∀ {P Q : Prop}, ¬ (P ∧ Q) → ¬ P ∨ ¬ Q, from begin intros P Q HH, cases classical.em P with HP HP, { cases classical.em Q with HQ HQ, { apply false.elim, apply HH, constructor, repeat { assumption } }, { exact or.inr HQ } }, { exact or.inl HP } end, cases Helper Z with ZZ ZZ, { have ZZ' := forall_not_of_not_exists ZZ, apply or.inl, intros x Ix, apply classical.by_contradiction, intro Px, apply ZZ' x (and.intro Ix Px) }, { have ZZ' := forall_not_of_not_exists ZZ, apply or.inr, intros x Ix, apply classical.by_contradiction, intro Px, apply ZZ' x (and.intro Ix Px) } } end def OrdAlg.ZeroPt (A : OrdAlg.{ℓ}) : A.PrimeSpec := { set := ∅ , prime := EmptyPrime _ , locl := Rel.FnInv.Empty _ } def ZeroPt.BasisEverywhere {X : OrdAlg.{ℓ}} {S : Set X.alg} : X.ZeroPt ∈ (OrdAlg.PrimeSpec.OpenBasis X).Open S := begin intro z, intro F, cases F with F₁ F₂, cases F₂ end def ZeroPt.Everywhere {X : OrdAlg.{ℓ}} {S : Set X.alg} : X.ZeroPt ∈ (OrdAlg.PrimeSpec.Topology X).Open (eq S) := begin existsi (OrdAlg.PrimeSpec.OpenBasis X).Open S, refine exists.intro _ _, { existsi S, exact and.intro rfl rfl }, { intro z, intro F, cases F with F₁ F₂, cases F₂ } end def OrdAlg.BigPt (A : OrdAlg.{ℓ}) (AUC : A.ord.UpClosed) (S : Set A.alg) (HS : A.ord.FnInv (JoinClosure S).Compl = (JoinClosure S).Compl) : A.PrimeSpec := { set := (JoinClosure S).Compl , prime := begin apply Set.JoinClosed.Complement_Prime, apply JoinClosure.JoinClosed end , locl := HS } def BigPt.In {X : OrdAlg.{ℓ}} {XUC : X.ord.UpClosed} {S : Set X.alg} {HS : X.ord.FnInv (JoinClosure S).Compl = (JoinClosure S).Compl} : X.BigPt @XUC S HS ∈ (OrdAlg.PrimeSpec.Topology X).Open (eq S) := begin existsi (OrdAlg.PrimeSpec.OpenBasis X).Open S, refine exists.intro _ _, { existsi S, exact and.intro rfl rfl }, { intros x F, cases F with HSx F, apply F, clear F, apply JoinClosure.gen, assumption } end -- def OrdAlg.BigPt (A : OrdAlg.{ℓ}) (AUC : A.ord.UpClosed) (S : Set A.alg) -- : A.PrimeSpec -- := { set := A.ord.FnInv (JoinClosure (A.ord.Fn S)).Compl -- , prime := begin -- apply UpClosed.PrimePres, -- { assumption }, -- { apply Set.JoinClosed.Complement_Prime, -- apply JoinClosure.JoinClosed -- } -- end -- , locl := begin -- intros x H, cases H with y H, -- cases H with H Rxy, -- cases H with z H, -- cases H with Hz Ryz, -- existsi z, -- refine and.intro Hz _, -- apply A.trans, -- repeat { assumption } -- end -- } -- def BigPt.In {X : OrdAlg.{ℓ}} {XUC : X.ord.UpClosed} {S : Set X.alg} -- : X.BigPt @XUC S ∈ (OrdAlg.PrimeSpec.Topology X).Open (eq S) -- := begin -- existsi (OrdAlg.PrimeSpec.OpenBasis X).Open S, -- refine exists.intro _ _, -- { existsi S, exact and.intro rfl rfl }, -- { intros x F, -- cases F with HSx F, -- cases F with y F, -- cases F with F Rxy, -- apply F, -- apply JoinClosure.gen, -- existsi x, exact and.intro HSx Rxy -- } -- end -- def OrdAlg.BigPt (A : OrdAlg.{ℓ}) (S : Set A.alg) : A.PrimeSpec -- := { set := set.sUnion ((λ (p : OrdAlg.PrimeSpec A), p.set) <$> (PrimeSpec.BasicOpen S)) -- , prime := Prime.Union _ -- begin -- intros p H, -- cases H with p' H, -- cases H with H E, -- subst E, -- exact p'.prime -- end -- , locl := begin -- intros x H, cases H with y H, -- cases H with H Rxy, -- cases H with S H, -- cases H with H HSy, -- cases H with p H, -- cases H with Hp E, -- subst E, -- existsi p.set, -- refine exists.intro _ _, -- { existsi p, exact and.intro @Hp rfl }, -- { exact p.locl ⟨_, and.intro HSy Rxy⟩ } -- end -- } -- def BigPt.In {X : OrdAlg.{ℓ}} {S : Set X.alg} -- : X.BigPt S ∈ (OrdAlg.PrimeSpec.Topology X).Open (eq S) -- := begin -- existsi (OrdAlg.PrimeSpec.OpenBasis X).Open S, -- refine exists.intro _ _, -- { existsi S, exact and.intro rfl rfl -- }, -- { intro z, intro F, -- cases F with F H, -- cases H with U H, -- cases H with H Hz, -- cases H with p H, -- cases H with Hp E, -- subst E, -- exact Hp (and.intro F Hz) -- } -- end end Sep
4a70e4772e561b22040f5e2aea24acec30c712b4
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/module/linear_map.lean
6fc8cd1d987c1144b8be4ff1dfc953acd87409aa
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,576
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [semimodule R M] [semimodule R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance compatible_smul.is_scalar_tower {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [semimodule S M] [is_scalar_tower R S M] [has_scalar R M₂] [semimodule S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : (f.to_add_monoid_hom : M → M₂) = f := rfl variable (R) /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ def restrict_scalars {S : Type*} [semiring S] [semimodule S M] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [semimodule ℤ M] [semimodule S M] [semimodule ℤ M₂] [semimodule S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simpa [add_smul] using ih }, case hn : n ih { simpa [sub_smul] using ih } end⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma injective_to_equiv : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := injective_to_equiv.eq_iff lemma injective_to_linear_map : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, injective_to_equiv $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := injective_to_linear_map.eq_iff end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : (e.to_equiv : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun [semimodule R M] [semimodule R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := injective_to_equiv e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := injective_to_equiv e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl end add_comm_monoid end linear_equiv
46059de6b0330fe79b3f89c4a5f7fe97667b0de4
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/e5.lean
f2497853a5c471666c2b3eb920897947fc3634ad
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,562
lean
prelude definition Prop := Sort.{0} definition false : Prop := ∀ x : Prop, x check false theorem false.elim (C : Prop) (H : false) : C := H C definition Eq {A : Type} (a b : A) := ∀ P : A → Prop, P a → P b check Eq infix `=`:50 := Eq theorem refl {A : Type} (a : A) : a = a := λ P H, H definition true : Prop := false = false theorem trivial : true := refl false attribute [elab_as_eliminator] theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b := H1 _ H2 theorem symm {A : Type} {a b : A} (H : a = b) : b = a := subst H (refl a) theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H2 H1 inductive nat : Type | zero : nat | succ : nat → nat namespace nat end nat open nat print "using strict implicit arguments" definition symmetric {A : Type} (R : A → A → Prop) := ∀ ⦃a b⦄, R a b → R b a check symmetric constant p : nat → nat → Prop check symmetric p axiom H1 : symmetric p axiom H2 : p zero (succ zero) check H1 check H1 H2 print "------------" print "using implicit arguments" definition symmetric2 {A : Type} (R : A → A → Prop) := ∀ {a b}, R a b → R b a check symmetric2 check symmetric2 p axiom H3 : symmetric2 p axiom H4 : p zero (succ zero) check H3 check H3 H4 print "-----------------" print "using strict implicit arguments (ASCII notation)" definition symmetric3 {A : Type} (R : A → A → Prop) := ∀ {{a b}}, R a b → R b a check symmetric3 check symmetric3 p axiom H5 : symmetric3 p axiom H6 : p zero (succ zero) check H5 check H5 H6
d0bdd6649c0dacf58c8a20bb0cd89d9f7b93a982
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/algebra/big_operators.lean
08aaa7d864139c1a3c700835374cd78d85320dce
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
30,739
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 Some big operators for lists and finite sets. -/ import data.list.basic data.list.perm data.finset import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive finset.sum] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1 @[to_additive finset.sum_eq_fold] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive finset.sum_empty] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive finset.sum_insert] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive finset.sum_singleton] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive finset.sum_const_zero] prod_const_one @[simp, to_additive finset.sum_image] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive sum_map] lemma prod_map [comm_monoid γ] (s : finset α) (e : α ↪ β) (f : β → γ): (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive finset.sum_congr] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive finset.sum_union_inter] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive finset.sum_union] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive finset.sum_sdiff] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive finset.sum_bind] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive finset.sum_product] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive finset.sum_sigma] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive finset.sum_image'] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive finset.sum_add_distrib] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive finset.sum_comm] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom (λ _ _, is_monoid_hom.map_mul g)) @[to_additive finset.sum_hom_rel] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive finset.sum_subset] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive sum_filter] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive finset.sum_eq_single] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive finset.sum_attach] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive finset.sum_bij] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive finset.sum_bij_ne_zero] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive finset.exists_ne_zero_of_sum_ne_zero] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive finset.sum_range_succ] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive finset.sum_involution] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive finset.sum_eq_zero] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_hom [add_comm_monoid β] [add_comm_monoid γ] (g : β → γ) [is_add_monoid_hom g] : s.sum (λx, g (f x)) = g (s.sum f) := eq.trans (by rw is_add_monoid_hom.map_zero g; refl) (fold_hom (λ _ _, is_add_monoid_hom.map_add g)) attribute [to_additive finset.sum_hom] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive finset.sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive finset.sum_const] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive finset.sum_range_succ'] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)):= begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive finset.sum_neg_distrib] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section ordered_cancel_comm_monoid variables [decidable_eq α] [ordered_cancel_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_le_zero (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) end ordered_cancel_comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, 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, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind 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, injective_pi_cons 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', ext ⟨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 end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum' : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum' (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum' h) lemma sum_le_zero' (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum' h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ zero_le_sum' $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (zero_le_sum' this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_le_zero' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset section geom_sum open finset theorem geom_sum_mul_add [semiring α] (x : α) : ∀ (n : ℕ), ((range n).sum (λ i, (x+1)^i)) * x + 1 = (x+1)^n | 0 := by simp | (n+1) := calc (range (n + 1)).sum (λi, (x + 1) ^ i) * x + 1 = (x + 1)^n * x + (((range n).sum (λ i, (x+1)^i)) * x + 1) : by simp [range_add_one, add_mul] ... = (x + 1)^n * x + (x + 1)^n : by rw geom_sum_mul_add n ... = (x + 1) ^ (n + 1) : by simp [pow_add, mul_add] theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : ((range n).sum (λ i, x^i)) * (x-1) = x^n-1 := have _ := geom_sum_mul_add (x-1) n, by rw [sub_add_cancel] at this; rw [← this, add_sub_cancel] theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (range n).sum (λ i, x^i) = (x^n-1)/(x-1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (range n).sum (λ m, x⁻¹ ^ m) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * x⁻¹ ^ n = x⁻¹ ^ n * x, from nat.cases_on n (by simp) (λ _, by conv { to_rhs, rw [pow_succ', mul_assoc, inv_mul_cancel hx0, mul_one] }; rw [pow_succ, ← mul_assoc, mul_inv_cancel hx0, one_mul]), by rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄] end geom_sum namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum end finset section group open list variables [group α] [group β] @[to_additive is_add_group_hom.sum] theorem is_group_hom.prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_group_hom.mul f, is_group_hom.one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.one f, simp only [prod_cons, is_group_anti_hom.mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.multiset_sum] lemma is_group_hom.multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.prod f l] @[to_additive is_add_group_hom.finset_sum] lemma is_group_hom.finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := ⟨assume a b, by simp only [λc, is_group_hom.mul (f c), finset.prod_mul_distrib]⟩ attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
8ce99a87133422ec7929ac5c59587c506d199883
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/stream/defs.lean
67ae6bcd57d83de5868953f9d26770ff45fb1473
[ "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
5,209
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 -/ /-! # Definition of `stream` and functions on streams A stream `stream α` is an infinite sequence of elements of `α`. One can also think about it as an infinite list. In this file we define `stream` and some functions that take and/or return streams. -/ universes u v w /-- A stream `stream α` is an infinite sequence of elements of `α`. -/ def stream (α : Type u) := nat → α open nat namespace stream variables {α : Type u} {β : Type v} {δ : Type w} /-- Prepend an element to a stream. -/ def cons (a : α) (s : stream α) : stream α | 0 := a | (n + 1) := s n notation h :: t := cons h t /-- Head of a stream: `stream.head s = stream.nth 0 s`. -/ def head (s : stream α) : α := s 0 /-- Tail of a stream: `stream.tail (h :: t) = t`. -/ def tail (s : stream α) : stream α := λ i, s (i+1) /-- Drop first `n` elements of a stream. -/ def drop (n : nat) (s : stream α) : stream α := λ i, s (i+n) /-- `n`-th element of a stream. -/ def nth (s : stream α) (n : ℕ) : α := s n /-- Proposition saying that all elements of a stream satisfy a predicate. -/ def all (p : α → Prop) (s : stream α) := ∀ n, p (nth s n) /-- Proposition saying that at least one element of a stream satisfies a predicate. -/ def any (p : α → Prop) (s : stream α) := ∃ n, p (nth s n) /-- `a ∈ s` means that `a = stream.nth n s` for some `n`. -/ instance : has_mem α (stream α) := ⟨λ a s, any (λ b, a = b) s⟩ /-- Apply a function `f` to all elements of a stream `s`. -/ def map (f : α → β) (s : stream α) : stream β := λ n, f (nth s n) /-- Zip two streams using a binary operation: `stream.nth n (stream.zip f s₁ s₂) = f (stream.nth s₁) (stream.nth s₂)`. -/ def zip (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : stream δ := λ n, f (nth s₁ n) (nth s₂ n) /-- The constant stream: `stream.nth n (stream.const a) = a`. -/ def const (a : α) : stream α := λ n, a /-- Iterates of a function as a stream. -/ def iterate (f : α → α) (a : α) : stream α := λ n, nat.rec_on n a (λ n r, f r) def corec (f : α → β) (g : α → α) : α → stream β := λ a, map f (iterate g a) def corec_on (a : α) (f : α → β) (g : α → α) : stream β := corec f g a def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f) /-- Use a state monad to generate a stream through corecursion -/ def corec_state {σ α} (cmd : state σ α) (s : σ) : stream α := corec prod.fst (cmd.run ∘ prod.snd) (cmd.run s) -- corec is also known as unfold def unfolds (g : α → β) (f : α → α) (a : α) : stream β := corec g f a /-- Interleave two streams. -/ def interleave (s₁ s₂ : stream α) : stream α := corec_on (s₁, s₂) (λ ⟨s₁, s₂⟩, head s₁) (λ ⟨s₁, s₂⟩, (s₂, tail s₁)) infix ` ⋈ `:65 := interleave /-- Elements of a stream with even indices. -/ def even (s : stream α) : stream α := corec (λ s, head s) (λ s, tail (tail s)) s /-- Elements of a stream with odd indices. -/ def odd (s : stream α) : stream α := even (tail s) /-- Append a stream to a list. -/ def append_stream : list α → stream α → stream α | [] s := s | (list.cons a l) s := a :: append_stream l s infix ` ++ₛ `:65 := append_stream /-- `take n s` returns a list of the `n` first elements of stream `s` -/ def take : ℕ → stream α → list α | 0 s := [] | (n+1) s := list.cons (head s) (take n (tail s)) /-- An auxiliary definition for `stream.cycle` corecursive def -/ protected def cycle_f : α × list α × α × list α → α | (v, _, _, _) := v /-- An auxiliary definition for `stream.cycle` corecursive def -/ protected def cycle_g : α × list α × α × list α → α × list α × α × list α | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) /-- Interpret a nonempty list as a cyclic stream. -/ def cycle : Π (l : list α), l ≠ [] → stream α | [] h := absurd rfl h | (list.cons a l) h := corec stream.cycle_f stream.cycle_g (a, l, a, l) /-- Tails of a stream, starting with `stream.tail s`. -/ def tails (s : stream α) : stream (stream α) := corec id tail (tail s) /-- An auxiliary definition for `stream.inits`. -/ def inits_core (l : list α) (s : stream α) : stream (list α) := corec_on (l, s) (λ ⟨a, b⟩, a) (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) /-- Nonempty initial segments of a stream. -/ def inits (s : stream α) : stream (list α) := inits_core [head s] (tail s) /-- A constant stream, same as `stream.const`. -/ def pure (a : α) : stream α := const a /-- Given a stream of functions and a stream of values, apply `n`-th function to `n`-th value. -/ def apply (f : stream (α → β)) (s : stream α) : stream β := λ n, (nth f n) (nth s n) infix ` ⊛ `:75 := apply -- input as \o* /-- The stream of natural numbers: `stream.nth n stream.nats = n`. -/ def nats : stream nat := λ n, n end stream
11d90396a0209a93c368eb2863de9570b3beabe1
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/set_theory/cardinal.lean
dd9da9c39f986a81ce70b3e39126300914146ae4
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
27,777
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.schroeder_bernstein logic.function open function lattice set local attribute [instance] classical.prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := assume a, quot.induction_on a $ λ α, ⟨embedding.refl _⟩, le_trans := assume a b c, quotient.induction_on₃ a b c $ assume α β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩, le_antisymm := assume a b, quotient.induction_on₂ a b $ assume α β ⟨e₁⟩ ⟨e₂⟩, quotient.sound (e₁.antisymm e₂), le_total := assume a b, quotient.induction_on₂ a b $ assume α β, embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦ulift empty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.ulift.symm⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).down.elim⟩ instance : has_one cardinal.{u} := ⟨⟦ulift unit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨⟨()⟩⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, ⟨()⟩, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.sum_congr equiv.ulift (equiv.refl α)) (equiv.empty_sum α)⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) $ equiv.trans (equiv.empty_prod α) equiv.ulift.symm⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) (equiv.unit_prod α)⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.trans (equiv.empty_arrow_equiv_unit α) $ equiv.ulift.symm⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.unit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans (equiv.arrow_unit_equiv_unit α) $ equiv.ulift.symm⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans $ equiv.bool_equiv_unit_sum_unit.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, have nonempty α, from ne_zero_iff_nonempty.1 heq, let a := classical.choice this in have (α → empty) ≃ empty, from ⟨λf, f a, λe a, e, assume f, (f a).rec_on (λ_, (λa', f a) = f), assume e, rfl⟩, quotient.sound ⟨equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans this equiv.ulift.symm⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le (a : cardinal) : 0 ≤ a := quot.induction_on a $ λ α, ⟨embedding.of_not_nonempty $ λ ⟨⟨a⟩⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add {a b c d : cardinal} : a ≤ b → c ≤ d → a + c ≤ b + d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul {a b c d : cardinal} : a ≤ b → c ≤ d → a * c ≤ b * d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left {a b c : cardinal} : a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := quotient.induction_on₃ a b c $ assume α β γ hα ⟨e⟩, have nonempty α, from classical.by_contradiction $ assume hnα, hα $ quotient.sound ⟨equiv.trans (equiv.empty_of_not_nonempty hnα) equiv.ulift.symm⟩, let ⟨a⟩ := this in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, le_imp_le_iff_lt_imp_lt.1 (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.comm_semiring, ..cardinal.linear_order } instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } theorem cantor (a : cardinal.{u}) : a < 2 ^ a := by rw ← prop_eq_two; exact quot.induction_on a (λ α, ⟨⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩) instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} (f : ι → cardinal) (a) : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := (sup_le _ _).2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := (sup_le _ _).2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.empty_of_not_nonempty $ by exact λ ⟨h⟩, h.elim0).trans equiv.ulift.symm⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, have : ∀ i, ¬ ∀ b, ∃ a, G ⟨i, a⟩ i = b, { refine λ i h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, simp [classical.not_forall] at this, exact let ⟨C, hc⟩ := classical.axiom_of_choice this, ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _), end end cardinal
d0f40f353b95394e3220dc32761762ef6ff1f887
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/finset/partition.lean
2f8973a38f6aee43fbd9552c19fbe51c82024ca0
[ "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
5,961
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Haitao Zhang Partitions of a type A into finite subsets of A. Such a partition is represented by a function f : A → finset A which maps every element a : A to its equivalence class. -/ import .card open function eq.ops variable {A : Type} variable [deceqA : decidable_eq A] include deceqA namespace finset definition is_partition (f : A → finset A) := ∀ a b, a ∈ f b = (f a = f b) structure partition : Type := (set : finset A) (part : A → finset A) (is_part : is_partition part) (complete : set = Union set part) attribute partition.part [coercion] namespace partition definition equiv_classes (f : partition) : finset (finset A) := image (partition.part f) (partition.set f) lemma equiv_class_disjoint (f : partition) (a1 a2 : finset A) (Pa1 : a1 ∈ equiv_classes f) (Pa2 : a2 ∈ equiv_classes f) : a1 ≠ a2 → a1 ∩ a2 = ∅ := assume Pne, have Pe1 : _, from exists_of_mem_image Pa1, obtain g1 Pg1, from Pe1, have Pe2 : _, from exists_of_mem_image Pa2, obtain g2 Pg2, from Pe2, begin apply inter_eq_empty_of_disjoint, apply disjoint.intro, rewrite [eq.symm (and.right Pg1), eq.symm (and.right Pg2)], intro x, rewrite [*partition.is_part f], intro Pxg1, rewrite [Pxg1, and.right Pg1, and.right Pg2], intro Pe, exact absurd Pe Pne end open nat theorem class_equation (f : @partition A _) : card (partition.set f) = finset.Sum (equiv_classes f) card := let s := (partition.set f), p := (partition.part f), img := image p s in calc card s = card (Union s p) : partition.complete f ... = card (Union img id) : image_eq_Union_index_image s p ... = card (Union (equiv_classes f) id) : rfl ... = finset.Sum (equiv_classes f) card : card_Union_of_disjoint _ id (equiv_class_disjoint f) lemma equiv_class_refl {f : A → finset A} (Pequiv : is_partition f) : ∀ a, a ∈ f a := take a, by rewrite [Pequiv a a] -- make it a little easier to prove union from restriction lemma restriction_imp_union {s : finset A} (f : A → finset A) (Pequiv : is_partition f) (Psub : ∀{a}, a ∈ s → f a ⊆ s) : s = Union s f := ext (take a, iff.intro (assume Pains, begin rewrite [(Union_insert_of_mem f Pains)⁻¹, Union_insert], apply mem_union_l, exact equiv_class_refl Pequiv a end) (assume Painu, have Pclass : ∃ x, x ∈ s ∧ a ∈ f x, from iff.elim_left (mem_Union_iff s f _) Painu, obtain x Px, from Pclass, have Pfx : f x ⊆ s, from Psub (and.left Px), mem_of_subset_of_mem Pfx (and.right Px))) lemma binary_union (P : A → Prop) [decP : decidable_pred P] {S : finset A} : S = {a ∈ S | P a} ∪ {a ∈ S | ¬(P a)} := ext take a, iff.intro (suppose a ∈ S, decidable.by_cases (suppose P a, mem_union_l (mem_sep_of_mem `a ∈ S` this)) (suppose ¬ P a, mem_union_r (mem_sep_of_mem `a ∈ S` this))) (suppose a ∈ sep P S ∪ {a ∈ S | ¬ P a}, or.elim (mem_or_mem_of_mem_union this) (suppose a ∈ sep P S, mem_of_mem_sep this) (suppose a ∈ {a ∈ S | ¬ P a}, mem_of_mem_sep this)) lemma binary_inter_empty {P : A → Prop} [decP : decidable_pred P] {S : finset A} : {a ∈ S | P a} ∩ {a ∈ S | ¬(P a)} = ∅ := inter_eq_empty (take a, assume Pa nPa, absurd (of_mem_sep Pa) (of_mem_sep nPa)) definition disjoint_sets (S : finset (finset A)) : Prop := ∀ s₁ s₂ (P₁ : s₁ ∈ S) (P₂ : s₂ ∈ S), s₁ ≠ s₂ → s₁ ∩ s₂ = ∅ lemma disjoint_sets_sep_of_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → disjoint_sets {s ∈ S | P s} := assume Pds, take s₁ s₂, assume P₁ P₂, Pds s₁ s₂ (mem_of_mem_sep P₁) (mem_of_mem_sep P₂) lemma binary_inter_empty_Union_disjoint_sets {P : finset A → Prop} [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → Union {s ∈ S | P s} id ∩ Union {s ∈ S | ¬P s} id = ∅ := assume Pds, inter_eq_empty (take a, assume Pa nPa, obtain s Psin Pains, from iff.elim_left !mem_Union_iff Pa, obtain t Ptin Paint, from iff.elim_left !mem_Union_iff nPa, have s ≠ t, from assume Peq, absurd (Peq ▸ of_mem_sep Psin) (of_mem_sep Ptin), have e₁ : s ∩ t = empty, from Pds s t (mem_of_mem_sep Psin) (mem_of_mem_sep Ptin) `s ≠ t`, have a ∈ s ∩ t, from mem_inter Pains Paint, have a ∈ empty, from e₁ ▸ this, absurd this !not_mem_empty) section variables {B: Type} [deceqB : decidable_eq B] include deceqB lemma binary_Union (f : A → finset B) {P : A → Prop} [decP : decidable_pred P] {s : finset A} : Union s f = Union {a ∈ s | P a} f ∪ Union {a ∈ s | ¬P a} f := begin rewrite [@binary_union _ _ P _ s at {1}], apply Union_union, exact binary_inter_empty end end open nat section variables {B : Type} [acmB : add_comm_monoid B] include acmB lemma Sum_binary_union (f : A → B) (P : A → Prop) [decP : decidable_pred P] {S : finset A} : Sum S f = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f := calc Sum S f = Sum ({s ∈ S | P s} ∪ {s ∈ S | ¬(P s)}) f : binary_union ... = Sum {s ∈ S | P s} f + Sum {s ∈ S | ¬P s} f : Sum_union f binary_inter_empty end lemma card_binary_Union_disjoint_sets (P : finset A → Prop) [decP : decidable_pred P] {S : finset (finset A)} : disjoint_sets S → card (Union S id) = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card := assume Pds, calc card (Union S id) = card (Union {s ∈ S | P s} id ∪ Union {s ∈ S | ¬P s} id) : binary_Union ... = card (Union {s ∈ S | P s} id) + card (Union {s ∈ S | ¬P s} id) : card_union_of_disjoint (binary_inter_empty_Union_disjoint_sets Pds) ... = Sum {s ∈ S | P s} card + Sum {s ∈ S | ¬P s} card : by rewrite [*(card_Union_of_disjoint _ id (disjoint_sets_sep_of_disjoint_sets Pds))] end partition end finset
b1dbea3d8941bdeb5e5d8086602147f88b382c60
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/ideal/associated_prime.lean
5ed07421fc294f02bece3c72ae779ad8929717ab
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
6,311
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import linear_algebra.span import ring_theory.ideal.operations import ring_theory.finiteness import ring_theory.localization.ideal import ring_theory.ideal.minimal_prime /-! # Associated primes of a module We provide the definition and related lemmas about associated primes of modules. ## Main definition - `is_associated_prime`: `is_associated_prime I M` if the prime ideal `I` is the annihilator of some `x : M`. - `associated_primes`: The set of associated primes of a module. ## Main results - `exists_le_is_associated_prime_of_is_noetherian_ring`: In a noetherian ring, any `ann(x)` is contained in an associated prime for `x ≠ 0`. - `associated_primes.eq_singleton_of_is_primary`: In a noetherian ring, `I.radical` is the only associated prime of `R ⧸ I` when `I` is primary. ## Todo Generalize this to a non-commutative setting once there are annihilator for non-commutative rings. -/ variables {R : Type*} [comm_ring R] (I J : ideal R) (M : Type*) [add_comm_group M] [module R M] /-- `is_associated_prime I M` if the prime ideal `I` is the annihilator of some `x : M`. -/ def is_associated_prime : Prop := I.is_prime ∧ ∃ x : M, I = (R ∙ x).annihilator variables (R) /-- The set of associated primes of a module. -/ def associated_primes : set (ideal R) := { I | is_associated_prime I M } variables {I J M R} (h : is_associated_prime I M) variables {M' : Type*} [add_comm_group M'] [module R M'] (f : M →ₗ[R] M') lemma associate_primes.mem_iff : I ∈ associated_primes R M ↔ is_associated_prime I M := iff.rfl lemma is_associated_prime.is_prime : I.is_prime := h.1 lemma is_associated_prime.map_of_injective (h : is_associated_prime I M) (hf : function.injective f) : is_associated_prime I M' := begin obtain ⟨x, rfl⟩ := h.2, refine ⟨h.1, ⟨f x, _⟩⟩, ext r, rw [submodule.mem_annihilator_span_singleton, submodule.mem_annihilator_span_singleton, ← map_smul, ← f.map_zero, hf.eq_iff], end lemma linear_equiv.is_associated_prime_iff (l : M ≃ₗ[R] M') : is_associated_prime I M ↔ is_associated_prime I M' := ⟨λ h, h.map_of_injective l l.injective, λ h, h.map_of_injective l.symm l.symm.injective⟩ lemma not_is_associated_prime_of_subsingleton [subsingleton M] : ¬ is_associated_prime I M := begin rintro ⟨hI, x, hx⟩, apply hI.ne_top, rwa [subsingleton.elim x 0, submodule.span_singleton_eq_bot.mpr rfl, submodule.annihilator_bot] at hx end variable (R) lemma exists_le_is_associated_prime_of_is_noetherian_ring [H : is_noetherian_ring R] (x : M) (hx : x ≠ 0) : ∃ P : ideal R, is_associated_prime P M ∧ (R ∙ x).annihilator ≤ P := begin have : (R ∙ x).annihilator ≠ ⊤, { rwa [ne.def, ideal.eq_top_iff_one, submodule.mem_annihilator_span_singleton, one_smul] }, obtain ⟨P, ⟨l, h₁, y, rfl⟩, h₃⟩ := set_has_maximal_iff_noetherian.mpr H ({ P | (R ∙ x).annihilator ≤ P ∧ P ≠ ⊤ ∧ ∃ y : M, P = (R ∙ y).annihilator }) ⟨(R ∙ x).annihilator, rfl.le, this, x, rfl⟩, refine ⟨_, ⟨⟨h₁, _⟩, y, rfl⟩, l⟩, intros a b hab, rw or_iff_not_imp_left, intro ha, rw submodule.mem_annihilator_span_singleton at ha hab, have H₁ : (R ∙ y).annihilator ≤ (R ∙ a • y).annihilator, { intros c hc, rw submodule.mem_annihilator_span_singleton at hc ⊢, rw [smul_comm, hc, smul_zero] }, have H₂ : (submodule.span R {a • y}).annihilator ≠ ⊤, { rwa [ne.def, submodule.annihilator_eq_top_iff, submodule.span_singleton_eq_bot] }, rwa [← h₃ (R ∙ a • y).annihilator ⟨l.trans H₁, H₂, _, rfl⟩ H₁, submodule.mem_annihilator_span_singleton, smul_comm, smul_smul] end variable {R} lemma associated_primes.subset_of_injective (hf : function.injective f) : associated_primes R M ⊆ associated_primes R M' := λ I h, h.map_of_injective f hf lemma linear_equiv.associated_primes.eq (l : M ≃ₗ[R] M') : associated_primes R M = associated_primes R M' := le_antisymm (associated_primes.subset_of_injective l l.injective) (associated_primes.subset_of_injective l.symm l.symm.injective) lemma associated_primes.eq_empty_of_subsingleton [subsingleton M] : associated_primes R M = ∅ := begin ext, simp only [set.mem_empty_iff_false, iff_false], apply not_is_associated_prime_of_subsingleton end variables (R M) lemma associated_primes.nonempty [is_noetherian_ring R] [nontrivial M] : (associated_primes R M).nonempty := begin obtain ⟨x, hx⟩ := exists_ne (0 : M), obtain ⟨P, hP, _⟩ := exists_le_is_associated_prime_of_is_noetherian_ring R x hx, exact ⟨P, hP⟩, end variables {R M} lemma is_associated_prime.annihilator_le (h : is_associated_prime I M) : (⊤ : submodule R M).annihilator ≤ I := begin obtain ⟨hI, x, rfl⟩ := h, exact submodule.annihilator_mono le_top, end lemma is_associated_prime.eq_radical (hI : I.is_primary) (h : is_associated_prime J (R ⧸ I)) : J = I.radical := begin obtain ⟨hJ, x, e⟩ := h, have : x ≠ 0, { rintro rfl, apply hJ.1, rwa [submodule.span_singleton_eq_bot.mpr rfl, submodule.annihilator_bot] at e }, obtain ⟨x, rfl⟩ := ideal.quotient.mkₐ_surjective R _ x, replace e : ∀ {y}, y ∈ J ↔ x * y ∈ I, { intro y, rw [e, submodule.mem_annihilator_span_singleton, ← map_smul, smul_eq_mul, mul_comm, ideal.quotient.mkₐ_eq_mk, ← ideal.quotient.mk_eq_mk, submodule.quotient.mk_eq_zero] }, apply le_antisymm, { intros y hy, exact (hI.2 $ e.mp hy).resolve_left ((submodule.quotient.mk_eq_zero I).not.mp this) }, { rw hJ.radical_le_iff, intros y hy, exact e.mpr (I.mul_mem_left x hy) } end lemma associated_primes.eq_singleton_of_is_primary [is_noetherian_ring R] (hI : I.is_primary) : associated_primes R (R ⧸ I) = {I.radical} := begin ext J, rw [set.mem_singleton_iff], refine ⟨is_associated_prime.eq_radical hI, _⟩, rintro rfl, haveI : nontrivial (R ⧸ I) := ⟨⟨(I^.quotient.mk : _) 1, (I^.quotient.mk : _) 0, _⟩⟩, obtain ⟨a, ha⟩ := associated_primes.nonempty R (R ⧸ I), exact ha.eq_radical hI ▸ ha, rw [ne.def, ideal.quotient.eq, sub_zero, ← ideal.eq_top_iff_one], exact hI.1 end
85fa9861e556ae547f43fecafad8c61461a12e7e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/lazyUnfoldingPerfIssue.lean
af4ecfe10a3bf73c4d14630b33a119137d2ecb87
[ "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
2,042
lean
namespace Ex1 inductive T: Type := | mk: String → Option T → T def runT: T → Nat | .mk _ none => 0 | .mk _ (some t) => runT t class Run (α: Type) where run: α → Nat instance: Run T := ⟨runT⟩ def x := T.mk "PrettyLong" (some <| .mk "PrettyLong" none) theorem equivalent: Run.run x = Run.run x := by -- simp (config := { dsimp := false, decide := false, etaStruct := .none }) [Run.run] apply Eq.refl (runT x) example : Run.run x = Run.run x := by simp [Run.run] end Ex1 namespace Ex2 inductive Wrapper where | wrap: Wrapper def Wrapper.extend: Wrapper → (Unit × Unit) | .wrap => ((), ()) mutual inductive Op where | mk: String → Block → Op inductive Assign where | mk : String → Op → Assign inductive Block where | mk: Assign → Block | empty: Block end mutual def runOp: Op → Wrapper | .mk _ r => let r' := runBlock r; .wrap def runAssign: Assign → Wrapper | .mk _ op => runOp op def runBlock: Block → Wrapper | .mk a => runAssign a | .empty => .wrap end private def b: Assign := .mk "r" (.mk "APrettyLongString" .empty) theorem bug: (runAssign b).extend.snd = (runAssign b).extend.snd := by --unfold b -- extremely slow sorry end Ex2 namespace Ex3 inductive ProgramType := | Op | Assign | Block section set_option hygiene false notation "Op" => Program ProgramType.Op notation "Assign" => Program ProgramType.Assign notation "Block" => Program ProgramType.Block end inductive Program: (type: ProgramType) → Type := | mkOp: String → Block → Op | mkAssign: String → Op → Assign | mkBlock: Assign → Block | emptyBlock: Block def runBase: Program type → Nat | .mkOp _ v => let _ := runBase v; 0 | .mkAssign _ t => runBase t | .mkBlock u => runBase u | .emptyBlock => 0 class Run (α: Type) where run: α → Nat instance: Run Assign := ⟨runBase⟩ def x: Assign := .mkAssign "PrettyLong" <| .mkOp "PrettyLong" .emptyBlock -- Now runs fine theorem equivalent: Run.run x = Run.run x := by simp [Run.run] end Ex3
6b9528517b73f4f0a66ba1e62452d2e2b17a6c57
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/ordmap/ordset.lean
bf6dbbdba64a512496763139fa64368355221f08
[ "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
69,254
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.ordmap.ordnode import algebra.order.ring.defs import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {α : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≤ s) : ¬ s ≤ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) h₂) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≤ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode α → ℕ | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode α → Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized α l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized α (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized α t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ l x r, C l → C r → C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : ∀ {t : ordnode α}, sized t → size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, h₂, h₃⟩ := by rw [size, h₁, size_eq_real_size h₂, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node α s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : ∀ (t : ordnode α), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode α) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : ℕ) : Prop := l + r ≤ 1 ∨ (l ≤ delta * r ∧ r ≤ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := λ l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode α → Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced α) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := begin refine or_iff_not_imp_left.2 (λ h, _), refine ⟨_, h₂.resolve_left h⟩, cases H, { cases r₂, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := have l + r₂ ≤ 1 → balanced_sz l r₁, from λ H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (λ H, or.cases_on h₂ this (λ h₂, or.inr ⟨h₂, le_trans h₁ H.2⟩)) theorem balanced.dual : ∀ {t : ordnode α}, balanced t → balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode α → α → ordnode α → ordnode α | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode α → α → ordnode α → ordnode α | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l α l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : ∀ {t : ordnode α} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode α} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l α l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r α l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized α l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized α l) (hr : sized r) : size (@balance' α l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, all P t → all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, h₂, h₃⟩ := ⟨h₁.imp, H _ h₂, h₃.imp⟩ theorem any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, any P t → any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, λ h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, λ h, or.inr (or.inl h)⟩ theorem all_dual {P : α → Prop} : ∀ {t : ordnode α}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, λ ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : α → Prop} : ∀ {t}, all P t ↔ ∀ x, emem x t → P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : α → Prop} : ∀ {t}, any P t ↔ ∃ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : α} {t} : emem x t ↔ ∀ P, all P t → P x := ⟨λ h P al, all_iff_forall.1 al _ h, λ H, H _ $ all_iff_forall.2 $ λ _, id⟩ theorem all_node' {P l x r} : @all α P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all α P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all α P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all α P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all α P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all α P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all α P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all α P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : ∀ (t : ordnode α) (r : list α), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil α) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node α s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : α} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : ∀ t : ordnode α, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode α} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := and_iff_right_of_imp $ λ h, by rw [← length_to_list h₁, h, length_to_list h₂] /-! ### `mem` -/ theorem pos_size_of_mem [has_le α] [@decidable_rel α (≤)] {x : α} {t : ordnode α} (h : sized t) (h_mem : x ∈ t) : 0 < size t := by { cases t, { contradiction }, { simp [h.1] } } /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : ∀ t (x : α), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : α) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : ∀ t : ordnode α, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode α) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : ∀ t : ordnode α, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : ∀ s l (x : α) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : ∀ s l (x : α) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : α → Prop} : ∀ t (x : α), all P t → P x → P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, h₂, h₃⟩ hx := find_min'_all _ _ h₁ h₂ @[elab_as_eliminator] theorem find_max'_all {P : α → Prop} : ∀ (x : α) t, P x → all P t → P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, h₂, h₃⟩ := find_max'_all _ _ h₂ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode α) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node α ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] (x : α) : ∀ t : ordnode α, dual (ordnode.insert x t) = @ordnode.insert αᵒᵈ _ _ x (dual t) | nil := rfl | (node _ l y r) := begin have : @cmp_le αᵒᵈ _ _ x y = cmp_le y x := rfl, rw [ordnode.insert, dual, ordnode.insert, this, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance α l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊢, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : rrs = 1 := sr.2.2.1, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : rls = 1 := sr.2.1.1, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊢, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : lrs = 1 := sl.2.2.1, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : lls = 1 := sl.2.1.1, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≤ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≤ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≤ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : @balance_l α l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : ¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : ℕ) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_rfl, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_rfl⟩ }, { rintro ⟨h₁, h₂⟩, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm h₂ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≤ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, tsub_le_iff_left] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≤ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ x₂ r₁ r₂} (H : raised (size r₁) (size r₂)) : raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := begin dsimp [node', size], generalize_hyp : size r₂ = m at H ⊢, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l α l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, H₂⟩⟩ | ⟨r', e, H | ⟨H₁, H₂⟩⟩, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:ℕ)<_) }, { exact le_trans H₂ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 H₂ } } end theorem balance_sz_dual {l r} (H : (∃ l', raised (@size α l) l' ∧ balanced_sz l' (@size α r)) ∨ ∃ r', raised r' (size r) ∧ balanced_sz (size l) r') : (∃ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ λ _, and.imp_right balanced_sz.symm) (Exists.imp $ λ _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l α l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r α l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r α l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder α] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded : ordnode α → with_bot α → with_top α → Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ o₂ := bounded l o₁ ↑x ∧ bounded r ↑x o₂ theorem bounded.dual : ∀ {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂), @bounded αᵒᵈ _ (dual t) o₂ o₁ | nil o₁ o₂ h := by cases o₁; cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode α} {o₁ o₂} : bounded t o₁ o₂ ↔ @bounded αᵒᵈ _ (dual t) o₂ o₁ := ⟨bounded.dual, λ h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t ⊥ o₂ | nil o₁ o₂ h := by cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t o₁ ⊤ | nil o₁ o₂ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := h.weak_left.weak_right theorem bounded.mono_left {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t ↑y o → bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t o ↑x → bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : ∀ {t : ordnode α} {x y : α}, bounded t x y → x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, h₂⟩ := lt_trans h₁.to_lt h₂.to_lt theorem bounded.to_nil {t : ordnode α} : ∀ {o₁ o₂}, bounded t o₁ o₂ → bounded nil o₁ o₂ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₂ o₁ o₂ | none o₂ h₁ h₂ := h₂.weak_left | (some y) o₂ h₁ h₂ := h₂.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₁ o₁ o₂ | o₁ none h₁ h₂ := h₁.weak_right | o₁ (some y) h₁ h₂ := h₁.mono_right (le_of_lt h₂.to_lt) theorem bounded.mem_lt : ∀ {t o} {x : α}, bounded t o ↑x → all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_lt.imp (λ z h, lt_trans h h₂.to_lt), h₂.to_lt, h₂.mem_lt⟩ theorem bounded.mem_gt : ∀ {t o} {x : α}, bounded t ↑x o → all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp (λ z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil o₁ ↑x → all (< x) t → bounded t o₁ ↑x | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁, h₂.of_lt al₂ al₃⟩ theorem bounded.of_gt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil ↑x o₂ → all (> x) t → bounded t ↑x o₂ | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁.of_gt al₂ al₁, h₂⟩ theorem bounded.to_sep {t₁ t₂ o₁ o₂} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ ↑x o₂) : t₁.all (λ y, t₂.all (λ z : α, y < z)) := h₁.mem_lt.imp $ λ y yx, h₂.mem_gt.imp $ λ z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder α] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot α) (t : ordnode α) (hi : with_top α) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode α) : Prop := valid' ⊥ t ⊤ theorem valid'.mono_left {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x t₂ o₂) : valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ ↑x o₂) : valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil ↑x o₂) (h₂ : all (> x) t) : valid' ↑x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem valid'.valid {t o₁ o₂} (h : @valid' α _ o₁ t o₂) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : bounded nil o₁ o₂) : valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil α) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : ∀ {t : ordnode α} {o₁ o₂} (h : valid' o₁ t o₂), @valid' αᵒᵈ _ o₂ (dual t) o₁ | nil o₁ o₂ h := valid'_nil h.1.dual | (node s l x r) o₁ o₂ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode α} {o₁ o₂} : valid' o₁ t o₂ ↔ @valid' αᵒᵈ _ o₂ (dual t) o₁ := ⟨valid'.dual, λ h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode α} : valid t → @valid αᵒᵈ _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode α} : valid t ↔ @valid αᵒᵈ _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' ↑x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node α s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node α s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil ↑x o₂) : valid' o₁ (singleton x : ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (or.inl zero_le_one) rfl theorem valid_singleton {x : α} : valid (singleton x : ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by linarith theorem valid'.node4_l_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≤ 1) ∨ (0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r)) : valid' o₁ (@node4_l α l x m y r) o₂ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mr₂, cases not_le_of_lt Hm mr₂ }, rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂, by_cases mm : size ml + size mr ≤ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, le_zero_iff] at mm₂, rw [ml0, mm₂] at mm, cases mm dec_trivial }, have : 2 * size l ≤ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mm₂, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lr₂ mr₂ mm₁) }, { exact valid'.node4_l_lemma₂ mr₂ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemma₄ lr₁ mr₂ mm₁ }, { exact valid'.node4_l_lemma₅ lr₂ mr₁ mm₂ } } end theorem valid'.rotate_l_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by linarith theorem valid'.rotate_l_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@rotate_l α l x r) o₂ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 → size rl + size rr ≤ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact λ h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := λ l0 : 1 ≤ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1, {intros, linarith}, have hlp : size l > 0 → ¬ size rl + size rr ≤ 1 := λ l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊢, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hb₂⟩, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hb₂ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemma₂ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hb₂ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@rotate_r α l x r) o₂ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance' α l x r) o₂ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 H₂ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {α l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := begin suffices : @size α r ≤ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≤ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, h₂⟩, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans h₂ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance' α l x r) o₂ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance α l x r) o₂ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance_l α l x r) o₂ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace H₂ : _ ≤ 3 * _ := H₂ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l α l x r) o₂ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@balance_r α l x r) o₂ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ H₂ H₃ end theorem valid'.balance_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r α l x r) o₂ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (@erase_max α (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊢, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' ↑(find_min' l x) (@erase_min α (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : ∀ {t} (h : @valid α _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid α _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact λ x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (λ a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (λ a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact λ y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (λ a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ λ x hx, sep.imp $ λ y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ λ y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ o₂} (hl : valid' o₁ l ↑(x:α)) (hr : valid' ↑x r o₂) : balanced_sz (size l) (size r) → valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node α ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hr₂⟩, {linarith}, suffices H₂, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ H₂ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hr₂ ⊢, linarith } end theorem valid'.merge_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) : valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ o₂ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ o₂, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ λ x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ λ x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (λ x, r.all (λ y, x < y))) : valid (@merge α l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil ↑x o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ o₂ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ o₂ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≤) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, ordnode.insert x t = insert_with (λ _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (λ _ _, ⟨le_rfl, le_rfl⟩) h theorem insert'_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (λ _, id) h theorem valid'.map_aux {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' (option.map f a₁) (map f t) (option.map f a₂) ∧ (map f t).size = t.size := begin induction t generalizing a₁ a₂, { simp [map], apply valid'_nil, cases a₁, { trivial }, cases a₂, { trivial }, simp [bounded], exact f_strict_mono h.ord }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, simp [map], split, { exact and.intro t_l_valid.ord t_r_valid.ord }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.sz.1 }, { exact t_l_valid.sz }, { exact t_r_valid.sz } }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.bal.1 }, { exact t_l_valid.bal }, { exact t_r_valid.bal } } }, end theorem map.valid {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t} (h : valid t) : valid (map f t) := (valid'.map_aux f_strict_mono h).1 theorem valid'.erase_aux [@decidable_rel α (≤)] (x : α) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' a₁ (erase x t) a₂ ∧ raised (erase x t).size t.size := begin induction t generalizing a₁ a₂, { simp [erase, raised], exact h }, { simp [erase], have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, cases (cmp_le x t_x); simp [erase._match_1]; rw h.sz.1, { suffices h_balanceable, split, { exact valid'.balance_r t_l_valid h.right h_balanceable }, { rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable, repeat { apply raised.add_right }, exact t_l_size }, { left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } }, { have h_glue := valid'.glue h.left h.right h.bal.1, cases h_glue with h_glue_valid h_glue_sized, split, { exact h_glue_valid }, { right, rw h_glue_sized } }, { suffices h_balanceable, split, { exact valid'.balance_l h.left t_r_valid h_balanceable }, { rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable, apply raised.add_right, apply raised.add_left, exact t_r_size }, { right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } }, end theorem erase.valid [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (erase x t) := (valid'.erase_aux x h).1 theorem size_erase_of_mem [@decidable_rel α (≤)] {x : α} {t a₁ a₂} (h : valid' a₁ t a₂) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := begin induction t generalizing a₁ a₂ h h_mem, { contradiction }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, unfold has_mem.mem mem at h_mem, unfold erase, cases (cmp_le x t_x); simp [mem._match_1] at h_mem; simp [erase._match_1], { have t_ih_l := t_ih_l' h_mem, clear t_ih_l' t_ih_r', have t_l_h := valid'.erase_aux x h.left, cases t_l_h with t_l_valid t_l_size, rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))), rw [t_ih_l, h.sz.1], have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem, cases t_l.size with t_l_size, { cases h_pos_t_l_size }, simp [nat.succ_add] }, { rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl }, { have t_ih_r := t_ih_r' h_mem, clear t_ih_l' t_ih_r', have t_r_h := valid'.erase_aux x h.right, cases t_r_h with t_r_valid t_r_size, rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))), rw [t_ih_r, h.sz.1], have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem, cases t_r.size with t_r_size, { cases h_pos_t_r_size }, simp [nat.succ_add, nat.add_succ] } }, end end end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type*) [preorder α] := {t : ordnode α // t.valid} namespace ordset open ordnode variable [preorder α] /-- O(1). The empty set. -/ def nil : ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : ordset α := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset α) := ⟨nil⟩ instance : inhabited (ordset α) := ⟨nil⟩ instance : has_singleton α (ordset α) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset α) : Prop := s = ∅ theorem empty_iff {s : ordset α} : s = ∅ ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, λ h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty α _) := λ s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total α (≤)] [@decidable_rel α (≤)] : has_insert α (ordset α) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variables [@decidable_rel α (≤)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : α) (s : ordset α) : bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : α) (s : ordset α) : option α := ordnode.find x s.val instance : has_mem α (ordset α) := ⟨λ x s, mem x s⟩ instance mem.decidable (x : α) (s : ordset α) : decidable (x ∈ s) := bool.decidable_eq _ _ theorem pos_size_of_mem {x : α} {t : ordset α} (h_mem : x ∈ t) : 0 < size t := begin simp [has_mem.mem, mem] at h_mem, apply ordnode.pos_size_of_mem t.property.sz h_mem, end end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.erase x s.val, ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {β} [preorder β] (f : α → β) (f_strict_mono : strict_mono f) (s : ordset α) : ordset β := ⟨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.property⟩ end ordset
e45c25ea4c64dfc3acbc5c28f28d9b6730a48bba
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/uniform_ring.lean
0d3d4e4b09f7c5f5a7a5049f561c0c1255a53760
[]
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
5,285
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.group_completion import Mathlib.topology.algebra.ring import Mathlib.PostPort universes u_1 u_2 u namespace Mathlib namespace uniform_space.completion protected instance has_one (α : Type u_1) [ring α] [uniform_space α] : HasOne (completion α) := { one := ↑1 } protected instance has_mul (α : Type u_1) [ring α] [uniform_space α] : Mul (completion α) := { mul := function.curry (dense_inducing.extend sorry (coe ∘ function.uncurry Mul.mul)) } theorem coe_one (α : Type u_1) [ring α] [uniform_space α] : ↑1 = 1 := rfl theorem coe_mul {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] (a : α) (b : α) : ↑(a * b) = ↑a * ↑b := Eq.symm (dense_inducing.extend_eq (dense_inducing.prod dense_inducing_coe dense_inducing_coe) (continuous.comp (continuous_coe α) continuous_mul) (a, b)) theorem continuous_mul {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] : continuous fun (p : completion α × completion α) => prod.fst p * prod.snd p := sorry theorem continuous.mul {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] {β : Type u_2} [topological_space β] {f : β → completion α} {g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous fun (b : β) => f b * g b := continuous.comp continuous_mul (continuous.prod_mk hf hg) protected instance ring {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] : ring (completion α) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry /-- The map from a uniform ring to its completion, as a ring homomorphism. -/ def coe_ring_hom {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] : α →+* completion α := ring_hom.mk coe (coe_one α) sorry sorry sorry /-- The completion extension as a ring morphism. -/ def extension_hom {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous ⇑f) [complete_space β] [separated_space β] : completion α →+* β := (fun (hf : uniform_continuous ⇑f) => ring_hom.mk (completion.extension ⇑f) sorry sorry sorry sorry) sorry protected instance top_ring_compl {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] : topological_ring (completion α) := topological_ring.mk continuous_neg /-- The completion map as a ring morphism. -/ def map_ring_hom {α : Type u_1} [ring α] [uniform_space α] [topological_ring α] [uniform_add_group α] {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous ⇑f) : completion α →+* completion β := extension_hom (ring_hom.comp coe_ring_hom f) sorry protected instance comm_ring (R : Type u_2) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] : comm_ring (completion R) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry end uniform_space.completion namespace uniform_space theorem ring_sep_rel (α : Type u_1) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext fun (x y : α) => group_separation_rel x y theorem ring_sep_quot (α : Type u_1) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = ideal.quotient (ideal.closure ⊥) := eq.mpr (id (Eq._oldrec (Eq.refl (quotient (separation_setoid α) = ideal.quotient (ideal.closure ⊥))) (ring_sep_rel α))) (Eq.refl (quotient (submodule.quotient_rel (ideal.closure ⊥)))) /-- 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 (α : Type u_1) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ ideal.quotient (ideal.closure ⊥) := quotient.congr_right sorry /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ protected instance comm_ring {α : Type u_1} [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := eq.mpr sorry (ideal.quotient.comm_ring (ideal.closure ⊥)) protected instance topological_ring {α : Type u_1} [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := sorry
4f688fe878637bde3fac95a2e661e66f8e5f9954
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/universal/comparisons.lean
8c5c2b5607a766d29b6268e346837639ad2b29df
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
6,033
lean
import category_theory.limits open category_theory namespace category_theory.limits universes u v variables {C : Type u} [𝒞 : category.{u v} C] {Y Y₁ Y₂ Z : C} include 𝒞 @[reducible] def binary_product_comparison (t : span Y Z) (X' : C) : (X' ⟶ t.X) → (X' ⟶ Y) × (X' ⟶ Z) := λ φ, (φ ≫ t.π₁, φ ≫ t.π₂) def is_binary_product.comparison {t : span Y Z} [is_binary_product t] (X' : C) : is_equiv (binary_product_comparison t X') := { inv := λ p, is_binary_product.lift _ ⟨ ⟨ X' ⟩, p.1, p.2 ⟩, hom_inv_id' := begin tidy, symmetry, have := is_binary_product.uniq _ {to_shape := {X := X'}, π₁ := x ≫ t.π₁, π₂ := x ≫ t.π₂} x, apply this, -- TODO why can't we just `apply`? tidy, end } def is_binary_product.of_comparison {t : span Y Z} (w : Π X' : C, is_equiv (binary_product_comparison t X')) : is_binary_product t := { lift := λ s, @inv _ _ _ _ _ (w s.X) (s.π₁, s.π₂), fac₁' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p (s.π₁, s.π₂), tidy, end, fac₂' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p (s.π₁, s.π₂), tidy, end, uniq' := λ s m w₁ w₂, begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, obviously, end } @[reducible] def equalizer_comparison {f g : Y ⟶ Z} (t : fork f g) (X' : C) : (X' ⟶ t.X) → { h : X' ⟶ Y // h ≫ f = h ≫ g } := λ φ, ⟨ φ ≫ t.ι, by obviously ⟩ def is_equalizer.comparison {f g : Y ⟶ Z} {t : fork f g} (h : is_equalizer t) (X' : C) : is_equiv (equalizer_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.1, p.2 ⟩, hom_inv_id' := begin tidy, symmetry, apply h.uniq {to_shape := {X := X'}, ι := x ≫ t.ι} x, tidy, end } def is_equalizer.of_comparison {f g : Y ⟶ Z} {t : fork f g} (w : Π X' : C, is_equiv (equalizer_comparison t X')) : is_equalizer t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ s.ι, s.w ⟩, fac := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ s.ι, s.w ⟩, tidy, end, uniq := λ s m w', begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold equalizer_comparison at q, rw ← q, congr, exact w', end } @[reducible] def pullback_comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} (t : square r₁ r₂) (X' : C) : (X' ⟶ t.X) → { c : (X' ⟶ Y₁) × (X' ⟶ Y₂) // c.1 ≫ r₁ = c.2 ≫ r₂ } := λ φ, ⟨ (φ ≫ t.π₁, φ ≫ t.π₂), by obviously ⟩ def is_pullback.comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} {t : square r₁ r₂} (h : is_pullback t) (X' : C) : is_equiv (pullback_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.val.1, p.val.2 ⟩, hom_inv_id' := begin tidy, symmetry, apply h.uniq {to_shape := {X := X'}, π₁ := x ≫ t.π₁, π₂ := x ≫ t.π₂} x, tidy, end } def is_pullback.of_comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} {t : square r₁ r₂} (w : Π X' : C, is_equiv (pullback_comparison t X')) : is_pullback t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ (s.π₁, s.π₂), s.w ⟩, fac₁ := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ (s.π₁, s.π₂), s.w ⟩, tidy, end, fac₂ := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ (s.π₁, s.π₂), s.w ⟩, tidy, end, uniq := λ s m w₁ w₂, begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold pullback_comparison at q, rw ← q, congr, tidy, end } variables {J : Type v} [𝒥 : small_category J] include 𝒥 @[reducible] def limit_comparison {F : J ⥤ C} (t : cone F) (X' : C) : (X' ⟶ t.X) → { c : Π j : J, (X' ⟶ F j) // ∀ {j j' : J} (f : j ⟶ j'), c j ≫ F.map f = c j' } := λ φ, ⟨ λ j, φ ≫ t.π j, by obviously ⟩ def is_limit.comparison {F : J ⥤ C} {t : cone F} (h : is_limit t) (X' : C) : is_equiv (limit_comparison t X') := { inv := λ p, is_limit.lift _ ⟨ ⟨ X' ⟩, p.val, p.property ⟩, hom_inv_id' := begin tidy, symmetry, apply is_limit.uniq _ {to_shape := {X := X'}, π := λ j, x ≫ t.π j, w := by obviously } x, tidy, end } def is_limit.of_comparison {F : J ⥤ C} {t : cone F} (w : Π X' : C, is_equiv (limit_comparison t X')) : is_limit t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ s.π, s.w ⟩, fac' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ s.π, s.w ⟩, tidy, exact congr_fun q j -- TODO fix automation end, uniq' := λ s m w', begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold limit_comparison at q, rw ← q, congr, tidy, end } end category_theory.limits
7127d4cac1bb8accaabdbec86c42eb7110a833ca
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/analysis/special_functions/pow.lean
e1759fd5054bab5da2f6af807eefc3a7493ee6d6
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
70,135
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, smul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, smul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section lim open complex variables {α : Type*} lemma measurable.cpow [measurable_space α] {f g : α → ℂ} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x ^ g x) := measurable.ite (hf $ measurable_set_singleton _) (measurable.ite (hg $ measurable_set_singleton _) measurable_const measurable_const) (hf.clog.mul hg).cexp lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@has_fderiv_at_cpow (a, b) ha).continuous_at.tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := (has_strict_deriv_at_const_cpow h).continuous_at.tendsto.comp hf variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, { simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring }, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, { cases lt_or_eq_of_le h with h₂ h₂, { exact h₂ }, exfalso, apply h_2, exact eq.symm h₂ }, have hy : 0 < y, { cases lt_or_eq_of_le h₁ with h₂ h₂, { exact h₂ }, exfalso, apply h_3, exact eq.symm h₂ }, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section measurability_real open complex lemma measurable.rpow {α} [measurable_space α] {f g : α → ℝ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := measurable_re.comp $ ((measurable_of_real.comp hf).cpow (measurable_of_real.comp hg)) lemma measurable.rpow_const {α} [measurable_space α] {f : α → ℝ} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.rpow measurable_const lemma real.measurable_rpow_const {y : ℝ} : measurable (λ x : ℝ, x ^ y) := measurable_id.rpow_const end measurability_real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma of_real_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : nnreal.of_real (x ^ y) = (nnreal.of_real x) ^ y := begin nth_rewrite 0 ← nnreal.coe_of_real x hx, rw [←nnreal.coe_rpow, nnreal.of_real_coe], end end nnreal namespace measurable variables {α : Type*} [measurable_space α] lemma nnreal_rpow {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := (hf.nnreal_coe.rpow hg).subtype_mk lemma nnreal_rpow_const {f : α → ℝ≥0} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.nnreal_rpow measurable_const end measurable open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ℝ≥0∞) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma inv_rpow_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin by_cases h0 : x = 0, { rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], }, by_cases h_top : x = ⊤, { rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], }, rw ←coe_to_nnreal h_top, have h : x.to_nnreal ≠ 0, { rw [ne.def, to_nnreal_eq_zero_iff], simp [h0, h_top], }, rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv], { rw coe_eq_coe, exact nnreal.inv_rpow x.to_nnreal y, }, { simp [h], }, end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := begin by_cases h0 : z = 0, { simp [h0], }, rw ←ne.def at h0, have hz_pos : 0 < z, from lt_of_le_of_ne hz h0.symm, rw [div_eq_mul_inv, mul_rpow_of_nonneg x y⁻¹ hz, inv_rpow_of_pos hz_pos, ←div_eq_mul_inv], end lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := begin refine ⟨λ h, _, λ h, rpow_le_rpow h (le_of_lt hz)⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul, ←one_div], exact rpow_le_rpow h (by simp [le_of_lt hz]), end lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := begin refine ⟨λ h_lt, _, λ h, rpow_lt_rpow h hz⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul], exact rpow_lt_rpow h_lt (by simp [hz]), end lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ℝ≥0∞, y^x) := λ y z hyz, rpow_lt_rpow hyz hx end ennreal section measurability_ennreal variables {α : Type*} [measurable_space α] lemma ennreal.measurable_rpow : measurable (λ p : ℝ≥0∞ × ℝ, p.1 ^ p.2) := begin refine ennreal.measurable_of_measurable_nnreal_prod _ _, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const (measurable_fst.nnreal_rpow measurable_snd).ennreal_coe, exact measurable_set.inter (measurable_fst (measurable_set_singleton 0)) (measurable_snd measurable_set_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite measurable_set_Ioi measurable_const _, exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, }, end lemma measurable.ennreal_rpow {f : α → ℝ≥0∞} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := begin change measurable ((λ p : ℝ≥0∞ × ℝ, p.1 ^ p.2) ∘ (λ a, (f a, g a))), exact ennreal.measurable_rpow.comp (measurable.prod hf hg), end lemma measurable.ennreal_rpow_const {f : α → ℝ≥0∞} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.ennreal_rpow measurable_const lemma ennreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ℝ≥0∞, a ^ y) := measurable_id.ennreal_rpow_const lemma ae_measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ℝ≥0∞} {μ : measure_theory.measure α} (hf : ae_measurable f μ) {y : ℝ} : ae_measurable (λ a : α, (f a) ^ y) μ := ennreal.measurable_rpow_const.comp_ae_measurable hf end measurability_ennreal
4c29277451092691ed1e97133eda53179b9aef9b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/open_subgroup.lean
35d5a9753cca57122ca3621360250285a2c78e69
[ "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
10,274
lean
/- Copyright (c) 2019 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.ideal.basic import topology.algebra.ring.basic import topology.sets.opens /-! # Open subgroups of a topological groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This files builds the lattice `open_subgroup G` of open subgroups in a topological group `G`, and its additive version `open_add_subgroup`. This lattice has a top element, the subgroup of all elements, but no bottom element in general. The trivial subgroup which is the natural candidate bottom has no reason to be open (this happens only in discrete groups). Note that this notion is especially relevant in a non-archimedean context, for instance for `p`-adic groups. ## Main declarations * `open_subgroup.is_closed`: An open subgroup is automatically closed. * `subgroup.is_open_mono`: A subgroup containing an open subgroup is open. There are also versions for additive groups, submodules and ideals. * `open_subgroup.comap`: Open subgroups can be pulled back by a continuous group morphism. ## TODO * Prove that the identity component of a locally path connected group is an open subgroup. Up to now this file is really geared towards non-archimedean algebra, not Lie groups. -/ open topological_space open_locale topology /-- The type of open subgroups of a topological additive group. -/ @[ancestor add_subgroup] structure open_add_subgroup (G : Type*) [add_group G] [topological_space G] extends add_subgroup G := (is_open' : is_open carrier) /-- The type of open subgroups of a topological group. -/ @[ancestor subgroup, to_additive] structure open_subgroup (G : Type*) [group G] [topological_space G] extends subgroup G := (is_open' : is_open carrier) /-- Reinterpret an `open_subgroup` as a `subgroup`. -/ add_decl_doc open_subgroup.to_subgroup /-- Reinterpret an `open_add_subgroup` as an `add_subgroup`. -/ add_decl_doc open_add_subgroup.to_add_subgroup namespace open_subgroup open function topological_space variables {G : Type*} [group G] [topological_space G] variables {U V : open_subgroup G} {g : G} @[to_additive] instance has_coe_subgroup : has_coe_t (open_subgroup G) (subgroup G) := ⟨to_subgroup⟩ @[to_additive] lemma coe_subgroup_injective : injective (coe : open_subgroup G → subgroup G) | ⟨_, _⟩ ⟨_, _⟩ rfl := rfl @[to_additive] instance : set_like (open_subgroup G) G := { coe := λ U, U.1, coe_injective' := λ _ _ h, coe_subgroup_injective $ set_like.ext' h } @[to_additive] instance : subgroup_class (open_subgroup G) G := { mul_mem := λ U _ _, U.mul_mem', one_mem := λ U, U.one_mem', inv_mem := λ U _, U.inv_mem' } @[to_additive] instance has_coe_opens : has_coe_t (open_subgroup G) (opens G) := ⟨λ U, ⟨U, U.is_open'⟩⟩ @[simp, norm_cast, to_additive] lemma coe_coe_opens : ((U : opens G) : set G) = U := rfl @[simp, norm_cast, to_additive] lemma coe_coe_subgroup : ((U : subgroup G) : set G) = U := rfl @[simp, norm_cast, to_additive] lemma mem_coe_opens : g ∈ (U : opens G) ↔ g ∈ U := iff.rfl @[simp, norm_cast, to_additive] lemma mem_coe_subgroup : g ∈ (U : subgroup G) ↔ g ∈ U := iff.rfl @[ext, to_additive] lemma ext (h : ∀ x, x ∈ U ↔ x ∈ V) : (U = V) := set_like.ext h variable (U) @[to_additive] protected lemma is_open : is_open (U : set G) := U.is_open' @[to_additive] lemma mem_nhds_one : (U : set G) ∈ 𝓝 (1 : G) := is_open.mem_nhds U.is_open U.one_mem variable {U} @[to_additive] instance : has_top (open_subgroup G) := ⟨{ is_open' := is_open_univ, .. (⊤ : subgroup G) }⟩ @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : open_subgroup G) := trivial @[simp, norm_cast, to_additive] lemma coe_top : ((⊤ : open_subgroup G) : set G) = set.univ := rfl @[simp, norm_cast, to_additive] lemma coe_subgroup_top : ((⊤ : open_subgroup G) : subgroup G) = ⊤ := rfl @[simp, norm_cast, to_additive] lemma coe_opens_top : ((⊤ : open_subgroup G) : opens G) = ⊤ := rfl @[to_additive] instance : inhabited (open_subgroup G) := ⟨⊤⟩ @[to_additive] lemma is_closed [has_continuous_mul G] (U : open_subgroup G) : is_closed (U : set G) := begin apply is_open_compl_iff.1, refine is_open_iff_forall_mem_open.2 (λ x hx, ⟨(λ y, y * x⁻¹) ⁻¹' U, _, _, _⟩), { refine λ u hux hu, hx _, simp only [set.mem_preimage, set_like.mem_coe] at hux hu ⊢, convert U.mul_mem (U.inv_mem hux) hu, simp }, { exact U.is_open.preimage (continuous_mul_right _) }, { simp [one_mem] } end @[to_additive] lemma is_clopen [has_continuous_mul G] (U : open_subgroup G) : is_clopen (U : set G) := ⟨U.is_open, U.is_closed⟩ section variables {H : Type*} [group H] [topological_space H] /-- The product of two open subgroups as an open subgroup of the product group. -/ @[to_additive "The product of two open subgroups as an open subgroup of the product group."] def prod (U : open_subgroup G) (V : open_subgroup H) : open_subgroup (G × H) := { is_open' := U.is_open.prod V.is_open, .. (U : subgroup G).prod (V : subgroup H) } @[simp, norm_cast, to_additive] lemma coe_prod (U : open_subgroup G) (V : open_subgroup H) : (U.prod V : set (G × H)) = U ×ˢ V := rfl @[simp, norm_cast, to_additive] lemma coe_subgroup_prod (U : open_subgroup G) (V : open_subgroup H) : (U.prod V : subgroup (G × H)) = (U : subgroup G).prod V := rfl end @[to_additive] instance : has_inf (open_subgroup G) := ⟨λ U V, ⟨U ⊓ V, U.is_open.inter V.is_open⟩⟩ @[simp, norm_cast, to_additive] lemma coe_inf : (↑(U ⊓ V) : set G) = (U : set G) ∩ V := rfl @[simp, norm_cast, to_additive] lemma coe_subgroup_inf : (↑(U ⊓ V) : subgroup G) = ↑U ⊓ ↑V := rfl @[simp, norm_cast, to_additive] lemma coe_opens_inf : (↑(U ⊓ V) : opens G) = ↑U ⊓ ↑V := rfl @[simp, to_additive] lemma mem_inf {x} : x ∈ U ⊓ V ↔ x ∈ U ∧ x ∈ V := iff.rfl @[to_additive] instance : semilattice_inf (open_subgroup G) := { .. set_like.partial_order, .. set_like.coe_injective.semilattice_inf (coe : open_subgroup G → set G) (λ _ _, rfl) } @[to_additive] instance : order_top (open_subgroup G) := { top := ⊤, le_top := λ U, set.subset_univ _ } @[simp, norm_cast, to_additive] lemma coe_subgroup_le : (U : subgroup G) ≤ (V : subgroup G) ↔ U ≤ V := iff.rfl variables {N : Type*} [group N] [topological_space N] /-- The preimage of an `open_subgroup` along a continuous `monoid` homomorphism is an `open_subgroup`. -/ @[to_additive "The preimage of an `open_add_subgroup` along a continuous `add_monoid` homomorphism is an `open_add_subgroup`."] def comap (f : G →* N) (hf : continuous f) (H : open_subgroup N) : open_subgroup G := { is_open' := H.is_open.preimage hf, .. (H : subgroup N).comap f } @[simp, norm_cast, to_additive] lemma coe_comap (H : open_subgroup N) (f : G →* N) (hf : continuous f) : (H.comap f hf : set G) = f ⁻¹' H := rfl @[simp, norm_cast, to_additive] lemma coe_subgroup_comap (H : open_subgroup N) (f : G →* N) (hf : continuous f) : (H.comap f hf : subgroup G) = (H : subgroup N).comap f := rfl @[simp, to_additive] lemma mem_comap {H : open_subgroup N} {f : G →* N} {hf : continuous f} {x : G} : x ∈ H.comap f hf ↔ f x ∈ H := iff.rfl @[to_additive] lemma comap_comap {P : Type*} [group P] [topological_space P] (K : open_subgroup P) (f₂ : N →* P) (hf₂ : continuous f₂) (f₁ : G →* N) (hf₁ : continuous f₁) : (K.comap f₂ hf₂).comap f₁ hf₁ = K.comap (f₂.comp f₁) (hf₂.comp hf₁) := rfl end open_subgroup namespace subgroup variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G] (H : subgroup G) @[to_additive] lemma is_open_of_mem_nhds {g : G} (hg : (H : set G) ∈ 𝓝 g) : is_open (H : set G) := begin refine is_open_iff_mem_nhds.2 (λ x hx, _), have hg' : g ∈ H := set_like.mem_coe.1 (mem_of_mem_nhds hg), have : filter.tendsto (λ y, y * (x⁻¹ * g)) (𝓝 x) (𝓝 g) := (continuous_id.mul continuous_const).tendsto' _ _ (mul_inv_cancel_left _ _), simpa only [set_like.mem_coe, filter.mem_map', H.mul_mem_cancel_right (H.mul_mem (H.inv_mem hx) hg')] using this hg, end @[to_additive] lemma is_open_mono {H₁ H₂ : subgroup G} (h : H₁ ≤ H₂) (h₁ : is_open (H₁ : set G)) : is_open (H₂ : set G) := is_open_of_mem_nhds _ $ filter.mem_of_superset (h₁.mem_nhds $ one_mem H₁) h @[to_additive] lemma is_open_of_open_subgroup {U : open_subgroup G} (h : ↑U ≤ H) : is_open (H : set G) := is_open_mono h U.is_open /-- If a subgroup of a topological group has `1` in its interior, then it is open. -/ @[to_additive "If a subgroup of an additive topological group has `0` in its interior, then it is open."] lemma is_open_of_one_mem_interior (h_1_int : (1 : G) ∈ interior (H : set G)) : is_open (H : set G) := is_open_of_mem_nhds H $ mem_interior_iff_mem_nhds.1 h_1_int end subgroup namespace open_subgroup variables {G : Type*} [group G] [topological_space G] [has_continuous_mul G] @[to_additive] instance : has_sup (open_subgroup G) := ⟨λ U V, ⟨U ⊔ V, subgroup.is_open_mono (le_sup_left : U.1 ≤ U ⊔ V) U.is_open⟩⟩ @[simp, norm_cast, to_additive] lemma coe_subgroup_sup (U V : open_subgroup G) : (↑(U ⊔ V) : subgroup G) = ↑U ⊔ ↑V := rfl @[to_additive] instance : lattice (open_subgroup G) := { .. open_subgroup.semilattice_inf, .. coe_subgroup_injective.semilattice_sup (coe : open_subgroup G → subgroup G) (λ _ _, rfl) } end open_subgroup namespace submodule open open_add_subgroup variables {R : Type*} {M : Type*} [comm_ring R] variables [add_comm_group M] [topological_space M] [topological_add_group M] [module R M] lemma is_open_mono {U P : submodule R M} (h : U ≤ P) (hU : is_open (U : set M)) : is_open (P : set M) := @add_subgroup.is_open_mono M _ _ _ U.to_add_subgroup P.to_add_subgroup h hU end submodule namespace ideal variables {R : Type*} [comm_ring R] variables [topological_space R] [topological_ring R] lemma is_open_of_open_subideal {U I : ideal R} (h : U ≤ I) (hU : is_open (U : set R)) : is_open (I : set R) := submodule.is_open_mono h hU end ideal
c858dd74fd4c54aa94169a88c566d4c9bf0f68e8
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Tactic/Basic.lean
6326e06c85a8bd8754b0d4b1d8eeb78f8ec7da57
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
15,671
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.Elab.Term namespace Lean.Elab open Meta /-- Assign `mvarId := sorry` -/ def admitGoal (mvarId : MVarId) : MetaM Unit := mvarId.withContext do let mvarType ← inferType (mkMVar mvarId) mvarId.assign (← mkSorry mvarType (synthetic := true)) def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map MessageData.ofGoal) m!"\n\n" def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := do logError <| MessageData.tagged `Tactic.unsolvedGoals <| m!"unsolved goals\n{goalsToMessageData goals}" goals.forM fun mvarId => admitGoal mvarId namespace Tactic structure Context where /-- Declaration name of the executing elaborator, used by `mkTacticInfo` to persist it in the info tree -/ elaborator : Name /-- If `true`, enable "error recovery" in some tactics. For example, `cases` tactic admits unsolved alternatives when `recover == true`. The combinator `withoutRecover <tac>` disables "error recovery" while executing `<tac>`. This is useful for tactics such as `first | ... | ...`. -/ recover : Bool := true structure SavedState where term : Term.SavedState tactic : State abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit /- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the whole monad stack at every use site. May eventually be covered by `deriving`. See comment at `Monad TermElabM` -/ @[always_inline] instance : Monad TacticM := let i := inferInstanceAs (Monad TacticM); { pure := i.pure, bind := i.bind } def getGoals : TacticM (List MVarId) := return (← get).goals def setGoals (mvarIds : List MVarId) : TacticM Unit := modify fun _ => { goals := mvarIds } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> g.isAssigned setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals getGoals @[inline] private def TacticM.runCore (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] private def TacticM.runCore' (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.runCore ctx s def run (mvarId : MVarId) (x : TacticM Unit) : TermElabM (List MVarId) := mvarId.withContext do let pendingMVarsSaved := (← get).pendingMVars modify fun s => { s with pendingMVars := [] } let aux : TacticM (List MVarId) := /- Important: the following `try` does not backtrack the state. This is intentional because we don't want to backtrack the error messages when we catch the "abort internal exception" We must define `run` here because we define `MonadExcept` instance for `TacticM` -/ try x; getUnsolvedGoals catch ex => if isAbortTacticException ex then getUnsolvedGoals else throw ex try aux.runCore' { elaborator := .anonymous } { goals := [mvarId] } finally modify fun s => { s with pendingMVars := pendingMVarsSaved } protected def saveState : TacticM SavedState := return { term := (← Term.saveState), tactic := (← get) } def SavedState.restore (b : SavedState) (restoreInfo := false) : TacticM Unit := do b.term.restore restoreInfo set b.tactic protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Core.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `builtin_tactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" `Lean.Elab.Tactic.tacticElabAttribute @[builtin_init mkTacticAttribute] opaque tacticElabAttribute : KeyedDeclsAttribute Tactic def mkTacticInfo (mctxBefore : MetavarContext) (goalsBefore : List MVarId) (stx : Syntax) : TacticM Info := return Info.ofTacticInfo { elaborator := (← read).elaborator mctxBefore := mctxBefore goalsBefore := goalsBefore stx := stx mctxAfter := (← getMCtx) goalsAfter := (← getUnsolvedGoals) } def mkInitialTacticInfo (stx : Syntax) : TacticM (TacticM Info) := do let mctxBefore ← getMCtx let goalsBefore ← getUnsolvedGoals return mkTacticInfo mctxBefore goalsBefore stx @[inline] def withTacticInfoContext (stx : Syntax) (x : TacticM α) : TacticM α := do withInfoContext x (← mkInitialTacticInfo stx) /-! Important: we must define `evalTactic` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages, and this is bad when rethrowing the exception at the `catch` block in these methods. We marked these places with a `(*)` in these methods. -/ /-- Auxiliary datastructure for capturing exceptions at `evalTactic`. -/ structure EvalTacticFailure where exception : Exception state : SavedState partial def evalTactic (stx : Syntax) : TacticM Unit := withRef stx <| withIncRecDepth <| withFreshMacroScope <| match stx with | .node _ k _ => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace[Elab.step] "{stx}" let evalFns := tacticElabAttribute.getEntries (← getEnv) stx.getKind let macros := macroAttribute.getEntries (← getEnv) stx.getKind if evalFns.isEmpty && macros.isEmpty then throwErrorAt stx "tactic '{stx.getKind}' has not been implemented" let s ← Tactic.saveState expandEval s macros evalFns #[] | .missing => pure () | _ => throwError m!"unexpected tactic{indentD stx}" where throwExs (failures : Array EvalTacticFailure) : TacticM Unit := do if let some fail := failures[0]? then -- Recall that `failures[0]` is the highest priority evalFn/macro fail.state.restore (restoreInfo := true) throw fail.exception -- (*) else throwErrorAt stx "unexpected syntax {indentD stx}" @[inline] handleEx (s : SavedState) (failures : Array EvalTacticFailure) (ex : Exception) (k : Array EvalTacticFailure → TacticM Unit) := do match ex with | .error .. => trace[Elab.tactic.backtrack] ex.toMessageData let failures := failures.push ⟨ex, ← Tactic.saveState⟩ s.restore (restoreInfo := true); k failures | .internal id _ => if id == unsupportedSyntaxExceptionId then -- We do not store `unsupportedSyntaxExceptionId`, see throwExs s.restore (restoreInfo := true); k failures else if id == abortTacticExceptionId then for msg in (← Core.getMessageLog).toList do trace[Elab.tactic.backtrack] msg.data let failures := failures.push ⟨ex, ← Tactic.saveState⟩ s.restore (restoreInfo := true); k failures else throw ex -- (*) expandEval (s : SavedState) (macros : List _) (evalFns : List _) (failures : Array EvalTacticFailure) : TacticM Unit := match macros with | [] => eval s evalFns failures | m :: ms => try withReader ({ · with elaborator := m.declName }) do withTacticInfoContext stx do let stx' ← adaptMacro m.value stx evalTactic stx' catch ex => handleEx s failures ex (expandEval s ms evalFns) eval (s : SavedState) (evalFns : List _) (failures : Array EvalTacticFailure) : TacticM Unit := do match evalFns with | [] => throwExs failures | evalFn::evalFns => do try withReader ({ · with elaborator := evalFn.declName }) <| withTacticInfoContext stx <| evalFn.value stx catch ex => handleEx s failures ex (eval s evalFns) def throwNoGoalsToBeSolved : TacticM α := throwError "no goals to be solved" def done : TacticM Unit := do let gs ← getUnsolvedGoals unless gs.isEmpty do Term.reportUnsolvedGoals gs throwAbortTactic def focus (x : TacticM α) : TacticM α := do let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved setGoals [mvarId] let a ← x let mvarIds' ← getUnsolvedGoals setGoals (mvarIds' ++ mvarIds) pure a def focusAndDone (tactic : TacticM α) : TacticM α := focus do let a ← tactic done pure a /-- Close the main goal using the given tactic. If it fails, log the error and `admit` -/ def closeUsingOrAdmit (tac : TacticM Unit) : TacticM Unit := do /- Important: we must define `closeUsingOrAdmit` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages. -/ let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved try focusAndDone tac catch ex => if (← read).recover then logException ex admitGoal mvarId setGoals mvarIds else throw ex instance : MonadBacktrack SavedState TacticM where saveState := Tactic.saveState restoreState b := b.restore @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM where throw := throw tryCatch := Tactic.tryCatch /-- Execute `x` with error recovery disabled -/ def withoutRecover (x : TacticM α) : TacticM α := withReader (fun ctx => { ctx with recover := false }) x @[inline] protected def orElse (x : TacticM α) (y : Unit → TacticM α) : TacticM α := do try withoutRecover x catch _ => y () instance : OrElse (TacticM α) where orElse := Tactic.orElse instance : Alternative TacticM where failure := fun {_} => throwError "failed" orElse := Tactic.orElse /-- Save the current tactic state for a token `stx`. This method is a no-op if `stx` has no position information. We use this method to save the tactic state at punctuation such as `;` -/ def saveTacticInfoForToken (stx : Syntax) : TacticM Unit := do unless stx.getPos?.isNone do withTacticInfoContext stx (pure ()) /-- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withMacroExpansionInfo beforeStx afterStx do withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ evalTactic stx' /-- Add the given goals at the end of the current goals collection. -/ def appendGoals (mvarIds : List MVarId) : TacticM Unit := modify fun s => { s with goals := s.goals ++ mvarIds } /-- Discard the first goal and replace it by the given list of goals, keeping the other goals. -/ def replaceMainGoal (mvarIds : List MVarId) : TacticM Unit := do let (_ :: mvarIds') ← getGoals | throwNoGoalsToBeSolved modify fun _ => { goals := mvarIds ++ mvarIds' } /-- Return the first goal. -/ def getMainGoal : TacticM MVarId := do loop (← getGoals) where loop : List MVarId → TacticM MVarId | [] => throwNoGoalsToBeSolved | mvarId :: mvarIds => do if (← mvarId.isAssigned) then loop mvarIds else setGoals (mvarId :: mvarIds) return mvarId /-- Return the main goal metavariable declaration. -/ def getMainDecl : TacticM MetavarDecl := do (← getMainGoal).getDecl /-- Return the main goal tag. -/ def getMainTag : TacticM Name := return (← getMainDecl).userName /-- Return expected type for the main goal. -/ def getMainTarget : TacticM Expr := do instantiateMVars (← getMainDecl).type /-- Execute `x` using the main goal local context and instances -/ def withMainContext (x : TacticM α) : TacticM α := do (← getMainGoal).withContext x /-- Evaluate `tac` at `mvarId`, and return the list of resulting subgoals. -/ def evalTacticAt (tac : Syntax) (mvarId : MVarId) : TacticM (List MVarId) := do let gs ← getGoals try setGoals [mvarId] evalTactic tac pruneSolvedGoals getGoals finally setGoals gs def ensureHasNoMVars (e : Expr) : TacticM Unit := do let e ← instantiateMVars e let pendingMVars ← getMVars e discard <| Term.logUnassignedUsingErrorInfos pendingMVars if e.hasExprMVar then throwError "tactic failed, resulting expression contains metavariables{indentExpr e}" /-- Close main goal using the given expression. If `checkUnassigned == true`, then `val` must not contain unassigned metavariables. -/ def closeMainGoal (val : Expr) (checkUnassigned := true): TacticM Unit := do if checkUnassigned then ensureHasNoMVars val (← getMainGoal).assign val replaceMainGoal [] @[inline] def liftMetaMAtMain (x : MVarId → MetaM α) : TacticM α := do withMainContext do x (← getMainGoal) @[inline] def liftMetaTacticAux (tac : MVarId → MetaM (α × List MVarId)) : TacticM α := do withMainContext do let (a, mvarIds) ← tac (← getMainGoal) replaceMainGoal mvarIds pure a /-- Get the mvarid of the main goal, run the given `tactic`, then set the new goals to be the resulting goal list.-/ @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) @[inline] def liftMetaTactic1 (tactic : MVarId → MetaM (Option MVarId)) : TacticM Unit := withMainContext do if let some mvarId ← tactic (← getMainGoal) then replaceMainGoal [mvarId] else replaceMainGoal [] def tryTactic? (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none def tryTactic (tactic : TacticM α) : TacticM Bool := do try discard tactic pure true catch _ => pure false /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do let mctx ← getMCtx let mut numAnonymous := 0 for g in newGoals do if mctx.isAnonymousMVar g then numAnonymous := numAnonymous + 1 modifyMCtx fun mctx => Id.run do let mut mctx := mctx let mut idx := 1 for g in newGoals do if mctx.isAnonymousMVar g then if numAnonymous == 1 then mctx := mctx.setMVarUserName g parentTag else mctx := mctx.setMVarUserName g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx /- Recall that `ident' := ident <|> Term.hole` -/ def getNameOfIdent' (id : Syntax) : Name := if id.isIdent then id.getId else `_ /-- Use position of `=> $body` for error messages. If there is a line break before `body`, the message will be displayed on `=>` only, but the "full range" for the info view will still include `body`. -/ def withCaseRef [Monad m] [MonadRef m] (arrow body : Syntax) (x : m α) : m α := withRef (mkNullNode #[arrow, body]) x builtin_initialize registerTraceClass `Elab.tactic builtin_initialize registerTraceClass `Elab.tactic.backtrack end Lean.Elab.Tactic
d4a5897a6ee714024b317f796e9c4a0f56878220
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/inner_product_space/pi_L2.lean
686beebf251c0b9241a45e2e2b4dff37344fa36c
[ "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
8,712
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth -/ import analysis.inner_product_space.projection import analysis.normed_space.pi_Lp /-! # `L²` inner product space structure on finite products of inner product spaces The `L²` norm on a finite product of inner product spaces is compatible with an inner product $$ \langle x, y\rangle = \sum \langle x_i, y_i \rangle. $$ This is recorded in this file as an inner product space instance on `pi_Lp 2`. ## Main definitions - `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 _ (n → 𝕜)` for any `fintype n`, i.e., the space from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably that it is a finite-dimensional inner product space). - `basis.isometry_euclidean_of_orthonormal`: provides the isometry to Euclidean space from a given finite-dimensional inner product space, induced by a basis of the space. - `linear_isometry_equiv.of_inner_product_space`: provides an arbitrary isometry to Euclidean space from a given finite-dimensional inner product space, induced by choosing an arbitrary basis. - `complex.isometry_euclidean`: standard isometry from `ℂ` to `euclidean_space ℝ (fin 2)` -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal complex_conjugate noncomputable theory variables {ι : Type*} variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /- 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 ring_equiv.map_sum, apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, 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] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 one_le_two f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 one_le_two f) : ∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) := by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] } /-- 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), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x section local attribute [reducible] pi_Lp variables [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma finrank_euclidean_space : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma finrank_euclidean_space_fin {n : ℕ} : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp /-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry from `E` to `pi_Lp 2` of the subspaces equipped with the `L2` inner product. -/ def direct_sum.submodule_is_internal.isometry_L2_of_orthogonal_family [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.submodule_is_internal V) (hV' : orthogonal_family 𝕜 V) : E ≃ₗᵢ[𝕜] pi_Lp 2 one_le_two (λ i, V i) := begin let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i), let e₂ := linear_equiv.of_bijective _ hV.injective hV.surjective, refine (e₂.symm.trans e₁).isometry_of_inner _, suffices : ∀ v w, ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫, { intros v₀ w₀, convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀)); simp only [linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] }, intros v w, transitivity ⟪(∑ i, (v i : E)), ∑ i, (w i : E)⟫, { simp [sum_inner, hV'.inner_right_fintype] }, { congr; simp } end /-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with `euclidean_space 𝕜 ι`. -/ def basis.isometry_euclidean_of_orthonormal (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι := v.equiv_fun.isometry_of_inner begin intros x y, let p : euclidean_space 𝕜 ι := v.equiv_fun x, let q : euclidean_space 𝕜 ι := v.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] }, { rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] } end end /-- `ℂ` is isometric to `ℝ²` with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := complex.basis_one_I.isometry_euclidean_of_orthonormal begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } open finite_dimensional /-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := (fin_orthonormal_basis hn).isometry_euclidean_of_orthonormal (fin_orthonormal_basis_orthonormal hn) local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv)
282ca5b12556088a618181d702c134e175651414
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/pnat/xgcd.lean
b5cbdc571bda226e0a6e8f2ed67de56742fe9fa7
[ "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
13,392
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland This file sets up a version of the Euclidean algorithm that works only with natural numbers. Given a, b > 0, it computes the unique system (w, x, y, z, d) such that the following identities hold: w * z = x * y + 1 a = (w + x) d b = (y + z) d These equations force w, z, d > 0. They also imply that the integers a' = w + x = a / d and b' = y + z = b / d are coprime, and that d is the gcd of a and b. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. -/ import tactic.ring import tactic.abel import data.pnat.prime namespace pnat open nat pnat /-- A term of xgcd_type is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ @[derive inhabited] structure xgcd_type := (wp x y zp ap bp : ℕ) namespace xgcd_type variable (u : xgcd_type) instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩ /-- The has_repr instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : has_repr xgcd_type := ⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++ "], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++ (repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type := mk w.val.pred x y z.val.pred a.val.pred b.val.pred def w : ℕ+ := succ_pnat u.wp def z : ℕ+ := succ_pnat u.zp def a : ℕ+ := succ_pnat u.ap def b : ℕ+ := succ_pnat u.bp def r : ℕ := (u.ap + 1) % (u.bp + 1) def q : ℕ := (u.ap + 1) / (u.bp + 1) def qp : ℕ := u.q - 1 /-- The map v gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map vp gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by { ext; dsimp [v, vp, w, z, a, b, succ₂]; repeat { rw [nat.succ_eq_add_one] }; ring } /-- is_special holds if the matrix has determinant one. -/ def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y) theorem is_special_iff : u.is_special ↔ u.is_special' := begin dsimp [is_special, is_special'], split; intro h, { apply eq, dsimp [w, z, succ_pnat], rw [← h], repeat { rw [nat.succ_eq_add_one] }, ring }, { apply nat.succ.inj, replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [mul_coe, w, z] at h, repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h }, repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring } end /-- is_reduced holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def is_reduced : Prop := u.ap = u.bp def is_reduced' : Prop := u.a = u.b theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' := ⟨ congr_arg succ_pnat, succ_pnat_inj ⟩ def flip : xgcd_type := { wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap } @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced := by { dsimp [is_reduced, flip], split; intro h; exact h.symm } theorem flip_is_special : (flip u).is_special ↔ u.is_special := by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] } theorem flip_v : (flip u).v = (u.v).swap := by { dsimp [v], ext, { simp only, ring }, { simp only, ring } } /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := begin by_cases hq : u.q = 0, { let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h }, { exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm } end /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying is_reduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_is_special (a b : ℕ+) : (start a b).is_special := by { dsimp [start, is_special], refl } theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := begin dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z], rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero], rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one], rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos] end def finish : xgcd_type := xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_is_reduced : u.finish.is_reduced := by { dsimp [is_reduced], refl } theorem finish_is_special (hs : u.is_special) : u.finish.is_special := begin dsimp [is_special, finish] at hs ⊢, rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs], ring end theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, rw [hr, zero_add] at ha, ext, { change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b, have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring }, { change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b, rw [← ha, u.qp_eq hr], ring } end /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : xgcd_type := xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u := begin change u.r - 1 < u.bp, have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr), have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos, rw[← h₀] at h₁, exact lt_of_succ_lt_succ h₁, end theorem step_is_special (hs : u.is_special) : u.step.is_special := begin dsimp [is_special, step] at hs ⊢, rw [mul_add, mul_comm u.y u.x, ← hs], ring end /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, let hr : (u.r - 1) + 1 = u.r := (add_comm _ 1).trans (nat.add_sub_of_le (nat.pos_of_ne_zero hr)), ext, { change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b, rw [← ha, hr], ring }, { change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b, rw [← ha, hr], ring } end /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce : xgcd_type → xgcd_type | u := dite (u.r = 0) (λ h, u.finish) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, flip (reduce u.step)) theorem reduce_a {u : xgcd_type} (h : u.r = 0) : u.reduce = u.finish := by { rw [reduce], simp only, rw [if_pos h] } theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by { rw [reduce], simp only, rw [if_neg h, step] } theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced | u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced }) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced }) theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' := (is_reduced_iff _).mp u.reduce_reduced theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special | u := dite (u.r = 0) (λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs }) (λ h hs, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h], let u' := u.step.reduce, have : u'.is_special := reduce_special u.step (u.step_is_special hs), exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) }) theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' := (is_special_iff _).mp (u.reduce_special hs) theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v | u := dite (u.r = 0) (λ h, by {rw[reduce_a h, finish_v u h]}) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] }) end xgcd_type section gcd variables (a b : ℕ+) def xgcd: xgcd_type := (xgcd_type.start a b).reduce def gcd_d : ℕ+ := (xgcd a b).a def gcd_w : ℕ+ := (xgcd a b).w def gcd_x : ℕ := (xgcd a b).x def gcd_y : ℕ := (xgcd a b).y def gcd_z : ℕ+ := (xgcd a b).z def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x) def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp) theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) := by { dsimp [gcd_a', gcd_w, xgcd_type.w], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) := by { dsimp [gcd_b', gcd_z, xgcd_type.z], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_props : let d := gcd_d a b, w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b, a' := gcd_a' a b, b' := gcd_b' a b in (w * z = succ_pnat (x * y) ∧ (a = a' * d) ∧ (b = b' * d) ∧ z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d ) := begin intros, let u := (xgcd_type.start a b), let ur := u.reduce, have ha : d = ur.a := rfl, have hb : d = ur.b := u.reduce_reduced', have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b, have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b, have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl, split, exact hdet, have hdet' : ((w * z) : ℕ) = x * y + 1 := by { rw [← mul_coe, hdet, succ_pnat_coe] }, have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b), let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (xgcd_type.start_v a b), rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv, have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm, have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm, split, exact eq ha'', split, exact eq hb'', have hza' : (z * a' : ℕ) = x * b' + 1, by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring }, have hwb' : (w * b' : ℕ) = y * a' + 1, by { rw [ha', hb', mul_add, mul_add, hdet'], ring }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] }, rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'], split; ring, end theorem gcd_eq : gcd_d a b = gcd a b := begin rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩, apply dvd_antisymm, { apply dvd_gcd, exact dvd.intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm, exact dvd.intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm}, { have h₇ : (gcd a b : ℕ) ∣ (gcd_z a b) * a := dvd_trans (nat.gcd_dvd_left a b) (dvd_mul_left _ _), have h₈ : (gcd a b : ℕ) ∣ (gcd_x a b) * b := dvd_trans (nat.gcd_dvd_right a b) (dvd_mul_left _ _), rw[h₅] at h₇, rw dvd_iff, exact (nat.dvd_add_iff_right h₈).mpr h₇,} end theorem gcd_det_eq : (gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) := (gcd_props a b).1 theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : (gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : (gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : ((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : ((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end pnat
154075e88cc18f755b1283618044f4dba61c1036
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/conj.lean
6081164c66ed322051a4eaa8019a5749d700bd17
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,465
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import category_theory.endomorphism import algebra.group_power /-! # Conjugate morphisms by isomorphisms An isomorphism `α : X ≅ Y` defines - a monoid isomorphism `conj : End X ≃* End Y` by `α.conj f = α.inv ≫ f ≫ α.hom`; - a group isomorphism `conj_Aut : Aut X ≃* Aut Y` by `α.conj_Aut f = α.symm ≪≫ f ≪≫ α`. For completeness, we also define `hom_congr : (X ≅ X₁) → (Y ≅ Y₁) → (X ⟶ Y) ≃ (X₁ ⟶ Y₁)`, cf. `equiv.arrow_congr`. -/ universes v u namespace category_theory namespace iso variables {C : Type u} [category.{v} C] /-- If `X` is isomorphic to `X₁` and `Y` is isomorphic to `Y₁`, then there is a natural bijection between `X ⟶ Y` and `X₁ ⟶ Y₁`. See also `equiv.arrow_congr`. -/ def hom_congr {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) : (X ⟶ Y) ≃ (X₁ ⟶ Y₁) := { to_fun := λ f, α.inv ≫ f ≫ β.hom, inv_fun := λ f, α.hom ≫ f ≫ β.inv, left_inv := λ f, show α.hom ≫ (α.inv ≫ f ≫ β.hom) ≫ β.inv = f, by rw [category.assoc, category.assoc, β.hom_inv_id, α.hom_inv_id_assoc, category.comp_id], right_inv := λ f, show α.inv ≫ (α.hom ≫ f ≫ β.inv) ≫ β.hom = f, by rw [category.assoc, category.assoc, β.inv_hom_id, α.inv_hom_id_assoc, category.comp_id] } @[simp] lemma hom_congr_apply {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) : α.hom_congr β f = α.inv ≫ f ≫ β.hom := rfl lemma hom_congr_comp {X Y Z X₁ Y₁ Z₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁) (f : X ⟶ Y) (g : Y ⟶ Z) : α.hom_congr γ (f ≫ g) = α.hom_congr β f ≫ β.hom_congr γ g := by simp @[simp] lemma hom_congr_refl {X Y : C} (f : X ⟶ Y) : (iso.refl X).hom_congr (iso.refl Y) f = f := by simp @[simp] lemma hom_congr_trans {X₁ Y₁ X₂ Y₂ X₃ Y₃ : C} (α₁ : X₁ ≅ X₂) (β₁ : Y₁ ≅ Y₂) (α₂ : X₂ ≅ X₃) (β₂ : Y₂ ≅ Y₃) (f : X₁ ⟶ Y₁) : (α₁ ≪≫ α₂).hom_congr (β₁ ≪≫ β₂) f = (α₁.hom_congr β₁).trans (α₂.hom_congr β₂) f := by simp @[simp] lemma hom_congr_symm {X₁ Y₁ X₂ Y₂ : C} (α : X₁ ≅ X₂) (β : Y₁ ≅ Y₂) : (α.hom_congr β).symm = α.symm.hom_congr β.symm := rfl variables {X Y : C} (α : X ≅ Y) /-- An isomorphism between two objects defines a monoid isomorphism between their monoid of endomorphisms. -/ def conj : End X ≃* End Y := { map_mul' := λ f g, hom_congr_comp α α α g f, .. hom_congr α α } lemma conj_apply (f : End X) : α.conj f = α.inv ≫ f ≫ α.hom := rfl @[simp] lemma conj_comp (f g : End X) : α.conj (f ≫ g) = (α.conj f) ≫ (α.conj g) := α.conj.map_mul g f @[simp] lemma conj_id : α.conj (𝟙 X) = 𝟙 Y := α.conj.map_one @[simp] lemma refl_conj (f : End X) : (iso.refl X).conj f = f := by rw [conj_apply, iso.refl_inv, iso.refl_hom, category.id_comp, category.comp_id] @[simp] lemma trans_conj {Z : C} (β : Y ≅ Z) (f : End X) : (α ≪≫ β).conj f = β.conj (α.conj f) := hom_congr_trans α α β β f @[simp] lemma symm_self_conj (f : End X) : α.symm.conj (α.conj f) = f := by rw [← trans_conj, α.self_symm_id, refl_conj] @[simp] lemma self_symm_conj (f : End Y) : α.conj (α.symm.conj f) = f := α.symm.symm_self_conj f @[simp] lemma conj_pow (f : End X) (n : ℕ) : α.conj (f^n) = (α.conj f)^n := α.conj.to_monoid_hom.map_pow f n /-- `conj` defines a group isomorphisms between groups of automorphisms -/ def conj_Aut : Aut X ≃* Aut Y := (Aut.units_End_equiv_Aut X).symm.trans $ (units.map_equiv α.conj).trans $ Aut.units_End_equiv_Aut Y lemma conj_Aut_apply (f : Aut X) : α.conj_Aut f = α.symm ≪≫ f ≪≫ α := by cases f; cases α; ext; refl @[simp] lemma conj_Aut_hom (f : Aut X) : (α.conj_Aut f).hom = α.conj f.hom := rfl @[simp] lemma trans_conj_Aut {Z : C} (β : Y ≅ Z) (f : Aut X) : (α ≪≫ β).conj_Aut f = β.conj_Aut (α.conj_Aut f) := by simp only [conj_Aut_apply, iso.trans_symm, iso.trans_assoc] @[simp] lemma conj_Aut_mul (f g : Aut X) : α.conj_Aut (f * g) = α.conj_Aut f * α.conj_Aut g := α.conj_Aut.map_mul f g @[simp] lemma conj_Aut_trans (f g : Aut X) : α.conj_Aut (f ≪≫ g) = α.conj_Aut f ≪≫ α.conj_Aut g := conj_Aut_mul α g f @[simp] lemma conj_Aut_pow (f : Aut X) (n : ℕ) : α.conj_Aut (f^n) = (α.conj_Aut f)^n := α.conj_Aut.to_monoid_hom.map_pow f n @[simp] lemma conj_Aut_gpow (f : Aut X) (n : ℤ) : α.conj_Aut (f^n) = (α.conj_Aut f)^n := α.conj_Aut.to_monoid_hom.map_gpow f n end iso namespace functor universes v₁ u₁ variables {C : Type u} [category.{v} C] {D : Type u₁} [category.{v₁} D] (F : C ⥤ D) lemma map_hom_congr {X Y X₁ Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) : F.map (iso.hom_congr α β f) = iso.hom_congr (F.map_iso α) (F.map_iso β) (F.map f) := by simp lemma map_conj {X Y : C} (α : X ≅ Y) (f : End X) : F.map (α.conj f) = (F.map_iso α).conj (F.map f) := map_hom_congr F α α f lemma map_conj_Aut (F : C ⥤ D) {X Y : C} (α : X ≅ Y) (f : Aut X) : F.map_iso (α.conj_Aut f) = (F.map_iso α).conj_Aut (F.map_iso f) := by ext; simp only [map_iso_hom, iso.conj_Aut_hom, F.map_conj] -- alternative proof: by simp only [iso.conj_Aut_apply, F.map_iso_trans, F.map_iso_symm] end functor end category_theory
cc892879493dac00a2e6cdd69284f22476f9d2fc
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/algebra/ordered_ring.lean
ff4f13eae3280e826a9251ca2efff704f810f767
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
28,123
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq eq.ops variable {A : Type} private definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ structure ordered_semiring [class] (A : Type) extends semiring A, ordered_cancel_comm_monoid A := (mul_le_mul_of_nonneg_left: ∀a b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: ∀a b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: ∀a b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: ∀a b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_lt_mul' (a b c d : A) (H1 : a < c) (H2 : b < d) (H3 : b ≥ 0) (H4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt H1) H3 ... < c * d : mul_lt_mul_of_pos_left H2 H4 theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_ordered_cancel_comm_monoid A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [trans_instance] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) definition linear_ordered_ring.to_linear_ordered_semiring [trans_instance] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @le_of_add_le_add_left A _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A _ ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, or.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [trans_instance] [reducible] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := or.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg 1 theorem pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, or.inl (and.intro Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, or.inr (and.intro Ha Hb))) theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc theorem zero_gt_neg_one : -1 < (0:A) := neg_zero ▸ (neg_lt_neg zero_lt_one) theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, note Hposa := lt_of_le_of_lt Hb Hab, note H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A definition decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [trans_instance] [reducible] [s : decidable_linear_ordered_comm_ring A] : decidable_linear_ordered_semiring A := ⦃decidable_linear_ordered_semiring, s, @linear_ordered_ring.to_linear_ordered_semiring A _⦄ section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases !iff.refl !neg_dvd_iff_dvd theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := iff.mpr !abs_dvd_iff theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases !iff.refl !dvd_neg_iff_dvd theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := iff.mpr !dvd_abs_iff theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg theorem abs_mul_self (a : A) : abs (a * a) = a * a := by rewrite [abs_mul, abs_mul_abs_self] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (!abs_sub ▸ H) theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) else (have Habs : b - a < c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, sub_lt_left_of_lt_add Habs') theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (!abs_sub ▸ H) theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_eq_add_neg (a*b), sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, *sub_eq_add_neg], rewrite [{a*a + b*b}add.comm], rewrite [mul.comm b a, *add.assoc] end theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ namespace norm_num theorem pos_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : bit0 a > 0 := by rewrite ↑bit0; apply add_pos H H theorem nonneg_bit0_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit0 a ≥ 0 := by rewrite ↑bit0; apply add_nonneg H H theorem pos_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a > 0 := begin rewrite ↑bit1, apply add_pos_of_nonneg_of_pos, apply nonneg_bit0_helper _ H, apply zero_lt_one end theorem nonneg_bit1_helper [s : linear_ordered_semiring A] (a : A) (H : a ≥ 0) : bit1 a ≥ 0 := by apply le_of_lt; apply pos_bit1_helper _ H theorem nonzero_of_pos_helper [s : linear_ordered_semiring A] (a : A) (H : a > 0) : a ≠ 0 := ne_of_gt H theorem nonzero_of_neg_helper [s : linear_ordered_ring A] (a : A) (H : a ≠ 0) : -a ≠ 0 := begin intro Ha, apply H, apply eq_of_neg_eq_neg, rewrite neg_zero, exact Ha end end norm_num
46206c99d0f4536f1979de74f57950bfe1fe9f3f
0ec6b5eb2131429a4464b8e6c6f09897abba3de1
/src/group_cohomology.lean
f6fa13afebae6efe831ea036f2719db13b28ed99
[]
no_license
kckennylau/local-langlands-abelian
ba1b86e9d956778cd28ac900ffec02b0f0ba172a
ee22666898357dab800a0432214a22c519ed26a9
refs/heads/master
1,584,671,060,846
1,545,151,246,000
1,545,151,246,000
137,111,892
8
0
null
null
null
null
UTF-8
Lean
false
false
4,244
lean
import data.finsupp algebra.pi_instances import group_theory.coset import .topological_group noncomputable theory local attribute [instance] classical.prop_decidable universes u v w u₁ section group_cohomology variables (G : Type u) [group G] variables (M : Type v) [add_comm_group M] @[reducible] def group_ring := additive G →₀ ℤ instance group_ring.ring : ring (group_ring G) := finsupp.to_ring instance group_ring.coe : has_coe G (group_ring G) := ⟨λ g, finsupp.single g 1⟩ @[reducible] def group_module := module (group_ring G) M variables {G M} [group_module G M] class is_crossed_hom (f : G → M) : Prop := (mul : ∀ g h, f (g * h) = f g + g • f h) def is_crossed_hom.add (f g : G → M) [is_crossed_hom f] [is_crossed_hom g] : is_crossed_hom (f + g) := ⟨λ x y, show f (x * y) + g (x * y) = (f x + g x) + x • (f y + g y), by simp [is_crossed_hom.mul f, is_crossed_hom.mul g, smul_add]⟩ def is_crossed_hom.neg (f : G → M) [is_crossed_hom f] : is_crossed_hom (-f) := ⟨λ x y, show -f (x * y) = -f x + x • (-f y), by simp [is_crossed_hom.mul f]⟩ variables (G M) def crossed_hom := subtype (@is_crossed_hom G _ M _ _) instance crossed_hom.to_is_crossed_hom (f : crossed_hom G M) : is_crossed_hom f.1 := f.2 instance crossed_hom.add_comm_group : add_comm_group (crossed_hom G M) := { add := λ f g, ⟨f.1 + g.1, is_crossed_hom.add f.1 g.1⟩, add_assoc := λ f g h, subtype.eq $ add_assoc _ _ _, zero := ⟨λ x, 0, ⟨λ x y, by simp⟩⟩, zero_add := λ f, subtype.eq $ zero_add _, add_zero := λ f, subtype.eq $ add_zero _, neg := λ f, ⟨-f.1, is_crossed_hom.neg f.1⟩, add_left_neg := λ f, subtype.eq $ add_left_neg _, add_comm := λ f g, subtype.eq $ add_comm _ _ } def principal_crossed_hom : set (crossed_hom G M) := { f | ∃ m, ∀ x, f.1 x = x • m - m } instance principal_crossed_hom.normal_subgroup : normal_add_subgroup (principal_crossed_hom G M) := { add_mem := λ f g ⟨m, hm⟩ ⟨n, hn⟩, ⟨m + n, λ x, show f.1 x + g.1 x = _, by simp [hm, hn, smul_add]⟩, zero_mem := ⟨0, λ x, by simp; refl⟩, neg_mem := λ f ⟨m, hm⟩, ⟨-m, λ x, show -f.1 x = _, by simp [hm]⟩, normal := λ f hf g, show g + f - g ∈ _, by simp [hf] } def H1 : Type (max u v) := quotient_add_group.quotient (principal_crossed_hom G M) instance H1.add_comm_group : add_comm_group (H1 G M) := quotient_add_group.add_comm_group _ end group_cohomology variables (G : Type u) [topological_space G] [group G] [topological_group G] variables (M : Type v) [topological_space M] [add_comm_group M] [topological_add_group M] --set_option old_structure_cmd true class topological_group_module extends module (group_ring G) M := (continuous_smul : continuous (λ m : G × M, (m.1 : group_ring G) • m.2)) variable [topological_group_module G M] def H1c.set : set (H1 G M) := λ x, quotient.lift_on' x (λ f, continuous f.1) $ λ f g ⟨m, h⟩, have H : ∀ (x : G), -(f.1 x) + (g.1 x) = ↑x • m - m := h, have Hm : continuous (λ (x : G), ↑x • m), by change continuous ((λ m : G × M, (m.1 : group_ring G) • m.2) ∘ (λ x, (x, m))); letI := @prod.topological_space G M _ _; apply (continuous.prod_mk continuous_id continuous_const).comp (topological_group_module.continuous_smul G M), propext ⟨λ hf, have H1 : g.1 = λ x, f.1 x + (x • m - m), from funext $ λ x, by rw ← H; simp [-add_comm], by rw H1; apply continuous_add hf (continuous_sub Hm continuous_const), λ hg, have H1 : f.1 = λ x, g.1 x - (x • m - m), from funext $ λ x, by rw ← H; simp, by rw H1; apply continuous_sub hg (continuous_sub Hm continuous_const)⟩ instance H1c.is_add_subgroup : is_add_subgroup (H1c.set G M) := { add_mem := λ x y, quotient.induction_on₂' x y $ λ f g hf hg, continuous_add hf hg, zero_mem := continuous_const, neg_mem := λ x, quotient.induction_on' x $ λ f hf, continuous_neg hf } def H1c : Type (max u v) := H1c.set G M instance H1c.add_comm_group : add_comm_group (H1c G M) := { add_comm := λ f g, subtype.eq $ add_comm _ _, .. subtype.add_group }
155a5f95b0c6ab2f605277860ad13d9d2b090b6b
bb31430994044506fa42fd667e2d556327e18dfe
/src/order/filter/zero_and_bounded_at_filter.lean
49cdbe93dfba0b0fb625352ecce4529fd4e7e6aa
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
4,901
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import algebra.module.submodule.basic import topology.algebra.monoid import analysis.asymptotics.asymptotics /-! # Zero and Bounded at filter Given a filter `l` we define the notion of a function being `zero_at_filter` as well as being `bounded_at_filter`. Alongside this we construct the `submodule`, `add_submonoid` of functions that are `zero_at_filter`. Similarly, we construct the `submodule` and `subalgebra` of functions that are `bounded_at_filter`. -/ namespace filter variables {α β : Type*} open_locale topological_space /-- If `l` is a filter on `α`, then a function `f : α → β` is `zero_at_filter l` if it tends to zero along `l`. -/ def zero_at_filter [has_zero β] [topological_space β] (l : filter α) (f : α → β) : Prop := filter.tendsto f l (𝓝 0) lemma zero_zero_at_filter [has_zero β] [topological_space β] (l : filter α) : zero_at_filter l (0 : α → β) := tendsto_const_nhds lemma zero_at_filter.add [topological_space β] [add_zero_class β] [has_continuous_add β] {l : filter α} {f g : α → β} (hf : zero_at_filter l f) (hg : zero_at_filter l g) : zero_at_filter l (f + g) := by simpa using hf.add hg lemma zero_at_filter.neg [topological_space β] [add_group β] [has_continuous_neg β] {l : filter α} {f : α → β} (hf : zero_at_filter l f) : zero_at_filter l (-f) := by simpa using hf.neg lemma zero_at_filter.smul {𝕜 : Type*} [topological_space 𝕜] [topological_space β] [has_zero 𝕜] [has_zero β] [smul_with_zero 𝕜 β] [has_continuous_smul 𝕜 β] {l : filter α} {f : α → β} (c : 𝕜) (hf : zero_at_filter l f) : zero_at_filter l (c • f) := by simpa using hf.const_smul c /-- `zero_at_filter_submodule l` is the submodule of `f : α → β` which tend to zero along `l`. -/ def zero_at_filter_submodule [topological_space β] [semiring β] [has_continuous_add β] [has_continuous_mul β] (l : filter α) : submodule β (α → β) := { carrier := zero_at_filter l, zero_mem' := zero_zero_at_filter l, add_mem' := λ a b ha hb, ha.add hb, smul_mem' := λ c f hf, hf.smul c } /-- `zero_at_filter_add_submonoid l` is the additive submonoid of `f : α → β` which tend to zero along `l`. -/ def zero_at_filter_add_submonoid [topological_space β] [add_zero_class β] [has_continuous_add β] (l : filter α) : add_submonoid (α → β) := { carrier := zero_at_filter l, add_mem' := λ a b ha hb, ha.add hb, zero_mem' := zero_zero_at_filter l, } /-- If `l` is a filter on `α`, then a function `f: α → β` is `bounded_at_filter l` if `f =O[l] 1`. -/ def bounded_at_filter [has_norm β] (l : filter α) (f : α → β) : Prop := asymptotics.is_O l f (1 : α → ℝ) lemma zero_at_filter.bounded_at_filter [normed_add_comm_group β] {l : filter α} {f : α → β} (hf : zero_at_filter l f) : bounded_at_filter l f := begin rw [zero_at_filter, ← asymptotics.is_o_const_iff (one_ne_zero' ℝ)] at hf, exact hf.is_O, end lemma const_bounded_at_filter [normed_field β] (l : filter α) (c : β) : bounded_at_filter l (function.const α c : α → β) := asymptotics.is_O_const_const c one_ne_zero l lemma bounded_at_filter.add [normed_add_comm_group β] {l : filter α} {f g : α → β} (hf : bounded_at_filter l f) (hg : bounded_at_filter l g) : bounded_at_filter l (f + g) := by simpa using hf.add hg lemma bounded_at_filter.neg [normed_add_comm_group β] {l : filter α} {f : α → β} (hf : bounded_at_filter l f) : bounded_at_filter l (-f) := hf.neg_left lemma bounded_at_filter.smul {𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group β] [normed_space 𝕜 β] {l : filter α} {f : α → β} (c : 𝕜) (hf : bounded_at_filter l f) : bounded_at_filter l (c • f) := hf.const_smul_left c lemma bounded_at_filter.mul [normed_field β] {l : filter α} {f g : α → β} (hf : bounded_at_filter l f) (hg : bounded_at_filter l g) : bounded_at_filter l (f * g) := begin refine (hf.mul hg).trans _, convert asymptotics.is_O_refl _ l, ext x, simp, end /-- The submodule of functions that are bounded along a filter `l`. -/ def bounded_filter_submodule [normed_field β] (l : filter α) : submodule β (α → β) := { carrier := bounded_at_filter l, zero_mem' := const_bounded_at_filter l 0, add_mem' := λ f g hf hg, hf.add hg, smul_mem' := λ c f hf, hf.smul c } /-- The subalgebra of functions that are bounded along a filter `l`. -/ def bounded_filter_subalgebra [normed_field β] (l : filter α) : subalgebra β (α → β) := begin refine submodule.to_subalgebra (bounded_filter_submodule l) _ (λ f g hf hg, _), { exact const_bounded_at_filter l (1:β) }, { simpa only [pi.one_apply, mul_one, norm_mul] using hf.mul hg, }, end end filter
47e0c9e79dc8165c77cdbfbc237510a9f571fc34
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/run/492_lean3.lean
16ad5408723481af0edbe9ba6292fc38468750d2
[ "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
763
lean
class foo (α : Type) : Type := (f : α) def foo.f' {α : Type} [c : foo α] : α := foo.f #print foo.f -- def foo.f : {α : Type} → [self : foo α] → α #print foo.f' -- def foo.f' : {α : Type} → [c : foo α] → α variables {α : Type} [c : foo α] #check c.f -- ok #check c.f' -- ok structure bar : Prop := (f : ∀ {m : Nat}, m = 0) def bar.f' : bar → ∀ {m : Nat}, m = 0 := bar.f #print bar.f -- def bar.f : bar → ∀ {m : ℕ}, m = 0 #print bar.f' -- def bar.f' : bar → ∀ {m : ℕ}, m = 0 variables (h : bar) (m : Nat) #check (h.f : ∀ {m : Nat}, m = 0) -- ok #check (h.f : m = 0) -- ok #check h.f (m := m) -- ok #check h.f (m := 0) -- ok #check (h.f' : m = 0) -- ok theorem ex1 (n) : (h.f : n = 0) = h.f (m := n) := rfl
5b0242d3f2acecbf3f3a53713457b743ff875649
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/order/complete_well_founded.lean
bdfc97f592808371ecf7fbe9e1cc789a009178e2
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
4,685
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import order.well_founded import order.order_iso_nat import data.set.finite import tactic.tfae /-! # Well-foundedness for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define two especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `is_sup_closed_compact` * `is_Sup_finite_compact` ## Main results The main result is that the following three conditions are equivalent for a complete lattice: * `well_founded (>)` * `is_sup_closed_compact` * `is_Sup_finite_compact` This is demonstrated by means of the following three lemmas: * `well_founded.is_Sup_finite_compact` * `is_Sup_finite_compact.is_sup_closed_compact` * `is_sup_closed_compact.well_founded` ## Tags complete lattice, well-founded, compact -/ namespace complete_lattice variables (α : Type*) [complete_lattice α] /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b, a ∈ s → b ∈ s → a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x y ⟨m, hm⟩ ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply a.to_rel_hom.map_sup, }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ well_founded.is_sup_closed_compact end complete_lattice
aebc25ec327499fc540ab3f24e89cb4e83f6ad43
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/algebra/category/morphism.lean
1daedb290a7a170ebcde13994b28ad5fb9871dcf
[ "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
12,158
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 import .basic algebra.relation algebra.binary open eq eq.ops category namespace morphism variables {ob : Type} [C : category ob] include C variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a} inductive is_section [class] (f : a ⟶ b) : Type := mk : ∀{g}, g ∘ f = id → is_section f inductive is_retraction [class] (f : a ⟶ b) : Type := mk : ∀{g}, f ∘ g = id → is_retraction f inductive is_iso [class] (f : a ⟶ b) : Type := mk : ∀{g}, g ∘ f = id → f ∘ g = id → is_iso f definition retraction_of (f : a ⟶ b) [H : is_section f] : hom b a := is_section.rec (λg h, g) H definition section_of (f : a ⟶ b) [H : is_retraction f] : hom b a := is_retraction.rec (λg h, g) H definition inverse (f : a ⟶ b) [H : is_iso f] : hom b a := is_iso.rec (λg h1 h2, g) H postfix `⁻¹` := inverse theorem inverse_compose (f : a ⟶ b) [H : is_iso f] : f⁻¹ ∘ f = id := is_iso.rec (λg h1 h2, h1) H theorem compose_inverse (f : a ⟶ b) [H : is_iso f] : f ∘ f⁻¹ = id := is_iso.rec (λg h1 h2, h2) H theorem retraction_compose (f : a ⟶ b) [H : is_section f] : retraction_of f ∘ f = id := is_section.rec (λg h, h) H theorem compose_section (f : a ⟶ b) [H : is_retraction f] : f ∘ section_of f = id := is_retraction.rec (λg h, h) H theorem iso_imp_retraction [instance] (f : a ⟶ b) [H : is_iso f] : is_section f := is_section.mk !inverse_compose theorem iso_imp_section [instance] (f : a ⟶ b) [H : is_iso f] : is_retraction f := is_retraction.mk !compose_inverse theorem id_is_iso [instance] : is_iso (ID a) := is_iso.mk !id_compose !id_compose theorem inverse_is_iso [instance] (f : a ⟶ b) [H : is_iso f] : is_iso (f⁻¹) := is_iso.mk !compose_inverse !inverse_compose theorem left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a} (Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' := calc g = g ∘ id : symm !id_right ... = g ∘ f ∘ g' : {symm Hr} ... = (g ∘ f) ∘ g' : !assoc ... = id ∘ g' : {Hl} ... = g' : !id_left theorem retraction_eq_intro [H : is_section f] (H2 : f ∘ h = id) : retraction_of f = h := left_inverse_eq_right_inverse !retraction_compose H2 theorem section_eq_intro [H : is_retraction f] (H2 : h ∘ f = id) : section_of f = h := symm (left_inverse_eq_right_inverse H2 !compose_section) theorem inverse_eq_intro_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h := left_inverse_eq_right_inverse !inverse_compose H2 theorem inverse_eq_intro_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h := symm (left_inverse_eq_right_inverse H2 !compose_inverse) theorem section_eq_retraction (f : a ⟶ b) [Hl : is_section f] [Hr : is_retraction f] : retraction_of f = section_of f := retraction_eq_intro !compose_section theorem section_retraction_imp_iso (f : a ⟶ b) [Hl : is_section f] [Hr : is_retraction f] : is_iso f := is_iso.mk (subst (section_eq_retraction f) (retraction_compose f)) (compose_section f) theorem inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' := inverse_eq_intro_left !inverse_compose theorem inverse_involutive (f : a ⟶ b) [H : is_iso f] : (f⁻¹)⁻¹ = f := inverse_eq_intro_right !inverse_compose theorem retraction_of_id : retraction_of (ID a) = id := retraction_eq_intro !id_compose theorem section_of_id : section_of (ID a) = id := section_eq_intro !id_compose theorem iso_of_id : ID a⁻¹ = id := inverse_eq_intro_left !id_compose theorem composition_is_section [instance] [Hf : is_section f] [Hg : is_section g] : is_section (g ∘ f) := is_section.mk (calc (retraction_of f ∘ retraction_of g) ∘ g ∘ f = retraction_of f ∘ retraction_of g ∘ g ∘ f : symm (assoc _ _ (g ∘ f)) ... = retraction_of f ∘ (retraction_of g ∘ g) ∘ f : {assoc _ g f} ... = retraction_of f ∘ id ∘ f : {retraction_compose g} ... = retraction_of f ∘ f : {id_left f} ... = id : !retraction_compose) theorem composition_is_retraction [instance] (Hf : is_retraction f) (Hg : is_retraction g) : is_retraction (g ∘ f) := is_retraction.mk (calc (g ∘ f) ∘ section_of f ∘ section_of g = g ∘ f ∘ section_of f ∘ section_of g : symm !assoc ... = g ∘ (f ∘ section_of f) ∘ section_of g : {assoc f _ _} ... = g ∘ id ∘ section_of g : {compose_section f} ... = g ∘ section_of g : {id_left (section_of g)} ... = id : !compose_section) theorem composition_is_inverse [instance] (Hf : is_iso f) (Hg : is_iso g) : is_iso (g ∘ f) := !section_retraction_imp_iso inductive isomorphic (a b : ob) : Type := mk : ∀(g : a ⟶ b) [H : is_iso g], isomorphic a b namespace isomorphic open relation -- should these be coercions? definition iso [coercion] (H : isomorphic a b) : a ⟶ b := isomorphic.rec (λg h, g) H theorem is_iso [instance] (H : isomorphic a b) : is_iso (isomorphic.iso H) := isomorphic.rec (λg h, h) H infix `≅`:50 := isomorphic theorem refl (a : ob) : a ≅ a := mk id theorem symm ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a := mk (inverse (iso H)) theorem trans ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c := mk (iso H2 ∘ iso H1) theorem is_equivalence_eq [instance] (T : Type) : is_equivalence isomorphic := is_equivalence.mk (is_reflexive.mk refl) (is_symmetric.mk symm) (is_transitive.mk trans) end isomorphic inductive is_mono [class] (f : a ⟶ b) : Prop := mk : (∀c (g h : hom c a), f ∘ g = f ∘ h → g = h) → is_mono f inductive is_epi [class] (f : a ⟶ b) : Prop := mk : (∀c (g h : hom b c), g ∘ f = h ∘ f → g = h) → is_epi f theorem mono_elim [H : is_mono f] {g h : c ⟶ a} (H2 : f ∘ g = f ∘ h) : g = h := is_mono.rec (λH3, H3 c g h H2) H theorem epi_elim [H : is_epi f] {g h : b ⟶ c} (H2 : g ∘ f = h ∘ f) : g = h := is_epi.rec (λH3, H3 c g h H2) H theorem section_is_mono [instance] (f : a ⟶ b) [H : is_section f] : is_mono f := is_mono.mk (λ c g h H, calc g = id ∘ g : symm !id_left ... = (retraction_of f ∘ f) ∘ g : {symm (retraction_compose f)} ... = retraction_of f ∘ f ∘ g : symm !assoc ... = retraction_of f ∘ f ∘ h : {H} ... = (retraction_of f ∘ f) ∘ h : !assoc ... = id ∘ h : {retraction_compose f} ... = h : !id_left) theorem retraction_is_epi [instance] (f : a ⟶ b) [H : is_retraction f] : is_epi f := is_epi.mk (λ c g h H, calc g = g ∘ id : symm !id_right ... = g ∘ f ∘ section_of f : {symm (compose_section f)} ... = (g ∘ f) ∘ section_of f : !assoc ... = (h ∘ f) ∘ section_of f : {H} ... = h ∘ f ∘ section_of f : symm !assoc ... = h ∘ id : {compose_section f} ... = h : !id_right) --these theorems are now proven automatically using type classes --should they be instances? theorem id_is_mono : is_mono (ID a) theorem id_is_epi : is_epi (ID a) theorem composition_is_mono [instance] [Hf : is_mono f] [Hg : is_mono g] : is_mono (g ∘ f) := is_mono.mk (λ d h₁ h₂ H, have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂), from symm (assoc g f h₁) ▸ symm (assoc g f h₂) ▸ H, mono_elim (mono_elim H2)) theorem composition_is_epi [instance] [Hf : is_epi f] [Hg : is_epi g] : is_epi (g ∘ f) := is_epi.mk (λ d h₁ h₂ H, have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f, from assoc h₁ g f ▸ assoc h₂ g f ▸ H, epi_elim (epi_elim H2)) end morphism namespace morphism --rewrite lemmas for inverses, modified from --https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v namespace iso section variables {ob : Type} [C : category ob] include C variables {a b c d : ob} (f : b ⟶ a) (r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b) (g : d ⟶ c) variable [Hq : is_iso q] include Hq theorem compose_pV : q ∘ q⁻¹ = id := !compose_inverse theorem compose_Vp : q⁻¹ ∘ q = id := !inverse_compose theorem compose_V_pp : q⁻¹ ∘ (q ∘ p) = p := calc q⁻¹ ∘ (q ∘ p) = (q⁻¹ ∘ q) ∘ p : assoc (q⁻¹) q p ... = id ∘ p : {inverse_compose q} ... = p : id_left p theorem compose_p_Vp : q ∘ (q⁻¹ ∘ g) = g := calc q ∘ (q⁻¹ ∘ g) = (q ∘ q⁻¹) ∘ g : assoc q (q⁻¹) g ... = id ∘ g : {compose_inverse q} ... = g : id_left g theorem compose_pp_V : (r ∘ q) ∘ q⁻¹ = r := calc (r ∘ q) ∘ q⁻¹ = r ∘ q ∘ q⁻¹ : assoc r q (q⁻¹)⁻¹ ... = r ∘ id : {compose_inverse q} ... = r : id_right r theorem compose_pV_p : (f ∘ q⁻¹) ∘ q = f := calc (f ∘ q⁻¹) ∘ q = f ∘ q⁻¹ ∘ q : assoc f (q⁻¹) q⁻¹ ... = f ∘ id : {inverse_compose q} ... = f : id_right f theorem inv_pp [H' : is_iso p] : (q ∘ p)⁻¹ = p⁻¹ ∘ q⁻¹ := have H1 : (p⁻¹ ∘ q⁻¹) ∘ q ∘ p = p⁻¹ ∘ (q⁻¹ ∘ (q ∘ p)), from assoc (p⁻¹) (q⁻¹) (q ∘ p)⁻¹, have H2 : (p⁻¹) ∘ (q⁻¹ ∘ (q ∘ p)) = p⁻¹ ∘ p, from congr_arg _ (compose_V_pp q p), have H3 : p⁻¹ ∘ p = id, from inverse_compose p, inverse_eq_intro_left (H1 ⬝ H2 ⬝ H3) --the proof using calc is hard for the unifier (needs ~90k steps) -- inverse_eq_intro_left -- (calc -- (p⁻¹ ∘ (q⁻¹)) ∘ q ∘ p = p⁻¹ ∘ (q⁻¹ ∘ (q ∘ p)) : assoc (p⁻¹) (q⁻¹) (q ∘ p)⁻¹ -- ... = (p⁻¹) ∘ p : congr_arg (λx, p⁻¹ ∘ x) (compose_V_pp q p) -- ... = id : inverse_compose p) theorem inv_Vp [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q := inverse_involutive q ▸ inv_pp (q⁻¹) g theorem inv_pV [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ := inverse_involutive f ▸ inv_pp q (f⁻¹) theorem inv_VV [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q := inverse_involutive r ▸ inv_Vp q (r⁻¹) end section variables {ob : Type} {C : category ob} include C variables {d c b a : ob} {i : b ⟶ c} {f : b ⟶ a} {r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b} {g : d ⟶ c} {h : c ⟶ b} {x : b ⟶ d} {z : a ⟶ c} {y : d ⟶ b} {w : c ⟶ a} variable [Hq : is_iso q] include Hq theorem moveR_Mp (H : y = q⁻¹ ∘ g) : q ∘ y = g := H⁻¹ ▸ compose_p_Vp q g theorem moveR_pM (H : w = f ∘ q⁻¹) : w ∘ q = f := H⁻¹ ▸ compose_pV_p f q theorem moveR_Vp (H : z = q ∘ p) : q⁻¹ ∘ z = p := H⁻¹ ▸ compose_V_pp q p theorem moveR_pV (H : x = r ∘ q) : x ∘ q⁻¹ = r := H⁻¹ ▸ compose_pp_V r q theorem moveL_Mp (H : q⁻¹ ∘ g = y) : g = q ∘ y := moveR_Mp (H⁻¹)⁻¹ theorem moveL_pM (H : f ∘ q⁻¹ = w) : f = w ∘ q := moveR_pM (H⁻¹)⁻¹ theorem moveL_Vp (H : q ∘ p = z) : p = q⁻¹ ∘ z := moveR_Vp (H⁻¹)⁻¹ theorem moveL_pV (H : r ∘ q = x) : r = x ∘ q⁻¹ := moveR_pV (H⁻¹)⁻¹ theorem moveL_1V (H : h ∘ q = id) : h = q⁻¹ := inverse_eq_intro_left H⁻¹ theorem moveL_V1 (H : q ∘ h = id) : h = q⁻¹ := inverse_eq_intro_right H⁻¹ theorem moveL_1M (H : i ∘ q⁻¹ = id) : i = q := moveL_1V H ⬝ inverse_involutive q theorem moveL_M1 (H : q⁻¹ ∘ i = id) : i = q := moveL_V1 H ⬝ inverse_involutive q theorem moveR_1M (H : id = i ∘ q⁻¹) : q = i := moveL_1M (H⁻¹)⁻¹ theorem moveR_M1 (H : id = q⁻¹ ∘ i) : q = i := moveL_M1 (H⁻¹)⁻¹ theorem moveR_1V (H : id = h ∘ q) : q⁻¹ = h := moveL_1V (H⁻¹)⁻¹ theorem moveR_V1 (H : id = q ∘ h) : q⁻¹ = h := moveL_V1 (H⁻¹)⁻¹ end end iso end morphism
72d1bc33465ff72ee212a0e3b0704c6335cbe82d
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_755.lean
06161306335b2c21b844a4b44531bfbfe44c344c
[]
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
146
lean
import algebra.ring namespace my_ring variables {R : Type*} [ring R] -- BEGIN theorem zero_mul (a : R) : 0 * a = 0 := sorry -- END end my_ring
fea62449e5435f6430f651a198edd5445a9d0262
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/logic/function/basic.lean
c0ddb8d55cc7c6efd938aac335187e7b4982e219
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
27,196
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import logic.basic import data.option.defs /-! # Miscellaneous function constructions and lemmas -/ universes u v w namespace function section variables {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `function.eval x : (Π x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α, y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma id_def : @id α = λ x, x := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext protected lemma bijective.injective {f : α → β} (hf : bijective f) : injective f := hf.1 protected lemma bijective.surjective {f : α → β} (hf : bijective f) : surjective f := hf.2 theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α := λ a b, decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ x y h, I $ show f (g x) = f (g y), from congr_arg f h lemma injective.of_comp_iff {f : α → β} (hf : injective f) (g : γ → α) : injective (f ∘ g) ↔ injective g := ⟨injective.of_comp, hf.comp⟩ lemma injective.of_comp_iff' (f : α → β) {g : γ → α} (hg : bijective g) : injective (f ∘ g) ↔ injective f := ⟨ λ h x y, let ⟨x', hx⟩ := hg.surjective x, ⟨y', hy⟩ := hg.surjective y in hx ▸ hy ▸ λ hf, h hf ▸ rfl, λ h, h.comp hg.injective⟩ lemma injective_of_subsingleton [subsingleton α] (f : α → β) : injective f := λ a b ab, subsingleton.elim _ _ lemma injective.dite (p : α → Prop) [decidable_pred p] {f : {a : α // p a} → β} {f' : {a : α // ¬ p a} → β} (hf : injective f) (hf' : injective f') (im_disj : ∀ {x x' : α} {hx : p x} {hx' : ¬ p x'}, f ⟨x, hx⟩ ≠ f' ⟨x', hx'⟩) : function.injective (λ x, if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) := λ x₁ x₂ h, begin dsimp only at h, by_cases h₁ : p x₁; by_cases h₂ : p x₂, { rw [dif_pos h₁, dif_pos h₂] at h, injection (hf h), }, { rw [dif_pos h₁, dif_neg h₂] at h, exact (im_disj h).elim, }, { rw [dif_neg h₁, dif_pos h₂] at h, exact (im_disj h.symm).elim, }, { rw [dif_neg h₁, dif_neg h₂] at h, injection (hf' h), }, end lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩ lemma surjective.of_comp_iff (f : α → β) {g : γ → α} (hg : surjective g) : surjective (f ∘ g) ↔ surjective f := ⟨surjective.of_comp, λ h, h.comp hg⟩ lemma surjective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : surjective (f ∘ g) ↔ surjective g := ⟨λ h x, let ⟨x', hx'⟩ := h (f x) in ⟨x', hf.injective hx'⟩, hf.surjective.comp⟩ instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr $ λ x, hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr $ λ x, hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x, hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x, hf.exists₂ lemma bijective_iff_exists_unique (f : α → β) : bijective f ↔ ∀ b : β, ∃! (a : α), f a = b := ⟨ λ hf b, let ⟨a, ha⟩ := hf.surjective b in ⟨a, ha, λ a' ha', hf.injective (ha'.trans ha.symm)⟩, λ he, ⟨ λ a a' h, unique_of_exists_unique (he (f a')) h rfl, λ b, exists_of_exists_unique (he b) ⟩⟩ /-- Shorthand for using projection notation with `function.bijective_iff_exists_unique`. -/ lemma bijective.exists_unique {f : α → β} (hf : bijective f) (b : β) : ∃! (a : α), f a = b := (bijective_iff_exists_unique f).mp hf b lemma bijective.of_comp_iff (f : α → β) {g : γ → α} (hg : bijective g) : bijective (f ∘ g) ↔ bijective f := and_congr (injective.of_comp_iff' _ hg) (surjective.of_comp_iff _ hg.surjective) lemma bijective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : function.bijective (f ∘ g) ↔ function.bijective g := and_congr (injective.of_comp_iff hf.injective _) (surjective.of_comp_iff' hf _) /-- Cantor's diagonal argument implies that there are no surjective functions from `α` to `set α`. -/ theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) /-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : (set α) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id] ... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] local attribute [instance, priority 10] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} include n local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β} include i lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective lemma surjective_to_subsingleton [na : nonempty α] [subsingleton β] (f : α → β) : surjective f := λ y, let ⟨a⟩ := na in ⟨a, subsingleton.elim _ _⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a /-- On non-dependent functions, `function.update` can be expressed as an `ite` -/ lemma update_apply {β : Sort*} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := begin dunfold update, congr, funext, rw eq_rec_constant, end @[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v := dif_pos rfl lemma update_injective (f : Πa, β a) (a' : α) : injective (update f a') := λ v v' h, have _ := congr_fun h a', by rwa [update_same, update_same] at this @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a := dif_neg h lemma forall_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x ≠ a, p x (f x) := calc (∀ x, p x (update f a b x)) ↔ ∀ x, (x = a ∨ x ≠ a) → p x (update f a b x) : by simp only [ne.def, classical.em, forall_prop_of_true] ... ↔ p a b ∧ ∀ x ≠ a, p x (f x) : by simp [or_imp_distrib, forall_and_distrib] { contextual := tt } lemma update_eq_iff {a : α} {b : β a} {f g : Π a, β a} : update f a b = g ↔ b = g a ∧ ∀ x ≠ a, f x = g x := funext_iff.trans $ forall_update_iff _ (λ x y, y = g x) lemma eq_update_iff {a : α} {b : β a} {f g : Π a, β a} : g = update f a b ↔ g a = b ∧ ∀ x ≠ a, g x = f x := funext_iff.trans $ forall_update_iff _ (λ x y, g x = y) @[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, λ _ _, rfl⟩ lemma update_comp_eq_of_forall_ne' {α'} (g : Π a, β a) {f : α' → α} {i : α} (a : β i) (h : ∀ x, f x ≠ i) : (λ j, (update g i a) (f j)) = (λ j, g (f j)) := funext $ λ x, update_noteq (h _) _ _ /-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/ lemma update_comp_eq_of_forall_ne {α β : Sort*} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ x, f x ≠ i) : (update g i a) ∘ f = g ∘ f := update_comp_eq_of_forall_ne' g a h lemma update_comp_eq_of_injective' (g : Π a, β a) {f : α' → α} (hf : function.injective f) (i : α') (a : β (f i)) : (λ j, update g (f i) a (f j)) = update (λ i, g (f i)) i a := eq_update_iff.2 ⟨update_same _ _ _, λ j hj, update_noteq (hf.ne hj) _ _⟩ /-- Non-dependent version of `function.update_comp_eq_of_injective'` -/ lemma update_comp_eq_of_injective {β : Sort*} (g : α' → β) {f : α → α'} (hf : function.injective f) (i : α) (a : β) : (function.update g (f i) a) ∘ f = function.update (g ∘ f) i a := update_comp_eq_of_injective' g hf i a lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*} (f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [decidable_eq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) : update (update f a v) b w = update (update f b w) a v := begin funext c, simp only [update], by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]}, cases h (h₂.symm.trans h₁), end @[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*} {a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w := by {funext b, by_cases b = a; simp [update, h]} end update section extend noncomputable theory local attribute [instance, priority 10] classical.prop_decidable variables {α β γ : Type*} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) [decidable (∃ a, f a = b)] : extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := by { unfold extend, congr } @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := begin simp only [extend_def, dif_pos, exists_apply_eq_apply], exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a)) end @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a, extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variables {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) := rfl end bicomp section uncurry variables {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ)) /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps.-/ add_decl_doc has_uncurry.uncurry notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) := funext_iff.symm namespace involutive variables {α : Sort u} {f : α → α} (h : involutive f) include h @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] /-- An involution commutes across an equality. Compare to `function.injective.eq_iff`. -/ protected lemma eq_iff {x y : α} : f x = y ↔ x = f y := h.injective.eq_iff' (h y) end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variables {α β γ : Type*} (f : α → β → γ) protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩ end injective2 section sometimes local attribute [instance, priority 10] classical.prop_decidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β := if h : nonempty α then f (classical.choice h) else classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa sometimes_eq end sometimes end function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] : Πi, β i := λi, if i ∈ s then f i else g i /-! ### Bijectivity of `eq.rec`, `eq.mp`, `eq.mpr`, and `cast` -/ lemma eq_rec_on_bijective {α : Sort*} {C : α → Sort*} : ∀ {a a' : α} (h : a = a'), function.bijective (@eq.rec_on _ _ C _ h) | _ _ rfl := ⟨λ x y, id, λ x, ⟨x, rfl⟩⟩ lemma eq_mp_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mp h) := eq_rec_on_bijective h lemma eq_mpr_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mpr h) := eq_rec_on_bijective h.symm lemma cast_bijective {α β : Sort*} (h : α = β) : function.bijective (cast h) := eq_rec_on_bijective h /-! Note these lemmas apply to `Type*` not `Sort*`, as the latter interferes with `simp`, and is trivial anyway.-/ @[simp] lemma eq_rec_inj {α : Sort*} {a a' : α} (h : a = a') {C : α → Type*} (x y : C a) : (eq.rec x h : C a') = eq.rec y h ↔ x = y := (eq_rec_on_bijective h).injective.eq_iff @[simp] lemma cast_inj {α β : Type*} (h : α = β) {x y : α} : cast h x = cast h y ↔ x = y := (cast_bijective h).injective.eq_iff /-- A set of functions "separates points" if for each pair of distinct points there is a function taking different values on them. -/ def set.separates_points {α β : Type*} (A : set (α → β)) : Prop := ∀ ⦃x y : α⦄, x ≠ y → ∃ f ∈ A, (f x : β) ≠ f y
695cc4f9d68ca771cdc28ccf3897b1314fd494a9
3863d2564418bccb1859e057bf5a4ef240e75fd7
/hott/homotopy/quaternionic_hopf.hlean
698a91a22a535d428d25d30134ede91b6cdeb1b4
[ "Apache-2.0" ]
permissive
JacobGross/lean
118bbb067ff4d4af48a266face2c7eb9868fa91c
eb26087df940c54337cb807b4bc6d345d1fc1085
refs/heads/master
1,582,735,011,532
1,462,557,826,000
1,462,557,826,000
46,451,196
0
0
null
1,462,557,826,000
1,447,885,161,000
C++
UTF-8
Lean
false
false
4,192
hlean
/- Copyright (c) 2016 Ulrik Buchholtz and Egbert Rijke. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz, Egbert Rijke The H-space structure on S³ and the quaternionic Hopf fibration (using the imaginaroid structure on S⁰). -/ import .complex_hopf .imaginaroid open eq equiv is_equiv circle is_conn trunc is_trunc sphere_index sphere susp open imaginaroid namespace hopf definition involutive_neg_empty [instance] : involutive_neg empty := ⦃ involutive_neg, neg := empty.elim, neg_neg := by intro a; induction a ⦄ definition involutive_neg_circle [instance] : involutive_neg circle := involutive_neg_susp definition has_star_circle [instance] : has_star circle := has_star_susp -- this is the "natural" conjugation defined using the base-loop recursor definition circle_star [reducible] : S¹ → S¹ := circle.elim base loop⁻¹ definition circle_neg_id (x : S¹) : -x = x := begin fapply (rec2_on x), { exact seg2⁻¹ }, { exact seg1 }, { apply eq_pathover, rewrite ap_id, krewrite elim_merid, apply square_of_eq, reflexivity }, { apply eq_pathover, rewrite ap_id, krewrite elim_merid, apply square_of_eq, apply trans (con.left_inv seg2), apply inverse, exact con.left_inv seg1 } end definition circle_mul_neg (x y : S¹) : x * (-y) = - x * y := by rewrite [circle_neg_id,circle_neg_id] definition circle_star_eq (x : S¹) : x* = circle_star x := begin fapply (rec2_on x), { reflexivity }, { exact seg2⁻¹ ⬝ (tr_constant seg1 base)⁻¹ }, { apply eq_pathover, krewrite elim_merid, rewrite elim_seg1, apply square_of_eq, apply trans (ap (λw, w ⬝ (tr_constant seg1 base)⁻¹) (con.right_inv seg2)⁻¹), apply con.assoc }, { apply eq_pathover, krewrite elim_merid, rewrite elim_seg2, apply square_of_eq, rewrite [↑loop,con_inv,inv_inv,idp_con], apply con.assoc } end open prod prod.ops definition circle_norm (x : S¹) : x * x* = 1 := begin rewrite circle_star_eq, induction x, { reflexivity }, { apply eq_pathover, rewrite ap_constant, krewrite [ap_compose' (λz : S¹ × S¹, circle_mul z.1 z.2) (λa : S¹, (a, circle_star a))], rewrite [ap_compose' (prod_functor (λa : S¹, a) circle_star) (λa : S¹, (a, a))], rewrite ap_diagonal, krewrite [ap_prod_functor (λa : S¹, a) circle_star loop loop], rewrite [ap_id,↑circle_star], krewrite elim_loop, krewrite (ap_binary circle_mul loop loop⁻¹), rewrite [ap_inv,↑circle_mul,elim_loop,ap_id,↑circle_turn,con.left_inv], constructor } end definition circle_star_mul (x y : S¹) : (x * y)* = y* * x* := begin induction x, { apply inverse, exact circle_mul_base (y*) }, { apply eq_pathover, induction y, { exact natural_square_tr (λa : S¹, ap (λb : S¹, b*) (circle_mul_base a)) loop }, { apply is_prop.elimo } } end definition imaginaroid_sphere_zero [instance] : imaginaroid (sphere (-1.+1)) := ⦃ imaginaroid, neg_neg := susp_neg_neg, mul := circle_mul, one_mul := circle_base_mul, mul_one := circle_mul_base, mul_neg := circle_mul_neg, norm := circle_norm, star_mul := circle_star_mul ⦄ local attribute sphere [reducible] open sphere.ops definition sphere_three_h_space [instance] : h_space (S 3) := @h_space_equiv_closed (join S¹ S¹) (cd_h_space (S -1.+1) circle_assoc) (S 3) (join.spheres 1 1) definition is_conn_sphere_three : is_conn 0 (S 3) := begin have le02 : trunc_index.le 0 2, from trunc_index.le.step (trunc_index.le.step (trunc_index.le.tr_refl 0)), exact @is_conn_of_le (S 3) 0 2 le02 (is_conn_sphere 3) -- apply is_conn_of_le (S 3) le02 -- doesn't find is_conn_sphere instance end local attribute is_conn_sphere_three [instance] definition quaternionic_hopf : S 7 → S 4 := begin intro x, apply @sigma.pr1 (susp (S 3)) (hopf (S 3)), apply inv (hopf.total (S 3)), apply inv (join.spheres 3 3), exact x end end hopf
90c593ef812929f454419028c2b43e43f335c6bb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1922.lean
088a539ea3252145d28ce9eb438666017f9cb79d
[ "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
121
lean
set_option pp.implicit true structure C := ( d : Π { X : Type }, list X → list X ) def P(c : C):= c.d [0] #print P
d8cfa7f8ac4101a76dd5599fa11ce91b6742d657
07f5f86b00fed90a419ccda4298d8b795a68f657
/library/init/data/option_t.lean
c3724de613b8c444b4cbd35c91d3244eeb1246a7
[ "Apache-2.0" ]
permissive
VBaratham/lean
8ec5c3167b4835cfbcd7f25e2173d61ad9416b3a
450ca5834c1c35318e4b47d553bb9820c1b3eee7
refs/heads/master
1,629,649,471,814
1,512,060,373,000
1,512,060,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,227
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.interactive init.category.transformers universes u v def option_t (m : Type u → Type v) [monad m] (α : Type u) : Type v := m (option α) @[inline] def option_t_bind {m : Type u → Type v} [monad m] {α β : Type u} (a : option_t m α) (b : α → option_t m β) : option_t m β := show m (option β), from do o ← a, match o with | none := return none | (some a) := b a end @[inline] def option_t_return {m : Type u → Type v} [monad m] {α : Type u} (a : α) : option_t m α := show m (option α), from return (some a) instance {m : Type u → Type v} [monad m] : monad (option_t m) := {pure := @option_t_return m _, bind := @option_t_bind m _, id_map := begin intros, simp [option_t_bind, function.comp], have h : option_t_bind._match_1 option_t_return = @pure m _ (option α), { apply funext, intro s, cases s; refl }, { simp [h, monad.bind_pure] }, end, pure_bind := begin intros, simp [option_t_bind, option_t_return, monad.pure_bind] end, bind_assoc := begin intros, simp [option_t_bind, option_t_return, monad.bind_assoc], apply congr_arg, apply funext, intro x, cases x, { simp [option_t_bind, monad.pure_bind] }, { refl } end} def option_t_orelse {m : Type u → Type v} [monad m] {α : Type u} (a : option_t m α) (b : option_t m α) : option_t m α := show m (option α), from do o ← a, match o with | none := b | (some v) := return (some v) end def option_t_fail {m : Type u → Type v} [monad m] {α : Type u} : option_t m α := show m (option α), from return none instance {m : Type u → Type v} [monad m] : alternative (option_t m) := { failure := @option_t_fail m _, orelse := @option_t_orelse m _, ..@option_t.monad m _ } def option_t.lift {m : Type u → Type v} [monad m] {α : Type u} (a : m α) : option_t m α := (some <$> a : m (option α)) instance option_t.monad_transformer : monad.monad_transformer option_t := { is_monad := @option_t.monad, monad_lift := @option_t.lift }
fa84f204bfcd2f26c0a75d04a919259e6558ef14
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/uniform_ring.lean
1e765f6aca777d897bce9b73184afb228d4c18e9
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
11,956
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 -/ import algebra.algebra.basic import topology.algebra.group_completion import topology.algebra.ring /-! # Completion of topological rings: This files endows the completion of a topological ring with a ring structure. More precisely the instance `uniform_space.completion.ring` builds a ring structure on the completion of a ring endowed with a compatible uniform structure in the sense of `uniform_add_group`. There is also a commutative version when the original ring is commutative. Moreover, if a topological ring is an algebra over a commutative semiring, then so is its `uniform_space.completion`. The last part of the file builds a ring structure on the biggest separated quotient of a ring. ## Main declarations: Beyond the instances explained above (that don't have to be explicitly invoked), the main constructions deal with continuous ring morphisms. * `uniform_space.completion.extension_hom`: extends a continuous ring morphism from `R` to a complete separated group `S` to `completion R`. * `uniform_space.completion.map_ring_hom` : promotes a continuous ring morphism from `R` to `S` into a continuous ring morphism from `completion R` to `completion S`. TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`. -/ open classical set filter topological_space add_comm_group open_locale classical noncomputable theory universes u 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 let m := (add_monoid_hom.mul : α →+ α →+ α).compr₂ to_compl, have : continuous (λ p : α × α, m p.1 p.2), from (continuous_coe α).comp continuous_mul, have di : dense_inducing (to_compl : α → completion α), from dense_inducing_coe, convert di.extend_Z_bilin di this, ext ⟨x, y⟩, refl 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 (hf.prod_mk 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]), .. add_monoid_with_one.unary, ..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⟩ lemma continuous_coe_ring_hom : continuous (coe_ring_hom : α → completion α) := continuous_coe α 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' : continuous (f : α →+ β), from hf, -- helping the elaborator have hf : uniform_continuous f, from uniform_continuous_add_monoid_hom_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 } /-- The completion map as a ring morphism. -/ def map_ring_hom (hf : continuous f) : completion α →+* completion β := extension_hom (coe_ring_hom.comp f) (continuous_coe_ring_hom.comp hf) section algebra variables (A : Type*) [ring A] [uniform_space A] [uniform_add_group A] [topological_ring A] (R : Type*) [comm_semiring R] [algebra R A] [has_uniform_continuous_const_smul R A] @[simp] lemma map_smul_eq_mul_coe (r : R) : completion.map ((•) r) = (*) (algebra_map R A r : completion A) := begin ext x, refine completion.induction_on x _ (λ a, _), { exact is_closed_eq (completion.continuous_map) (continuous_mul_left _) }, { rw [map_coe (uniform_continuous_const_smul r) a, algebra.smul_def, coe_mul] }, end instance : algebra R (completion A) := { commutes' := λ r x, completion.induction_on x (is_closed_eq (continuous_mul_left _) (continuous_mul_right _)) $ λ a, by simpa only [coe_mul] using congr_arg (coe : A → completion A) (algebra.commutes r a), smul_def' := λ r x, congr_fun (map_smul_eq_mul_coe A R r) x, ..((uniform_space.completion.coe_ring_hom : A →+* completion A).comp (algebra_map R A)) } lemma algebra_map_def (r : R) : algebra_map R (completion A) r = (algebra_map R A r : completion A) := rfl end algebra section comm_ring 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 } /-- A shortcut instance for the common case -/ instance algebra' : algebra R (completion R) := by apply_instance end comm_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 $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm lemma ring_sep_quot (α : Type u) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (α ⧸ (⊥ : ideal α).closure) := 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.congr_right $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm /- 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 section uniform_extension variables {α : Type*} [uniform_space α] [semiring α] variables {β : Type*} [uniform_space β] [semiring β] [topological_semiring β] variables {γ : Type*} [uniform_space γ] [semiring γ] [topological_semiring γ] variables [t2_space γ] [complete_space γ] /-- The dense inducing extension as a ring homomorphism. -/ noncomputable def dense_inducing.extend_ring_hom {i : α →+* β} {f : α →+* γ} (ue : uniform_inducing i) (dr : dense_range i) (hf : uniform_continuous f): β →+* γ := { to_fun := (ue.dense_inducing dr).extend f, map_one' := by { convert dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous 1, exacts [i.map_one.symm, f.map_one.symm], }, map_zero' := by { convert dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous 0, exacts [i.map_zero.symm, f.map_zero.symm], }, map_add' := begin have h := (uniform_continuous_uniformly_extend ue dr hf).continuous, refine λ x y, dense_range.induction_on₂ dr _ (λ a b, _) x y, { exact is_closed_eq (continuous.comp h continuous_add) ((h.comp continuous_fst).add (h.comp continuous_snd)), }, { simp_rw [← i.map_add, dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous _, ← f.map_add], }, end, map_mul' := begin have h := (uniform_continuous_uniformly_extend ue dr hf).continuous, refine λ x y, dense_range.induction_on₂ dr _ (λ a b, _) x y, { exact is_closed_eq (continuous.comp h continuous_mul) ((h.comp continuous_fst).mul (h.comp continuous_snd)), }, { simp_rw [← i.map_mul, dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous _, ← f.map_mul], }, end, } end uniform_extension
52ae12b7dfbec355d2b4ea5bc6833f6cf82d17c1
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/equiv/mul_add.lean
1ffe098d9decf2416bd1056041018ea71bcd8f66
[ "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
10,506
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.basic import deprecated.group /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. We also introduce the corresponding groups of automorphisms `add_aut` and `mul_aut`. ## Notations The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, mul_aut, add_aut -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {G : Type*} {H : Type*} set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B := (map_add' : ∀ x y : A, to_fun (x + y) = to_fun x + to_fun y) /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N := (map_mul' : ∀ x y : M, to_fun (x * y) = to_fun x * to_fun y) infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive] instance (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive] def symm (h : M ≃* N) : N ≃* M := { map_mul' := λ n₁ n₂, function.injective_of_left_inverse h.left_inv begin show h.to_equiv (h.to_equiv.symm (n₁ * n₂)) = h ((h.to_equiv.symm n₁) * (h.to_equiv.symm n₂)), rw h.map_mul, show _ = h.to_equiv (_) * h.to_equiv (_), rw [h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply, h.to_equiv.apply_symm_apply], end, ..h.to_equiv.symm} @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] theorem coe_symm_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃).symm = g := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply /-- a multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism) -/ @[simp, to_additive] lemma map_one {M N} [monoid M] [monoid N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq x 1 @[to_additive] lemma map_ne_one_iff {M N} [monoid M] [monoid N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- Extract the forward direction of a multiplicative equivalence as a multiplication preserving function. -/ @[to_additive to_add_monoid_hom] def to_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma to_monoid_hom_apply {M N} [monoid M] [monoid N] (e : M ≃* N) (x : M) : e.to_monoid_hom x = e x := rfl /-- A multiplicative equivalence of groups preserves inversion. -/ @[to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use to_monoid_hom). -/ @[to_additive is_add_monoid_hom] instance is_monoid_hom {M N} [monoid M] [monoid N] (h : M ≃* N) : is_monoid_hom h := ⟨h.map_one⟩ /-- A multiplicative bijection between two groups is a group hom (deprecated -- use to_monoid_hom). -/ @[to_additive is_add_group_hom] instance is_group_hom {G H} [group G] [group H] (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ := equiv.ext f.to_equiv g.to_equiv h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext end mul_equiv /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y /-- The group of multiplicative automorphisms. -/ @[to_additive "The group of additive automorphisms."] def mul_aut (M : Type*) [has_mul M] := M ≃* M namespace mul_aut variables (M) [has_mul M] /-- The group operation on multiplicative automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (mul_aut M) := by refine_struct { mul := λ g h, mul_equiv.trans h g, one := mul_equiv.refl M, inv := mul_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (mul_aut M) := ⟨1⟩ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : mul_aut M →* equiv.perm M := by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl end mul_aut namespace add_aut variables (A) [has_add A] /-- The group operation on additive automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance group : group (add_aut A) := by refine_struct { mul := λ g h, add_equiv.trans h g, one := add_equiv.refl A, inv := add_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (add_aut A) := ⟨1⟩ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : add_aut A →* equiv.perm A := by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl end add_aut /-- A group is isomorphic to its group of units. -/ def to_units (G) [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } end units namespace equiv section group variables [group G] @[to_additive] protected def mul_left (a : G) : perm G := { to_fun := λx, a * x, inv_fun := λx, a⁻¹ * x, left_inv := assume x, show a⁻¹ * (a * x) = x, from inv_mul_cancel_left a x, right_inv := assume x, show a * (a⁻¹ * x) = x, from mul_inv_cancel_left a x } @[to_additive] protected def mul_right (a : G) : perm G := { to_fun := λx, x * a, inv_fun := λx, x * a⁻¹, left_inv := assume x, show (x * a) * a⁻¹ = x, from mul_inv_cancel_right x a, right_inv := assume x, show (x * a⁻¹) * a = x, from inv_mul_cancel_right x a } variable (G) @[to_additive] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } end group section point_reflection variables [add_comm_group A] (x y : A) /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : A) : perm A := (equiv.neg A).trans (equiv.add_left (x + x)) lemma point_reflection_apply : point_reflection x y = x + x - y := rfl @[simp] lemma point_reflection_self : point_reflection x x = x := add_sub_cancel _ _ lemma point_reflection_involutive : function.involutive (point_reflection x : A → A) := λ y, by simp only [point_reflection_apply, sub_sub_cancel] @[simp] lemma point_reflection_symm : (point_reflection x).symm = point_reflection x := by { ext y, rw [symm_apply_eq, point_reflection_involutive x y] } /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_bit0_inj {x y : A} (h : function.injective (bit0 : A → A)) : point_reflection x y = y ↔ y = x := sub_eq_iff_eq_add.trans $ h.eq_iff.trans eq_comm end point_reflection end equiv
ad51c7edc2be85588b047b80ca0cbb23656fcffe
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/affine_space/basic.lean
18437f0e711ce05ca968e4edafe2e4139b6102dd
[ "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,706
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import algebra.add_torsor /-! # Affine space In this file we introduce the following notation: * `affine_space V P` is an alternative notation for `add_torsor V P` introduced at the end of this file. We tried to use an `abbreviation` instead of a `notation` but this led to hard-to-debug elaboration errors. So, we introduce a localized notation instead. When this notation is enabled with `open_locale affine`, Lean will use `affine_space` instead of `add_torsor` both in input and in the proof state. Here is an incomplete list of notions related to affine spaces, all of them are defined in other files: * `affine_map`: a map between affine spaces that preserves the affine structure; * `affine_equiv`: an equivalence between affine spaces that preserves the affine structure; * `affine_subspace`: a subset of an affine space closed w.r.t. affine combinations of points; * `affine_combination`: an affine combination of points; * `affine_independent`: affine independent set of points. ## TODO Some key definitions are not yet present. * Affine frames. An affine frame might perhaps be represented as an `affine_equiv` to a `finsupp` (in the general case) or function type (in the finite-dimensional case) that gives the coordinates, with appropriate proofs of existence when `k` is a field. * Although results on affine combinations implicitly provide barycentric frames and coordinates, there is no explicit representation of the map from a point to its coordinates. -/ localized "notation `affine_space` := add_torsor" in affine
890f3408dd87140823bf74f3537b074bcce1aaae
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/field_theory/fixed.lean
8383f7ab388f7219a6069e25eba4753fe71a4d10
[ "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
14,736
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import field_theory.normal import field_theory.separable import field_theory.tower import ring_theory.polynomial /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables {M : Type u} [monoid M] variables (G : Type u) [group G] variables (F : Type v) [field F] [mul_semiring_action M F] [mul_semiring_action G F] (m : M) /-- The subfield of F fixed by the field endomorphism `m`. -/ def fixed_by.subfield : subfield F := { carrier := fixed_by M F m, zero_mem' := smul_zero m, add_mem' := λ x y hx hy, (smul_add m x y).trans $ congr_arg2 _ hx hy, neg_mem' := λ x hx, (smul_neg m x).trans $ congr_arg _ hx, one_mem' := smul_one m, mul_mem' := λ x y hx hy, (smul_mul' m x y).trans $ congr_arg2 _ hx hy, inv_mem' := λ x hx, (smul_inv' F m x).trans $ congr_arg _ hx } section invariant_subfields variables (M) {F} /-- A typeclass for subrings invariant under a `mul_semiring_action`. -/ class is_invariant_subfield (S : subfield F) : Prop := (smul_mem : ∀ (m : M) {x : F}, x ∈ S → m • x ∈ S) variable (S : subfield F) instance is_invariant_subfield.to_mul_semiring_action [is_invariant_subfield M S] : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subfield.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } instance [is_invariant_subfield M S] : is_invariant_subring M (S.to_subring) := { smul_mem := is_invariant_subfield.smul_mem } end invariant_subfields namespace fixed_points variable (M) -- we use `subfield.copy` so that the underlying set is `fixed_points M F` /-- The subfield of fixed points by a monoid action. -/ def subfield : subfield F := subfield.copy (⨅ (m : M), fixed_by.subfield F m) (fixed_points M F) (by { ext z, simp [fixed_points, fixed_by.subfield, infi, subfield.mem_Inf] }) instance : is_invariant_subfield M (fixed_points.subfield M F) := { smul_mem := λ g x hx g', by rw [hx, hx] } @[simp] theorem smul (m : M) (x : fixed_points.subfield M F) : m • x = x := subtype.eq $ x.2 m -- Why is this so slow? @[simp] theorem smul_polynomial (m : M) (p : polynomial (fixed_points.subfield M F)) : m • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow, polynomial.smul_X]) instance : algebra (fixed_points.subfield M F) F := algebra.of_subring (fixed_points.subfield M F).to_subring theorem coe_algebra_map : algebra_map (fixed_points.subfield M F) F = subfield.subtype (fixed_points.subfield M F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points.subfield G F) (λ i : (s : set F), (i : F)) → linear_independent F (λ i : (s : set F), mul_action.to_fun G F i) := begin haveI : is_empty ((∅ : finset F) : set F) := ⟨subtype.prop⟩, refine finset.induction_on s (λ _, linear_independent_empty_type) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points.subfield G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points.subfield G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • (to_fun G F) i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points.subfield G F) := (prod_X_sub_smul G F x).to_subring (fixed_points.subfield G F).to_subring $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (subring.subtype $ (fixed_points.subfield G F).to_subring) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp only [minpoly, polynomial.map_to_subring], end theorem eval₂' : polynomial.eval₂ (subfield.subtype $ (fixed_points.subfield G F)) x (minpoly G F x) = 0 := eval₂ G F x theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points.subfield G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points.subfield G F)) (hf : polynomial.eval₂ (subfield.subtype $ fixed_points.subfield G F) x f = 0) : minpoly G F x ∣ f := begin erw [← polynomial.map_dvd_map' (subfield.subtype $ fixed_points.subfield G F), minpoly, polynomial.map_to_subring _ (subfield G F).to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← subfield.to_subring.subtype_eq_subtype, ← is_invariant_subring.coe_subtype_hom' G (fixed_points.subfield G F).to_subring, ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, subfield.to_subring.subtype_eq_subtype, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points.subfield G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points.subfield G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points.subfield G F) x := minpoly.unique' (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, ← subfield.to_subring.subtype_eq_subtype, polynomial.map_to_subring _ (fixed_points.subfield G F).to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points.subfield G F) F := ⟨λ x, is_integral G F x, λ x, by { -- this was a plain rw when we were using unbundled subrings erw [← minpoly_eq_minpoly, ← polynomial.separable_map (fixed_points.subfield G F).subtype, minpoly, polynomial.map_to_subring _ ((subfield G F).to_subring) ], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : module.rank (fixed_points.subfield G F) F ≤ fintype.card G := begin refine dim_le (λ s hs, cardinal.nat_cast_le.1 _), rw [← @dim_fun' F G, ← cardinal.lift_nat_cast.{v (max u v)}, cardinal.finset_card, ← cardinal.lift_id (module.rank F (G → F))], exact cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max u v)} (linear_independent_smul_of_linear_independent G F hs) end instance : finite_dimensional (fixed_points.subfield G F) F := is_noetherian.iff_dim_lt_omega.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_omega _) lemma finrank_le_card : finrank (fixed_points.subfield G F) F ≤ fintype.card G := begin rw [← cardinal.nat_cast_le, finrank_eq_dim], apply dim_le_card, end end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [integral_domain A] [algebra R A] [integral_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_hom.fintype (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : fintype (V →ₐ[K] W) := classical.choice $ cardinal.lt_omega_iff_fintype.1 $ lt_of_le_of_lt (cardinal_mk_alg_hom K V W) (cardinal.nat_lt_omega _) noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points /-- Embedding produced from a faithful action. -/ @[simps apply {fully_applied := ff}] def to_alg_hom (G : Type u) (F : Type v) [group G] [field F] [mul_semiring_action G F] [has_faithful_scalar G F] : G ↪ (F →ₐ[fixed_points.subfield G F] F) := { to_fun := λ g, { commutes' := λ x, x.2 g, .. mul_semiring_action.to_ring_hom G F g }, inj' := λ g₁ g₂ hg, to_ring_hom_injective G F $ ring_hom.ext $ λ x, alg_hom.ext_iff.1 hg x, } lemma to_alg_hom_apply_apply {G : Type u} {F : Type v} [group G] [field F] [mul_semiring_action G F] [has_faithful_scalar G F] (g : G) (x : F) : to_alg_hom G F g x = g • x := rfl theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : finrank (fixed_points.subfield G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points.subfield G F] F) : fintype.card_le_of_injective _ (to_alg_hom G F).2 ... ≤ finrank F (F →ₗ[fixed_points.subfield G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points.subfield G F) F : finrank_linear_map' _ _ _ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : function.bijective (to_alg_hom G F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact (to_alg_hom G F).injective }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (to_alg_hom G F).injective }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [mul_semiring_action G F] [has_faithful_scalar G F] : G ≃ (F →ₐ[fixed_points.subfield G F] F) := function.embedding.equiv_of_surjective (to_alg_hom G F) (to_alg_hom_bijective G F).2 end fixed_points
b052b4957d71e8546f144b5a95086b0a17bf815a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/homology/complex_shape.lean
640e7ce12ade7db1e560ca0346afe349a556ba8a
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,663
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebra.group.defs import logic.relation /-! # Shapes of homological complexes We define a structure `complex_shape ι` for describing the shapes of homological complexes indexed by a type `ι`. This is intended to capture chain complexes and cochain complexes, indexed by either `ℕ` or `ℤ`, as well as more exotic examples. Rather than insisting that the indexing type has a `succ` function specifying where differentials should go, inside `c : complex_shape` we have `c.rel : ι → ι → Prop`, and when we define `homological_complex` we only allow nonzero differentials `d i j` from `i` to `j` if `c.rel i j`. Further, we require that `{ j // c.rel i j }` and `{ i // c.rel i j }` are subsingletons. This means that the shape consists of some union of lines, rays, intervals, and circles. Convenience functions `c.next` and `c.prev` provide these related elements when they exist, and return their input otherwise. This design aims to avoid certain problems arising from dependent type theory. In particular we never have to ensure morphisms `d i : X i ⟶ X (succ i)` compose as expected (which would often require rewriting by equations in the indexing type). Instead such identities become separate proof obligations when verifying that a complex we've constructed is of the desired shape. If `α` is an `add_right_cancel_semigroup`, then we define `up α : complex_shape α`, the shape appropriate for cohomology,so `d : X i ⟶ X j` is nonzero only when `j = i + 1`, as well as `down α : complex_shape α`, appropriate for homology, so `d : X i ⟶ X j` is nonzero only when `i = j + 1`. (Later we'll introduce `cochain_complex` and `chain_complex` as abbreviations for `homological_complex` with one of these shapes baked in.) -/ open_locale classical noncomputable theory /-- A `c : complex_shape ι` describes the shape of a chain complex, with chain groups indexed by `ι`. Typically `ι` will be `ℕ`, `ℤ`, or `fin n`. There is a relation `rel : ι → ι → Prop`, and we will only allow a non-zero differential from `i` to `j` when `rel i j`. There are axioms which imply `{ j // c.rel i j }` and `{ i // c.rel i j }` are subsingletons. This means that the shape consists of some union of lines, rays, intervals, and circles. Below we define `c.next` and `c.prev` which provide these related elements. -/ @[ext, nolint has_nonempty_instance] structure complex_shape (ι : Type*) := (rel : ι → ι → Prop) (next_eq : ∀ {i j j'}, rel i j → rel i j' → j = j') (prev_eq : ∀ {i i' j}, rel i j → rel i' j → i = i') namespace complex_shape variables {ι : Type*} /-- The complex shape where only differentials from each `X.i` to itself are allowed. This is mostly only useful so we can describe the relation of "related in `k` steps" below. -/ @[simps] def refl (ι : Type*) : complex_shape ι := { rel := λ i j, i = j, next_eq := λ i j j' w w', w.symm.trans w', prev_eq := λ i i' j w w', w.trans w'.symm, } /-- The reverse of a `complex_shape`. -/ @[simps] def symm (c : complex_shape ι) : complex_shape ι := { rel := λ i j, c.rel j i, next_eq := λ i j j' w w', c.prev_eq w w', prev_eq := λ i i' j w w', c.next_eq w w', } @[simp] lemma symm_symm (c : complex_shape ι) : c.symm.symm = c := by { ext, simp, } /-- The "composition" of two `complex_shape`s. We need this to define "related in k steps" later. -/ @[simp] def trans (c₁ c₂ : complex_shape ι) : complex_shape ι := { rel := relation.comp c₁.rel c₂.rel, next_eq := λ i j j' w w', begin obtain ⟨k, w₁, w₂⟩ := w, obtain ⟨k', w₁', w₂'⟩ := w', rw c₁.next_eq w₁ w₁' at w₂, exact c₂.next_eq w₂ w₂', end, prev_eq := λ i i' j w w', begin obtain ⟨k, w₁, w₂⟩ := w, obtain ⟨k', w₁', w₂'⟩ := w', rw c₂.prev_eq w₂ w₂' at w₁, exact c₁.prev_eq w₁ w₁', end } instance subsingleton_next (c : complex_shape ι) (i : ι) : subsingleton { j // c.rel i j } := begin fsplit, rintros ⟨j, rij⟩ ⟨k, rik⟩, congr, exact c.next_eq rij rik, end instance subsingleton_prev (c : complex_shape ι) (j : ι) : subsingleton { i // c.rel i j } := begin fsplit, rintros ⟨i, rik⟩ ⟨j, rjk⟩, congr, exact c.prev_eq rik rjk, end /-- An arbitary choice of index `j` such that `rel i j`, if such exists. Returns `i` otherwise. -/ def next (c : complex_shape ι) (i : ι) : ι := if h : ∃ j, c.rel i j then h.some else i /-- An arbitary choice of index `i` such that `rel i j`, if such exists. Returns `j` otherwise. -/ def prev (c : complex_shape ι) (j : ι) : ι := if h : ∃ i, c.rel i j then h.some else j lemma next_eq' (c : complex_shape ι) {i j : ι} (h : c.rel i j) : c.next i = j := by { apply c.next_eq _ h, dsimp only [next], rw dif_pos, exact Exists.some_spec ⟨j, h⟩, } lemma prev_eq' (c : complex_shape ι) {i j : ι} (h : c.rel i j) : c.prev j = i := by { apply c.prev_eq _ h, dsimp only [prev], rw dif_pos, exact Exists.some_spec ⟨i, h⟩, } /-- The `complex_shape` allowing differentials from `X i` to `X (i+a)`. (For example when `a = 1`, a cohomology theory indexed by `ℕ` or `ℤ`) -/ @[simps] def up' {α : Type*} [add_right_cancel_semigroup α] (a : α) : complex_shape α := { rel := λ i j , i + a = j, next_eq := λ i j k hi hj, hi.symm.trans hj, prev_eq := λ i j k hi hj, add_right_cancel (hi.trans hj.symm), } /-- The `complex_shape` allowing differentials from `X (j+a)` to `X j`. (For example when `a = 1`, a homology theory indexed by `ℕ` or `ℤ`) -/ @[simps] def down' {α : Type*} [add_right_cancel_semigroup α] (a : α) : complex_shape α := { rel := λ i j , j + a = i, next_eq := λ i j k hi hj, add_right_cancel (hi.trans (hj.symm)), prev_eq := λ i j k hi hj, hi.symm.trans hj, } lemma down'_mk {α : Type*} [add_right_cancel_semigroup α] (a : α) (i j : α) (h : j + a = i) : (down' a).rel i j := h /-- The `complex_shape` appropriate for cohomology, so `d : X i ⟶ X j` only when `j = i + 1`. -/ @[simps] def up (α : Type*) [add_right_cancel_semigroup α] [has_one α] : complex_shape α := up' 1 /-- The `complex_shape` appropriate for homology, so `d : X i ⟶ X j` only when `i = j + 1`. -/ @[simps] def down (α : Type*) [add_right_cancel_semigroup α] [has_one α] : complex_shape α := down' 1 lemma down_mk {α : Type*} [add_right_cancel_semigroup α] [has_one α] (i j : α) (h : j + 1 = i) : (down α).rel i j := down'_mk (1 : α) i j h end complex_shape
7ce80f8ae289a215779d01ff577ac5aaf461c669
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/monoid_algebra_to_direct_sum.lean
b378ba69e4922551e8182ed3a3ca408f60cbfeff
[ "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
7,008
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum_graded import algebra.monoid_algebra import data.finsupp.to_dfinsupp /-! # Conversion between `add_monoid_algebra` and homogenous `direct_sum` This module provides conversions between `add_monoid_algebra` and `direct_sum`. The latter is essentially a dependent version of the former. Note that since `direct_sum.has_mul` combines indices additively, there is no equivalent to `monoid_algebra`. ## Main definitions * `add_monoid_algebra.to_direct_sum : add_monoid_algebra M ι → (⨁ i : ι, M)` * `direct_sum.to_add_monoid_algebra : (⨁ i : ι, M) → add_monoid_algebra M ι` * Bundled equiv versions of the above: * `add_monoid_algebra_equiv_direct_sum : add_monoid_algebra M ι ≃ (⨁ i : ι, M)` * `add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ (⨁ i : ι, M)` * `add_monoid_algebra_ring_equiv_direct_sum R : add_monoid_algebra M ι ≃+* (⨁ i : ι, M)` ## Theorems The defining feature of these operations is that they map `finsupp.single` to `direct_sum.of` and vice versa: * `add_monoid_algebra.to_direct_sum_single` * `direct_sum.to_add_monoid_algebra_of` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `add_monoid_algebra.to_direct_sum`: * `add_monoid_algebra_add_equiv_direct_sum_apply` * `add_monoid_algebra_lequiv_direct_sum_apply` * `add_monoid_algebra_add_equiv_direct_sum_symm_apply` * `add_monoid_algebra_lequiv_direct_sum_symm_apply` ## Implementation notes This file largely just copies the API of `data/finsupp/to_dfinsupp`, and reuses the proofs. Recall that `add_monoid_algebra M ι` is defeq to `ι →₀ M` and `⨁ i : ι, M` is defeq to `Π₀ i : ι, M`. Note that there is no `add_monoid_algebra` equivalent to `finsupp.single`, so many statements still involve this definition. -/ variables {ι : Type*} {R : Type*} {M : Type*} open_locale direct_sum /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `add_monoid_algebra` as a homogenous `direct_sum`. -/ def add_monoid_algebra.to_direct_sum [semiring M] (f : add_monoid_algebra M ι) : ⨁ i : ι, M := finsupp.to_dfinsupp f section variables [decidable_eq ι] [semiring M] @[simp] lemma add_monoid_algebra.to_direct_sum_single (i : ι) (m : M) : add_monoid_algebra.to_direct_sum (finsupp.single i m) = direct_sum.of _ i m := finsupp.to_dfinsupp_single i m variables [Π m : M, decidable (m ≠ 0)] /-- Interpret a homogenous `direct_sum` as a `add_monoid_algebra`. -/ def direct_sum.to_add_monoid_algebra (f : ⨁ i : ι, M) : add_monoid_algebra M ι := dfinsupp.to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_of (i : ι) (m : M) : (direct_sum.of _ i m : ⨁ i : ι, M).to_add_monoid_algebra = finsupp.single i m := dfinsupp.to_finsupp_single i m @[simp] lemma add_monoid_algebra.to_direct_sum_to_add_monoid_algebra (f : add_monoid_algebra M ι) : f.to_direct_sum.to_add_monoid_algebra = f := finsupp.to_dfinsupp_to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_to_direct_sum (f : ⨁ i : ι, M) : f.to_add_monoid_algebra.to_direct_sum = f := dfinsupp.to_finsupp_to_dfinsupp f end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace add_monoid_algebra @[simp] lemma to_direct_sum_zero [semiring M] : (0 : add_monoid_algebra M ι).to_direct_sum = 0 := finsupp.to_dfinsupp_zero @[simp] lemma to_direct_sum_add [semiring M] (f g : add_monoid_algebra M ι) : (f + g).to_direct_sum = f.to_direct_sum + g.to_direct_sum := finsupp.to_dfinsupp_add _ _ @[simp] lemma to_direct_sum_mul [decidable_eq ι] [add_monoid ι] [semiring M] (f g : add_monoid_algebra M ι) : (f * g).to_direct_sum = f.to_direct_sum * g.to_direct_sum := begin let to_hom : add_monoid_algebra M ι →+ (⨁ i : ι, M) := ⟨to_direct_sum, to_direct_sum_zero, to_direct_sum_add⟩, have : ⇑to_hom = to_direct_sum := rfl, rw ←this, revert f g, rw add_monoid_hom.map_mul_iff, ext xi xv yi yv : 4, dsimp only [add_monoid_hom.comp_apply, add_monoid_hom.compl₂_apply, add_monoid_hom.compr₂_apply, add_monoid_hom.mul_apply, add_equiv.coe_to_add_monoid_hom, finsupp.single_add_hom_apply], simp only [add_monoid_algebra.single_mul_single, this, add_monoid_algebra.to_direct_sum_single], rw [direct_sum.of_mul_of, semiring.direct_sum_mul], end end add_monoid_algebra namespace direct_sum variables [decidable_eq ι] @[simp] lemma to_add_monoid_algebra_zero [semiring M] [Π m : M, decidable (m ≠ 0)] : to_add_monoid_algebra 0 = (0 : add_monoid_algebra M ι) := dfinsupp.to_finsupp_zero @[simp] lemma to_add_monoid_algebra_add [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f + g).to_add_monoid_algebra = to_add_monoid_algebra f + to_add_monoid_algebra g := dfinsupp.to_finsupp_add _ _ @[simp] lemma to_add_monoid_algebra_mul [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f * g).to_add_monoid_algebra = to_add_monoid_algebra f * to_add_monoid_algebra g := begin apply_fun add_monoid_algebra.to_direct_sum, { simp }, { apply function.left_inverse.injective, apply add_monoid_algebra.to_direct_sum_to_add_monoid_algebra } end end direct_sum end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `add_monoid_algebra.to_direct_sum` and `direct_sum.to_add_monoid_algebra` together form an equiv. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, ..finsupp_equiv_dfinsupp } /-- The additive version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def add_monoid_algebra_add_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_add' := add_monoid_algebra.to_direct_sum_add, .. add_monoid_algebra_equiv_direct_sum} /-- `add_monoid_algebra` is equivalent to a homogenous direct sum. This is non-computable because `add_monoid_algebra` is noncomputable. -/ noncomputable def add_monoid_algebra_ring_equiv_direct_sum [decidable_eq ι] [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+* ⨁ i : ι, M := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_mul' := add_monoid_algebra.to_direct_sum_mul, ..(add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ ⨁ i : ι, M) } end equivs
3b57779f827b748d48d3e89994072a08908d288d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/pairwise.lean
f7d9b833b3276430e66cf676b132e6943a79a50a
[ "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
2,692
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 logic.function.basic import tactic.basic /-! # Relations holding pairwise > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/622 > Any changes to this file require a corresponding PR to mathlib4. This file defines pairwise relations. ## Main declarations * `pairwise`: `pairwise r` states that `r i j` for all `i ≠ j`. * `set.pairwise`: `s.pairwise r` states that `r i j` for all `i ≠ j` with `i, j ∈ s`. -/ open set function variables {α β γ ι ι' : Type*} {r p q : α → α → Prop} section pairwise variables {f g : ι → α} {s t u : set α} {a b : α} /-- A relation `r` holds pairwise if `r i j` for all `i ≠ j`. -/ def pairwise (r : α → α → Prop) := ∀ ⦃i j⦄, i ≠ j → r i j lemma pairwise.mono (hr : pairwise r) (h : ∀ ⦃i j⦄, r i j → p i j) : pairwise p := λ i j hij, h $ hr hij protected lemma pairwise.eq (h : pairwise r) : ¬ r a b → a = b := not_imp_comm.1 $ @h _ _ lemma function.injective_iff_pairwise_ne : injective f ↔ pairwise ((≠) on f) := forall₂_congr $ λ i j, not_imp_not.symm alias function.injective_iff_pairwise_ne ↔ function.injective.pairwise_ne _ namespace set /-- The relation `r` holds pairwise on the set `s` if `r x y` for all *distinct* `x y ∈ s`. -/ protected def pairwise (s : set α) (r : α → α → Prop) := ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → x ≠ y → r x y lemma pairwise_of_forall (s : set α) (r : α → α → Prop) (h : ∀ a b, r a b) : s.pairwise r := λ a _ b _ _, h a b lemma pairwise.imp_on (h : s.pairwise r) (hrp : s.pairwise (λ ⦃a b : α⦄, r a b → p a b)) : s.pairwise p := λ a ha b hb hab, hrp ha hb hab $ h ha hb hab lemma pairwise.imp (h : s.pairwise r) (hpq : ∀ ⦃a b : α⦄, r a b → p a b) : s.pairwise p := h.imp_on $ pairwise_of_forall s _ hpq protected lemma pairwise.eq (hs : s.pairwise r) (ha : a ∈ s) (hb : b ∈ s) (h : ¬ r a b) : a = b := of_not_not $ λ hab, h $ hs ha hb hab lemma _root_.reflexive.set_pairwise_iff (hr : reflexive r) : s.pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr $ λ a _ b _, or_iff_not_imp_left.symm.trans $ or_iff_right_of_imp $ eq.rec $ hr a lemma pairwise.on_injective (hs : s.pairwise r) (hf : function.injective f) (hfs : ∀ x, f x ∈ s) : pairwise (r on f) := λ i j hij, hs (hfs i) (hfs j) (hf.ne hij) end set lemma pairwise.set_pairwise (h : pairwise r) (s : set α) : s.pairwise r := λ x hx y hy w, h w end pairwise
4a58fd78a2b1152ea0d29bc117266c8b66dd4175
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monad/basic.lean
ea56c54e503cea3a202779f618952f8d240f2c1c
[]
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
12,894
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta, Adam Topaz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.functor_category import Mathlib.PostPort universes v₁ u₁ l namespace Mathlib namespace category_theory /-- The data of a monad on C consists of an endofunctor T together with natural transformations η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations: - T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity) - η_(TX) ≫ μ_X = 1_X (left unit) - Tη_X ≫ μ_X = 1_X (right unit) -/ class monad {C : Type u₁} [category C] (T : C ⥤ C) where η : 𝟭 ⟶ T μ : T ⋙ T ⟶ T assoc' : autoParam (∀ (X : C), functor.map T (nat_trans.app μ X) ≫ nat_trans.app μ X = nat_trans.app μ (functor.obj T X) ≫ nat_trans.app μ X) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) left_unit' : autoParam (∀ (X : C), nat_trans.app η (functor.obj T X) ≫ nat_trans.app μ X = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) right_unit' : autoParam (∀ (X : C), functor.map T (nat_trans.app η X) ≫ nat_trans.app μ X = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) theorem monad.assoc {C : Type u₁} [category C] {T : C ⥤ C} [c : monad T] (X : C) : functor.map T (nat_trans.app (monad.μ T) X) ≫ nat_trans.app (monad.μ T) X = nat_trans.app (monad.μ T) (functor.obj T X) ≫ nat_trans.app (monad.μ T) X := sorry @[simp] theorem monad.left_unit {C : Type u₁} [category C] {T : C ⥤ C} [c : monad T] (X : C) : nat_trans.app (monad.η T) (functor.obj T X) ≫ nat_trans.app (monad.μ T) X = 𝟙 := sorry @[simp] theorem monad.right_unit {C : Type u₁} [category C] {T : C ⥤ C} [c : monad T] (X : C) : functor.map T (nat_trans.app (monad.η T) X) ≫ nat_trans.app (monad.μ T) X = 𝟙 := sorry @[simp] theorem monad.right_unit_assoc {C : Type u₁} [category C] {T : C ⥤ C} [c : monad T] (X : C) {X' : C} (f' : functor.obj T X ⟶ X') : functor.map T (nat_trans.app (monad.η T) X) ≫ nat_trans.app (monad.μ T) X ≫ f' = f' := sorry notation:1024 "η_" => Mathlib.category_theory.monad.η notation:1024 "μ_" => Mathlib.category_theory.monad.μ /-- The data of a comonad on C consists of an endofunctor G together with natural transformations ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations: - δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity) - δ_X ≫ ε_(GX) = 1_X (left counit) - δ_X ≫ G ε_X = 1_X (right counit) -/ class comonad {C : Type u₁} [category C] (G : C ⥤ C) where ε : G ⟶ 𝟭 δ : G ⟶ G ⋙ G coassoc' : autoParam (∀ (X : C), nat_trans.app δ X ≫ functor.map G (nat_trans.app δ X) = nat_trans.app δ X ≫ nat_trans.app δ (functor.obj G X)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) left_counit' : autoParam (∀ (X : C), nat_trans.app δ X ≫ nat_trans.app ε (functor.obj G X) = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) right_counit' : autoParam (∀ (X : C), nat_trans.app δ X ≫ functor.map G (nat_trans.app ε X) = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) theorem comonad.coassoc {C : Type u₁} [category C] {G : C ⥤ C} [c : comonad G] (X : C) : nat_trans.app (comonad.δ G) X ≫ functor.map G (nat_trans.app (comonad.δ G) X) = nat_trans.app (comonad.δ G) X ≫ nat_trans.app (comonad.δ G) (functor.obj G X) := sorry @[simp] theorem comonad.left_counit {C : Type u₁} [category C] {G : C ⥤ C} [c : comonad G] (X : C) : nat_trans.app (comonad.δ G) X ≫ nat_trans.app (comonad.ε G) (functor.obj G X) = 𝟙 := sorry @[simp] theorem comonad.right_counit {C : Type u₁} [category C] {G : C ⥤ C} [c : comonad G] (X : C) : nat_trans.app (comonad.δ G) X ≫ functor.map G (nat_trans.app (comonad.ε G) X) = 𝟙 := sorry @[simp] theorem comonad.left_counit_assoc {C : Type u₁} [category C] {G : C ⥤ C} [c : comonad G] (X : C) {X' : C} (f' : functor.obj G X ⟶ X') : nat_trans.app (comonad.δ G) X ≫ nat_trans.app (comonad.ε G) (functor.obj G X) ≫ f' = f' := sorry notation:1024 "ε_" => Mathlib.category_theory.comonad.ε notation:1024 "δ_" => Mathlib.category_theory.comonad.δ /-- A morphisms of monads is a natural transformation compatible with η and μ. -/ structure monad_hom {C : Type u₁} [category C] (M : C ⥤ C) (N : C ⥤ C) [monad M] [monad N] extends nat_trans M N where app_η' : autoParam (∀ {X : C}, nat_trans.app η_ X ≫ nat_trans.app _to_nat_trans X = nat_trans.app η_ X) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) app_μ' : autoParam (∀ {X : C}, nat_trans.app μ_ X ≫ nat_trans.app _to_nat_trans X = (functor.map M (nat_trans.app _to_nat_trans X) ≫ nat_trans.app _to_nat_trans (functor.obj N X)) ≫ nat_trans.app μ_ X) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem monad_hom.app_η {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (c : monad_hom M N) {X : C} : nat_trans.app η_ X ≫ nat_trans.app (monad_hom.to_nat_trans c) X = nat_trans.app η_ X := sorry @[simp] theorem monad_hom.app_μ {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (c : monad_hom M N) {X : C} : nat_trans.app μ_ X ≫ nat_trans.app (monad_hom.to_nat_trans c) X = (functor.map M (nat_trans.app (monad_hom.to_nat_trans c) X) ≫ nat_trans.app (monad_hom.to_nat_trans c) (functor.obj N X)) ≫ nat_trans.app μ_ X := sorry @[simp] theorem monad_hom.app_η_assoc {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (c : monad_hom M N) {X : C} {X' : C} (f' : functor.obj N X ⟶ X') : nat_trans.app η_ X ≫ nat_trans.app (monad_hom.to_nat_trans c) X ≫ f' = nat_trans.app η_ X ≫ f' := sorry /-- A morphisms of comonads is a natural transformation compatible with η and μ. -/ structure comonad_hom {C : Type u₁} [category C] (M : C ⥤ C) (N : C ⥤ C) [comonad M] [comonad N] extends nat_trans M N where app_ε' : autoParam (∀ {X : C}, nat_trans.app _to_nat_trans X ≫ nat_trans.app ε_ X = nat_trans.app ε_ X) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) app_δ' : autoParam (∀ {X : C}, nat_trans.app _to_nat_trans X ≫ nat_trans.app δ_ X = nat_trans.app δ_ X ≫ nat_trans.app _to_nat_trans (functor.obj M X) ≫ functor.map N (nat_trans.app _to_nat_trans X)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem comonad_hom.app_ε {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (c : comonad_hom M N) {X : C} : nat_trans.app (comonad_hom.to_nat_trans c) X ≫ nat_trans.app ε_ X = nat_trans.app ε_ X := sorry @[simp] theorem comonad_hom.app_δ {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (c : comonad_hom M N) {X : C} : nat_trans.app (comonad_hom.to_nat_trans c) X ≫ nat_trans.app δ_ X = nat_trans.app δ_ X ≫ nat_trans.app (comonad_hom.to_nat_trans c) (functor.obj M X) ≫ functor.map N (nat_trans.app (comonad_hom.to_nat_trans c) X) := sorry @[simp] theorem comonad_hom.app_δ_assoc {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (c : comonad_hom M N) {X : C} {X' : C} (f' : functor.obj N (functor.obj N X) ⟶ X') : nat_trans.app (comonad_hom.to_nat_trans c) X ≫ nat_trans.app δ_ X ≫ f' = nat_trans.app δ_ X ≫ nat_trans.app (comonad_hom.to_nat_trans c) (functor.obj M X) ≫ functor.map N (nat_trans.app (comonad_hom.to_nat_trans c) X) ≫ f' := sorry namespace monad_hom theorem ext {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (f : monad_hom M N) (g : monad_hom M N) : to_nat_trans f = to_nat_trans g → f = g := sorry /-- The identity natural transformations is a morphism of monads. -/ def id {C : Type u₁} [category C] (M : C ⥤ C) [monad M] : monad_hom M M := mk (nat_trans.mk (nat_trans.app 𝟙)) protected instance inhabited {C : Type u₁} [category C] {M : C ⥤ C} [monad M] : Inhabited (monad_hom M M) := { default := id M } /-- The composition of two morphisms of monads. -/ def comp {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} {L : C ⥤ C} [monad M] [monad N] [monad L] (f : monad_hom M N) (g : monad_hom N L) : monad_hom M L := mk (nat_trans.mk fun (X : C) => nat_trans.app (to_nat_trans f) X ≫ nat_trans.app (to_nat_trans g) X) @[simp] theorem id_comp {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (f : monad_hom M N) : comp (id M) f = f := ext (comp (id M) f) f (nat_trans.ext (to_nat_trans (comp (id M) f)) (to_nat_trans f) (funext fun (x : C) => category.id_comp (nat_trans.app (to_nat_trans f) x))) @[simp] theorem comp_id {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [monad M] [monad N] (f : monad_hom M N) : comp f (id N) = f := ext (comp f (id N)) f (nat_trans.ext (to_nat_trans (comp f (id N))) (to_nat_trans f) (funext fun (x : C) => category.comp_id (nat_trans.app (to_nat_trans f) x))) /-- Note: `category_theory.monad.bundled` provides a category instance for bundled monads.-/ @[simp] theorem assoc {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} {L : C ⥤ C} {K : C ⥤ C} [monad M] [monad N] [monad L] [monad K] (f : monad_hom M N) (g : monad_hom N L) (h : monad_hom L K) : comp (comp f g) h = comp f (comp g h) := sorry end monad_hom namespace comonad_hom theorem ext {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (f : comonad_hom M N) (g : comonad_hom M N) : to_nat_trans f = to_nat_trans g → f = g := sorry /-- The identity natural transformations is a morphism of comonads. -/ def id {C : Type u₁} [category C] (M : C ⥤ C) [comonad M] : comonad_hom M M := mk (nat_trans.mk (nat_trans.app 𝟙)) protected instance inhabited {C : Type u₁} [category C] {M : C ⥤ C} [comonad M] : Inhabited (comonad_hom M M) := { default := id M } /-- The composition of two morphisms of comonads. -/ def comp {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} {L : C ⥤ C} [comonad M] [comonad N] [comonad L] (f : comonad_hom M N) (g : comonad_hom N L) : comonad_hom M L := mk (nat_trans.mk fun (X : C) => nat_trans.app (to_nat_trans f) X ≫ nat_trans.app (to_nat_trans g) X) @[simp] theorem id_comp {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (f : comonad_hom M N) : comp (id M) f = f := ext (comp (id M) f) f (nat_trans.ext (to_nat_trans (comp (id M) f)) (to_nat_trans f) (funext fun (x : C) => category.id_comp (nat_trans.app (to_nat_trans f) x))) @[simp] theorem comp_id {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} [comonad M] [comonad N] (f : comonad_hom M N) : comp f (id N) = f := ext (comp f (id N)) f (nat_trans.ext (to_nat_trans (comp f (id N))) (to_nat_trans f) (funext fun (x : C) => category.comp_id (nat_trans.app (to_nat_trans f) x))) /-- Note: `category_theory.monad.bundled` provides a category instance for bundled comonads.-/ @[simp] theorem assoc {C : Type u₁} [category C] {M : C ⥤ C} {N : C ⥤ C} {L : C ⥤ C} {K : C ⥤ C} [comonad M] [comonad N] [comonad L] [comonad K] (f : comonad_hom M N) (g : comonad_hom N L) (h : comonad_hom L K) : comp (comp f g) h = comp f (comp g h) := sorry end comonad_hom namespace monad protected instance category_theory.functor.id.monad {C : Type u₁} [category C] : monad 𝟭 := mk 𝟙 𝟙 end monad namespace comonad protected instance category_theory.functor.id.comonad {C : Type u₁} [category C] : comonad 𝟭 := mk 𝟙 𝟙
17d44bc25b5f4b8c2bba1a56be35742ae1544fa8
df561f413cfe0a88b1056655515399c546ff32a5
/7-advanced-multiplication-world/l1.lean
513b021402f454cc9ab1a7ea9617dfc4372f5648
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
211
lean
theorem mul_pos (a b : mynat) : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := begin intros aH bH abH, cases b with n, apply bH, refl, apply aH, rw mul_succ at abH, rw add_comm at abH, exact add_right_eq_zero abH, end
d6b8e23033c3af56cc0522945c5a8ddc697f4674
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/init_/data/int/basic.lean
8a1b5b01553f02def18784635819003c36d1b21d
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
1,687
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Instances, copied from the core library by Johan Commelin -/ import algebra.ring instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : zero_ne_one_class ℤ := { zero := 0, one := 1, zero_ne_one := int.zero_ne_one }
695b32558e41fea1a65d6b5565139b94f90e9d32
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/fun_like/basic.lean
f5803b8a55a700446c709a1feceb962e72863ba0
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,904
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import logic.function.basic import tactic.lint import tactic.norm_cast /-! # Typeclass for a type `F` with an injective map to `A → B` This typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`. ## Basic usage of `fun_like` A typical type of morphisms should be declared as: ``` structure my_hom (A B : Type*) [my_class A] [my_class B] := (to_fun : A → B) (map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y)) namespace my_hom variables (A B : Type*) [my_class A] [my_class B] -- This instance is optional if you follow the "morphism class" design below: instance : fun_like (my_hom A B) A (λ _, B) := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl @[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h /-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B := { to_fun := f', map_op' := h.symm ▸ f.map_op' } end my_hom ``` This file will then provide a `has_coe_to_fun` instance and various extensionality and simp lemmas. ## Morphism classes extending `fun_like` The `fun_like` design provides further benefits if you put in a bit more work. The first step is to extend `fun_like` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` section set_option old_structure_cmd true /-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms. You should extend this class when you extend `my_hom`. -/ class my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B] extends fun_like F A (λ _, B) := (map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y)) end @[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B] (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) := my_hom_class.map_op -- You can replace `my_hom.fun_like` with the below instance: instance : my_hom_class (my_hom A B) A B := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := my_hom.map_op' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` The second step is to add instances of your new `my_hom_class` for all types extending `my_hom`. Typically, you can just declare a new class analogous to `my_hom_class`: ``` structure cooler_hom (A B : Type*) [cool_class A] [cool_class B] extends my_hom A B := (map_cool' : to_fun cool_class.cool = cool_class.cool) section set_option old_structure_cmd true class cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B] extends my_hom_class F A B := (map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool) end @[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B] (f : F) : f cool_class.cool = cool_class.cool := my_hom_class.map_op -- You can also replace `my_hom.fun_like` with the below instance: instance : cool_hom_class (cool_hom A B) A B := { coe := cool_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := cool_hom.map_op', map_cool := cool_hom.map_cool' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry lemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry ``` This means anything set up for `my_hom`s will automatically work for `cool_hom_class`es, and defining `cool_hom_class` only takes a constant amount of effort, instead of linearly increasing the work per `my_hom`-related declaration. -/ -- This instance should have low priority, to ensure we follow the chain -- `fun_like → has_coe_to_fun` attribute [instance, priority 10] coe_fn_trans /-- The class `fun_like F α β` expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. This typeclass is used in the definition of the homomorphism typeclasses, such as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, .... -/ class fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) := (coe : F → Π a : α, β a) (coe_injective' : function.injective coe) section dependent /-! ### `fun_like F α β` where `β` depends on `a : α` -/ variables (F α : Sort*) (β : α → Sort*) namespace fun_like variables {F α β} [i : fun_like F α β] include i @[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous instance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe } @[simp] lemma coe_eq_coe_fn : (fun_like.coe : F → Π a : α, β a) = coe_fn := rfl theorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) := fun_like.coe_injective' @[simp, norm_cast] theorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g := ⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩ theorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g := coe_injective h theorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g := coe_injective (funext h) theorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) := coe_fn_eq.symm.trans function.funext_iff protected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x lemma ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall lemma exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h end fun_like end dependent section non_dependent /-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/ variables {F α β : Sort*} [i : fun_like F α (λ _, β)] include i namespace fun_like protected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ end fun_like end non_dependent
e3b93e1197ff0586736a89c80bb4cbeea15bb403
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/set/lattice.lean
a4c564b1fda634495efdf0a74346d60fed11a68d
[ "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
60,625
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import data.nat.basic import order.complete_boolean_algebra import order.directed import order.galois_connection /-! # The set lattice This file provides usual set notation for unions and intersections, a `complete_lattice` instance for `set α`, and some more set constructions. ## Main declarations * `set.Union`: Union of an indexed family of sets. * `set.Inter`: Intersection of an indexed family of sets. * `set.sInter`: **s**et **Inter**. Intersection of sets belonging to a set of sets. * `set.sUnion`: **s**et **Union**. Intersection of sets belonging to a set of sets. This is actually defined in core Lean. * `set.sInter_eq_bInter`, `set.sUnion_eq_bInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and `⋃₀ s = ⋃ x ∈ s, x`. * `set.complete_boolean_algebra`: `set α` is a `complete_boolean_algebra` with `≤ = ⊆`, `< = ⊂`, `⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `set.boolean_algebra`. * `set.kern_image`: For a function `f : α → β`, `s.kern_image f` is the set of `y` such that `f ⁻¹ y ⊆ s`. * `set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union of `f '' t` over all `f ∈ s`, where `t : set α` and `s : set (α → β)`. * `set.pairwise_disjoint`: `pairwise_disjoint s` states that all sets in `s` are either equal or disjoint. * `set.Union_eq_sigma_of_disjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an indexed family of disjoint sets. ## Notation * `⋃`: `set.Union` * `⋂`: `set.Inter` * `⋃₀`: `set.sUnion` * `⋂₀`: `set.sInter` -/ open function tactic set auto universes u variables {α β γ : Type*} {ι ι' ι₂ : Sort*} namespace set /-! ### Complete lattice and complete Boolean algebra instances -/ instance : has_Inf (set α) := ⟨λ s, {a | ∀ t ∈ s, a ∈ t}⟩ instance : has_Sup (set α) := ⟨sUnion⟩ /-- Intersection of a set of sets. -/ def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl /-- Indexed union of a family of sets -/ def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] lemma Sup_eq_sUnion (S : set (set α)) : Sup S = ⋃₀ S := rfl @[simp] lemma Inf_eq_sInter (S : set (set α)) : Inf S = ⋂₀ S := rfl @[simp] lemma supr_eq_Union (s : ι → set α) : supr s = Union s := rfl @[simp] lemma infi_eq_Inter (s : ι → set α) : infi s = Inter s := rfl @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨λ ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, λ ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨λ (h : ∀ a ∈ {a : set β | ∃ i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, λ h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃ t ∈ S, x ∈ t := iff.rfl instance : complete_boolean_algebra (set α) := { Sup := Sup, Inf := Inf, le_Sup := λ s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := λ s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := λ s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := λ s t t_in a h, h _ t_in, infi_sup_le_sup_Inf := λ s S x, iff.mp $ by simp [forall_or_distrib_left], inf_Sup_le_supr_inf := λ s S x, iff.mp $ by simp [exists_and_distrib_left], .. set.boolean_algebra, .. pi.complete_lattice } /-- `set.image` is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := λ s t, image_subset _ theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) := λ b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) := λ b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) := λ a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := λ a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := λ a b, ⟨ λ h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, λ h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /-! ### Union and intersection over an indexed family of sets -/ @[congr] theorem Union_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Union f₁ = Union f₂ := supr_congr_Prop pq f @[congr] theorem Inter_congr_Prop {p q : Prop} {f₁ : p → set α} {f₂ : q → set α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : Inter f₁ = Inter f₂ := infi_congr_Prop pq f lemma Union_eq_if {p : Prop} [decidable p] (s : set α) : (⋃ h : p, s) = if p then s else ∅ := supr_eq_if _ lemma Union_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋃ (h : p), s h) = if h : p then s h else ∅ := supr_eq_dif _ lemma Inter_eq_if {p : Prop} [decidable p] (s : set α) : (⋂ h : p, s) = if p then s else univ := infi_eq_if _ lemma Infi_eq_dif {p : Prop} [decidable p] (s : p → set α) : (⋂ (h : p), s h) = if h : p then s h else univ := infi_eq_dif _ lemma exists_set_mem_of_union_eq_top {ι : Type*} (t : set ι) (s : ι → set β) (w : (⋃ i ∈ t, s i) = ⊤) (x : β) : ∃ (i ∈ t), x ∈ s i := begin have p : x ∈ ⊤ := set.mem_univ x, simpa only [←w, set.mem_Union] using p, end lemma nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : set ι) (s : ι → set α) (H : nonempty α) (w : (⋃ i ∈ t, s i) = ⊤) : t.nonempty := begin obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some, exact ⟨x, m⟩, end theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ _ _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨λ h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := @le_infi (set β) _ _ _ _ h theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i := @le_infi_iff (set β) _ _ _ _ theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr /-- This rather trivial consequence of `subset_Union`is convenient with `apply`, and has `i` explicit for this purpose. -/ theorem subset_subset_Union {A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i := h.trans (subset_Union s i) theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x}) = {x : α | ∀ i, P i x} := by { ext, simp } lemma Union_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋃ x, f x) = ⋃ y, g y := supr_congr h h1 h2 lemma Inter_congr {f : ι → set α} {g : ι₂ → set α} (h : ι → ι₂) (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⋂ x, f x) = ⋂ y, g y := infi_congr h h1 h2 theorem Union_const [nonempty ι] (s : set β) : (⋃ i : ι, s) = s := supr_const theorem Inter_const [nonempty ι] (s : set β) : (⋂ i : ι, s) = s := infi_const @[simp] theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := compl_supr @[simp] theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := compl_infi -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp only [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp only [compl_Union, compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := inf_supr_eq _ _ theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := supr_inf_eq _ _ theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := supr_sup_eq theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := infi_inf_eq theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := sup_supr theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := supr_sup theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := inf_infi theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := infi_inf -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := sup_infi_eq _ _ theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {f : ι → set α} (hd : directed (⊆) f) (h : ∀ x, directed_on r (f x)) : directed_on r (⋃ x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact λ a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := by { rintro x ⟨_, ⟨i, rfl⟩, xs, xt⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨i, rfl⟩, xt⟩ } lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := begin ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩, rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, _, ⟨j, rfl⟩, xt⟩, exact ⟨_, ⟨i ⊔ j, rfl⟩, hs le_sup_left xs, ht le_sup_right xt⟩ end /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ } lemma Union_option {ι} (s : option ι → set α) : (⋃ o, s o) = s none ∪ ⋃ i, s (some i) := supr_option s lemma Inter_option {ι} (s : option ι → set α) : (⋂ o, s o) = s none ∩ ⋂ i, s (some i) := infi_option s section variables (p : ι → Prop) [decidable_pred p] lemma Union_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋃ i, if h : p i then f i h else g i h) = (⋃ i (h : p i), f i h) ∪ (⋃ i (h : ¬ p i), g i h) := supr_dite _ _ _ lemma Union_ite (f g : ι → set α) : (⋃ i, if p i then f i else g i) = (⋃ i (h : p i), f i) ∪ (⋃ i (h : ¬ p i), g i) := Union_dite _ _ _ lemma Inter_dite (f : Π i, p i → set α) (g : Π i, ¬p i → set α) : (⋂ i, if h : p i then f i h else g i h) = (⋂ i (h : p i), f i h) ∩ (⋂ i (h : ¬ p i), g i h) := infi_dite _ _ _ lemma Inter_ite (f g : ι → set α) : (⋂ i, if p i then f i else g i) = (⋂ i (h : p i), f i) ∩ (⋂ i (h : ¬ p i), g i) := Inter_dite _ _ _ end lemma image_projection_prod {ι : Type*} {α : ι → Type*} {v : Π (i : ι), set (α i)} (hv : (pi univ v).nonempty) (i : ι) : (λ (x : Π (i : ι), α i), x i) '' (⋂ k, (λ (x : Π (j : ι), α j), x k) ⁻¹' v k) = v i:= begin classical, apply subset.antisymm, { simp [Inter_subset] }, { intros y y_in, simp only [mem_image, mem_Inter, mem_preimage], rcases hv with ⟨z, hz⟩, refine ⟨function.update z i y, _, update_same i y z⟩, rw @forall_update_iff ι α _ z i y (λ i t, t ∈ v i), exact ⟨y_in, λ j hj, by simpa using hz j⟩ }, end /-! ### Unions and intersections indexed by `Prop` -/ @[simp] theorem Inter_false {s : false → set α} : Inter s = univ := infi_false @[simp] theorem Union_false {s : false → set α} : Union s = ∅ := supr_false @[simp] theorem Inter_true {s : true → set α} : Inter s = s trivial := infi_true @[simp] theorem Union_true {s : true → set α} : Union s = s trivial := supr_true @[simp] theorem Inter_exists {p : ι → Prop} {f : Exists p → set α} : (⋂ x, f x) = (⋂ i (h : p i), f ⟨i, h⟩) := infi_exists @[simp] theorem Union_exists {p : ι → Prop} {f : Exists p → set α} : (⋃ x, f x) = (⋃ i (h : p i), f ⟨i, h⟩) := supr_exists @[simp] lemma Union_empty : (⋃ i : ι, ∅ : set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂ i : ι, univ : set α) = univ := infi_top section variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] lemma Union_nonempty_index (s : set α) (t : s.nonempty → set β) : (⋃ h, t h) = ⋃ x ∈ s, t ⟨x, ‹_›⟩ := supr_exists end @[simp] theorem Inter_Inter_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋂ x (h : x = b), s x h) = s b rfl := infi_infi_eq_left @[simp] theorem Inter_Inter_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋂ x (h : b = x), s x h) = s b rfl := infi_infi_eq_right @[simp] theorem Union_Union_eq_left {b : β} {s : Π x : β, x = b → set α} : (⋃ x (h : x = b), s x h) = s b rfl := supr_supr_eq_left @[simp] theorem Union_Union_eq_right {b : β} {s : Π x : β, b = x → set α} : (⋃ x (h : b = x), s x h) = s b rfl := supr_supr_eq_right theorem Inter_or {p q : Prop} (s : p ∨ q → set α) : (⋂ h, s h) = (⋂ h : p, s (or.inl h)) ∩ (⋂ h : q, s (or.inr h)) := infi_or theorem Union_or {p q : Prop} (s : p ∨ q → set α) : (⋃ h, s h) = (⋃ i, s (or.inl i)) ∪ (⋃ j, s (or.inr j)) := supr_or theorem Union_and {p q : Prop} (s : p ∧ q → set α) : (⋃ h, s h) = ⋃ hp hq, s ⟨hp, hq⟩ := supr_and theorem Inter_and {p q : Prop} (s : p ∧ q → set α) : (⋂ h, s h) = ⋂ hp hq, s ⟨hp, hq⟩ := infi_and theorem Union_comm (s : ι → ι' → set α) : (⋃ i i', s i i') = ⋃ i' i, s i i' := supr_comm theorem Inter_comm (s : ι → ι' → set α) : (⋂ i i', s i i') = ⋂ i' i, s i i' := infi_comm @[simp] theorem bUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Union_and, @Union_comm _ ι'] @[simp] theorem bUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Union_and, @Union_comm _ ι] @[simp] theorem bInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : Π x y, p x ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h) = ⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [Inter_and, @Inter_comm _ ι'] @[simp] theorem bInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : Π x y, p y ∧ q x y → set α) : (⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h) = ⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [Inter_and, @Inter_comm _ ι] @[simp] theorem Union_Union_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋃ x h, s x h) = s b (or.inl rfl) ∪ ⋃ x (h : p x), s x (or.inr h) := by simp only [Union_or, Union_union_distrib, Union_Union_eq_left] @[simp] theorem Inter_Inter_eq_or_left {b : β} {p : β → Prop} {s : Π x : β, (x = b ∨ p x) → set α} : (⋂ x h, s x h) = s b (or.inl rfl) ∩ ⋂ x (h : p x), s x (or.inr h) := by simp only [Inter_or, Inter_inter_distrib, Inter_Inter_eq_left] /-! ### Bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp lemma mem_bUnion_iff' {p : α → Prop} {t : α → set β} {y : β} : y ∈ (⋃ i (h : p i), t i) ↔ ∃ i (h : p i), y ∈ t i := mem_bUnion_iff theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := mem_bUnion_iff.2 ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := mem_bInter_iff.2 h theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := Union_subset $ λ x, Union_subset (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ λ x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅ x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β} (h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) : (⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) := begin simp only [Union_subset_iff], rintros a a_in x ha, rcases h a a_in with ⟨c, c_in, hc⟩, exact mem_bUnion c_in (hc ha) end theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := begin intros x x_in, simp only [mem_Inter] at *, exact λ a a_in, h a a_in $ x_in _ (hs a_in) end theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) := bInter_mono' (subset.refl s) h theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) := bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩) theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ @[simp] lemma bUnion_self (s : set α) : (⋃ x ∈ s, s) = s := subset.antisymm (bUnion_subset $ λ x hx, subset.refl s) (λ x hx, mem_bUnion hx hx) @[simp] lemma Union_nonempty_self (s : set α) : (⋃ h : s.nonempty, s) = s := by rw [Union_nonempty_index, bUnion_self] -- TODO(Jeremy): here is an artifact of the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := infi_singleton theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := by simp -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by rw [bInter_insert, bInter_singleton] lemma bInter_inter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, f i ∩ t) = (⋂ i ∈ s, f i) ∩ t := begin haveI : nonempty s := hs.to_subtype, simp [bInter_eq_Inter, ← Inter_inter] end lemma inter_bInter {ι α : Type*} {s : set ι} (hs : s.nonempty) (f : ι → set α) (t : set α) : (⋂ i ∈ s, t ∩ f i) = t ∩ ⋂ i ∈ s, f i := begin rw [inter_comm, ← bInter_inter hs], simp [inter_comm] end theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma Union_subtype {α β : Type*} (s : set α) (f : α → set β) : (⋃ (i : s), f i) = ⋃ (i ∈ s), f i := (set.bUnion_eq_Union s $ λ x _, f x).symm -- TODO(Jeremy): once again, simp doesn't do it alone. theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := by simp theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) := by simp theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) := by simp theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := by simp only [inter_Union] theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp only [@inter_comm _ _ u, inter_bUnion] theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ht, hx⟩ -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t := ⟨λ h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma Union_eq_univ_iff {f : ι → set α} : (⋃ i, f i) = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_Union] lemma bUnion_eq_univ_iff {f : α → set β} {s : set α} : (⋃ x ∈ s, f x) = univ ↔ ∀ y, ∃ x ∈ s, y ∈ f x := by simp only [Union_eq_univ_iff, mem_Union] lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] -- classical lemma sInter_eq_empty_iff {c : set (set α)} : ⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b := by simp [set.eq_empty_iff_forall_not_mem, mem_sInter] -- classical @[simp] theorem sInter_nonempty_iff {c : set (set α)}: (⋂₀ c).nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b := by simp [← ne_empty_iff_nonempty, sInter_eq_empty_iff] -- classical theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintro ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ λ t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋃ i, s i) ⊆ (⋃ i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {s : ι → set α} {t : ι₂ → set α} (h : ∀ i, ∃ j, s i ⊆ t j) : (⋃ i, s i) ⊆ (⋃ i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {s : set α} (h : ι → ι₂) : (⋃ i : ι, s) ⊆ (⋃ j : ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type*) : (⋃ x, {x} : set α) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, rfl⟩ @[simp] lemma Union_of_singleton_coe (s : set α) : (⋃ (i : s), {i} : set α) = s := by simp theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := sup_eq_supr s₁ s₂ lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := inf_eq_infi s₁ s₂ lemma sInter_union_sInter {S T : set (set α)} : (⋂₀ S) ∪ (⋂₀ T) = (⋂ p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀ s) ∩ (⋃₀ t) = (⋃ p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup lemma bUnion_Union (s : ι → set α) (t : α → set β) : (⋃ x ∈ ⋃ i, s i, t x) = ⋃ i (x ∈ s i), t x := by simp [@Union_comm _ ι] /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/ lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀ s ∈ S, s = ⋂₀ T s ‹s ∈ S›) : ⋂₀ (⋃ s ∈ S, T s ‹_›) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { rintro H s sS, rw [hT s sS, mem_sInter], exact λ t, H t s sS }, { rintro H t s sS tTs, suffices : s ⊆ t, exact this (H s sS), rw [hT s sS, sInter_eq_bInter], exact bInter_subset_of_mem tTs } end /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/ lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀ s ∈ S, s = ⋃₀ T s ‹_›) : ⋃₀ (⋃ s ∈ S, T s ‹_›) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintro ⟨t, ⟨s, sS, tTs⟩, xt⟩, refine ⟨s, sS, _⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintro ⟨s, sS, xs⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨s, sS, tTs⟩, xt⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀ (s : C), β → s} (hf : ∀ (s : C), surjective (f s)) : (⋃ (y : β), range (λ (s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, _⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀ (x : ι), β → C x} (hf : ∀ (x : ι), surjective (f x)) : (⋃ (y : β), range (λ (x : ι), (f x y).val)) = ⋃ x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, i, rfl⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, exact ⟨y, i, congr_arg subtype.val hy⟩ } end lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := infi_sup_eq _ _ lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := sup_infi_eq _ _ lemma union_distrib_bInter_left {ι : Type*} (s : ι → set α) (u : set ι) (t : set α) : t ∪ (⋂ i ∈ u, s i) = ⋂ i ∈ u, t ∪ s i := by rw [bInter_eq_Inter, bInter_eq_Inter, union_distrib_Inter_left] lemma union_distrib_bInter_right {ι : Type*} (s : ι → set α) (u : set ι) (t : set α) : (⋂ i ∈ u, s i) ∪ t = ⋂ i ∈ u, s i ∪ t := by rw [bInter_eq_Inter, bInter_eq_Inter, union_distrib_Inter_right] section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) t) : maps_to f (⋃ i hi, s i hi) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f s (t i hi)) : maps_to f s (⋂ i hi, t i hi) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) : f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) := (maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_bInter_subset } /-! ### `inj_on` -/ lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩, suffices : x (default ι) = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f s (t i hi)) : surj_on f s (⋃ i hi, t i hi) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) : surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function /-! ### `image`, `preimage` -/ section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃ i, f '' s i) := begin ext1 x, simp [image, ← exists_and_distrib_right, @exists_swap α] end lemma image_bUnion {f : α → β} {s : ι → set α} {p : ι → Prop} : f '' (⋃ i (hi : p i), s i) = (⋃ i (hi : p i), f '' s i) := by simp only [image_Union] lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃ x (h : p x), {⟨x, h⟩}) := set.ext $ λ ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃ i, {f i}) := set.ext $ λ a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃ i ∈ s, {f i}) := set.ext $ λ b, by simp [@eq_comm β b] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃ x ∈ range f, g x) = (⋃ y, g (f y)) := supr_range @[simp] lemma Union_Union_eq' {f : ι → α} {g : α → set β} : (⋃ x y (h : f y = x), g x) = ⋃ y, g (f y) := by simpa using bUnion_range lemma bInter_range {f : ι → α} {g : α → set β} : (⋂ x ∈ range f, g x) = (⋂ y, g (f y)) := infi_range @[simp] lemma Inter_Inter_eq' {f : ι → α} {g : α → set β} : (⋂ x y (h : f y = x), g x) = ⋂ y, g (f y) := by simpa using bInter_range variables {s : set γ} {f : γ → α} {g : α → set β} lemma bUnion_image : (⋃ x ∈ f '' s, g x) = (⋃ y ∈ s, g (f y)) := supr_image lemma bInter_image : (⋂ x ∈ f '' s, g x) = (⋂ y ∈ s, g (f y)) := infi_image end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := λ a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort*} {f : α → β} {s : ι → set β} : f ⁻¹' (⋃ i, s i) = (⋃ i, f ⁻¹' s i) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : f ⁻¹' (⋃ i ∈ s, t i) = (⋃ i ∈ s, f ⁻¹' (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃ t ∈ s, f ⁻¹' t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i ∈ t, s i) = (⋂ i ∈ t, f ⁻¹' s i) := by ext; simp @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_bUnion, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by rw [bUnion_preimage_singleton, preimage_range] end preimage section prod theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λ x, (f x).prod (g x)) := λ a b h, prod_mono (hf h) (hg h) alias monotone_prod ← monotone.set_prod lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) := by { ext, simp } lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} : s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] } lemma Union_prod_const {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t := by { ext, simp } lemma bUnion_prod_const {ι} {u : set ι} {s : ι → set α} {t : set β} : (⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t := by simp_rw [Union_prod_const] lemma sUnion_prod_const {C : set (set α)} {t : set β} : (⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, bUnion_prod_const, bUnion_image] } lemma Union_prod {ι α β} (s : ι → set α) (t : ι → set β) : (⋃ (x : ι × ι), (s x.1).prod (t x.2)) = (⋃ (i : ι), s i).prod (⋃ (i : ι), t i) := by { ext, simp } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, x, hw⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end end prod section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintro ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } lemma image2_Union_left (s : ι → set α) (t : set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, Union_prod_const, image_Union] lemma image2_Union_right (s : set α) (t : ι → set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_Union, image_Union] end image2 section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃ f ∈ s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u) := iff.intro (λ h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (λ h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := λ b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λ f : α → β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (λ c, iff.intro _ _), { rintro ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintro ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintro ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintro ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λ b a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq /-! ### `set` as a monad -/ instance : monad set := { pure := λ (α : Type u) a, {a}, bind := λ (α β : Type u) s f, ⋃ i ∈ s, f i, seq := λ (α β : Type u), set.seq, map := λ (α β : Type u), set.image } section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃ i ∈ s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad instance : is_lawful_monad set := { pure_bind := λ α β x f, by simp, bind_assoc := λ α β γ s f g, set.ext $ λ a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := λ α, id_map, bind_pure_comp_eq_map := λ α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := λ α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ λ α β s t, prod_image_seq_comm s t ⟩ section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Π a, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma univ_pi_eq_Inter (t : Π i, set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, Inter_true, mem_univ] lemma pi_diff_pi_subset (i : set α) (s t : Π a, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end lemma Union_univ_pi (t : Π i, ι → set (π i)) : (⋃ (x : α → ι), pi univ (λ i, t i (x i))) = pi univ (λ i, ⋃ (j : ι), t i j) := by { ext, simp [classical.skolem] } end pi end set namespace function namespace surjective lemma Union_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋃ x, g (f x)) = ⋃ y, g y := hf.supr_comp g lemma Inter_comp {f : ι → ι₂} (hf : surjective f) (g : ι₂ → set α) : (⋂ x, g (f x)) = ⋂ y, g y := hf.infi_comp g end surjective end function /-! ### Disjoint sets We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ section disjoint variables {s t u : set α} namespace disjoint theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t := inf_left _ h lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t := inf_left' _ h lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) := inf_right _ h lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) := inf_right' _ h lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx end disjoint namespace set protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] theorem disjoint_Union_left {ι : Sort*} {s : ι → set α} : disjoint (⋃ i, s i) t ↔ ∀ i, disjoint (s i) t := supr_disjoint_iff @[simp] theorem disjoint_Union_right {ι : Sort*} {s : ι → set α} : disjoint t (⋃ i, s i) ↔ ∀ i, disjoint t (s i) := disjoint_supr_iff theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α} : disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) : pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) := λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂) lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ := ⟨preimage_eq_empty, λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩ lemma disjoint_iff_subset_compl_right : disjoint s t ↔ s ⊆ tᶜ := disjoint_left lemma disjoint_iff_subset_compl_left : disjoint s t ↔ t ⊆ sᶜ := disjoint_right end set end disjoint namespace set /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀ (x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end -- classical lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σ i, t i) : (⋃ i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃ a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, b, hb⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, b₁, h₁⟩ ⟨a₂, b₂, h₂⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ λ ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀ i j, i ≠ j → disjoint (t i) (t j)) : (⋃ i, t i) ≃ (Σ i, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃ i ∈ s, t i) ≃ (Σ i : s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ λ ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ λ eq, ne $ subtype.eq eq end set
35db84dafafd4c7f00d9cba6b126b2ec40e1f4c6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/uniform_field.lean
f8a53e5876f01560eb5f8d24360fd593ef6cfb0c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,918
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.uniform_ring import topology.algebra.field import field_theory.subfield /-! # Completion of topological fields The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 : The completion `hat K` of a Hausdorff topological field is a field if the image under the mapping `x ↦ x⁻¹` of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at `0` is a Cauchy filter (with respect to the additive uniform structure). Bourbaki does not give any detail here, he refers to the general discussion of extending functions defined on a dense subset with values in a complete Hausdorff space. In particular the subtlety about clustering at zero is totally left to readers. Note that the separated completion of a non-separated topological field is the zero ring, hence the separation assumption is needed. Indeed the kernel of the completion map is the closure of zero which is an ideal. Hence it's either zero (and the field is separated) or the full field, which implies one is sent to zero and the completion ring is trivial. The main definition is `completable_top_field` which packages the assumptions as a Prop-valued type class and the main results are the instances `uniform_space.completion.field` and `uniform_space.completion.topological_division_ring`. -/ noncomputable theory open_locale classical uniformity topological_space open set uniform_space uniform_space.completion filter variables (K : Type*) [field K] [uniform_space K] local notation `hat` := completion /-- A topological field is completable if it is separated and the image under the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at 0 is a Cauchy filter (with respect to the additive uniform structure). This ensures the completion is a field. -/ class completable_top_field extends separated_space K : Prop := (nice : ∀ F : filter K, cauchy F → 𝓝 0 ⊓ F = ⊥ → cauchy (map (λ x, x⁻¹) F)) namespace uniform_space namespace completion @[priority 100] instance [separated_space K] : nontrivial (hat K) := ⟨⟨0, 1, λ h, zero_ne_one $ (uniform_embedding_coe K).inj h⟩⟩ variables {K} /-- extension of inversion to the completion of a field. -/ def hat_inv : hat K → hat K := dense_inducing_coe.extend (λ x : K, (coe x⁻¹ : hat K)) lemma continuous_hat_inv [completable_top_field K] {x : hat K} (h : x ≠ 0) : continuous_at hat_inv x := begin haveI : t3_space (hat K) := completion.t3_space K, refine dense_inducing_coe.continuous_at_extend _, apply mem_of_superset (compl_singleton_mem_nhds h), intros y y_ne, rw mem_compl_singleton_iff at y_ne, apply complete_space.complete, rw ← filter.map_map, apply cauchy.map _ (completion.uniform_continuous_coe K), apply completable_top_field.nice, { haveI := dense_inducing_coe.comap_nhds_ne_bot y, apply cauchy_nhds.comap, { rw completion.comap_coe_eq_uniformity, exact le_rfl } }, { have eq_bot : 𝓝 (0 : hat K) ⊓ 𝓝 y = ⊥, { by_contradiction h, exact y_ne (eq_of_nhds_ne_bot $ ne_bot_iff.mpr h).symm }, erw [dense_inducing_coe.nhds_eq_comap (0 : K), ← filter.comap_inf, eq_bot], exact comap_bot }, end /- The value of `hat_inv` at zero is not really specified, although it's probably zero. Here we explicitly enforce the `inv_zero` axiom. -/ instance : has_inv (hat K) := ⟨λ x, if x = 0 then 0 else hat_inv x⟩ variables [topological_division_ring K] lemma hat_inv_extends {x : K} (h : x ≠ 0) : hat_inv (x : hat K) = coe (x⁻¹ : K) := dense_inducing_coe.extend_eq_at ((continuous_coe K).continuous_at.comp (continuous_at_inv₀ h)) variables [completable_top_field K] @[norm_cast] lemma coe_inv (x : K) : (x : hat K)⁻¹ = ((x⁻¹ : K) : hat K) := begin by_cases h : x = 0, { rw [h, inv_zero], dsimp [has_inv.inv], norm_cast, simp }, { conv_lhs { dsimp [has_inv.inv] }, rw if_neg, { exact hat_inv_extends h }, { exact λ H, h (dense_embedding_coe.inj H) } } end variables [uniform_add_group K] lemma mul_hat_inv_cancel {x : hat K} (x_ne : x ≠ 0) : x*hat_inv x = 1 := begin haveI : t1_space (hat K) := t2_space.t1_space, let f := λ x : hat K, x*hat_inv x, let c := (coe : K → hat K), change f x = 1, have cont : continuous_at f x, { letI : topological_space (hat K × hat K) := prod.topological_space, have : continuous_at (λ y : hat K, ((y, hat_inv y) : hat K × hat K)) x, from continuous_id.continuous_at.prod (continuous_hat_inv x_ne), exact (_root_.continuous_mul.continuous_at.comp this : _) }, have clo : x ∈ closure (c '' {0}ᶜ), { have := dense_inducing_coe.dense x, rw [← image_univ, show (univ : set K) = {0} ∪ {0}ᶜ, from (union_compl_self _).symm, image_union] at this, apply mem_closure_of_mem_closure_union this, rw image_singleton, exact compl_singleton_mem_nhds x_ne }, have fxclo : f x ∈ closure (f '' (c '' {0}ᶜ)) := mem_closure_image cont clo, have : f '' (c '' {0}ᶜ) ⊆ {1}, { rw image_image, rintros _ ⟨z, z_ne, rfl⟩, rw mem_singleton_iff, rw mem_compl_singleton_iff at z_ne, dsimp [c, f], rw hat_inv_extends z_ne, norm_cast, rw mul_inv_cancel z_ne, }, replace fxclo := closure_mono this fxclo, rwa [closure_singleton, mem_singleton_iff] at fxclo end instance : field (hat K) := { exists_pair_ne := ⟨0, 1, λ h, zero_ne_one ((uniform_embedding_coe K).inj h)⟩, mul_inv_cancel := λ x x_ne, by { dsimp [has_inv.inv], simp [if_neg x_ne, mul_hat_inv_cancel x_ne], }, inv_zero := show ((0 : K) : hat K)⁻¹ = ((0 : K) : hat K), by rw [coe_inv, inv_zero], ..completion.has_inv, ..(by apply_instance : comm_ring (hat K)) } instance : topological_division_ring (hat K) := { continuous_at_inv₀ := begin intros x x_ne, have : {y | hat_inv y = y⁻¹ } ∈ 𝓝 x, { have : {(0 : hat K)}ᶜ ⊆ {y : hat K | hat_inv y = y⁻¹ }, { intros y y_ne, rw mem_compl_singleton_iff at y_ne, dsimp [has_inv.inv], rw if_neg y_ne }, exact mem_of_superset (compl_singleton_mem_nhds x_ne) this }, exact continuous_at.congr (continuous_hat_inv x_ne) this end, ..completion.top_ring_compl } end completion end uniform_space variables (L : Type*) [field L] [uniform_space L] [completable_top_field L] instance subfield.completable_top_field (K : subfield L) : completable_top_field K := { nice := begin intros F F_cau inf_F, let i : K →+* L := K.subtype, have hi : uniform_inducing i, from uniform_embedding_subtype_coe.to_uniform_inducing, rw ← hi.cauchy_map_iff at F_cau ⊢, rw [map_comm (show (i ∘ λ x, x⁻¹) = (λ x, x⁻¹) ∘ i, by {ext, refl})], apply completable_top_field.nice _ F_cau, rw [← filter.push_pull', ← map_zero i, ← hi.inducing.nhds_eq_comap, inf_F, filter.map_bot] end, ..subtype.separated_space (K : set L) } @[priority 100] instance completable_top_field_of_complete (L : Type*) [field L] [uniform_space L] [topological_division_ring L] [separated_space L] [complete_space L] : completable_top_field L := { nice := λ F cau_F hF, begin haveI : ne_bot F := cau_F.1, rcases complete_space.complete cau_F with ⟨x, hx⟩, have hx' : x ≠ 0, { rintro rfl, rw inf_eq_right.mpr hx at hF, exact cau_F.1.ne hF }, exact filter.tendsto.cauchy_map (calc map (λ x, x⁻¹) F ≤ map (λ x, x⁻¹) (𝓝 x) : map_mono hx ... ≤ 𝓝 (x⁻¹) : continuous_at_inv₀ hx') end, ..‹separated_space L›}
40ebd6e2a4354ce4ffa16c1befefd1a5c08b0d78
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Util/Path.lean
e01f16a26321b71e4eff19b909b2322770008144
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,977
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 Management of the Lean search path (`LEAN_PATH`), which is a list of `pkg=path` mappings from package name to root path. An import `A.B.C` given an `A=path` entry resolves to `path/B/C.olean`, and just `A` to `path.olean` (meaning that `path` should probably end with `/A`). -/ prelude import Init.System.IO import Init.System.FilePath import Init.Data.Array import Init.Data.List.Control import Init.Data.HashMap import Init.Data.Nat.Control import Init.Lean.Data.Name namespace Lean open System.FilePath (pathSeparator extSeparator) private def pathSep : String := toString pathSeparator def realPathNormalized (fname : String) : IO String := do fname ← IO.realPath fname; pure (System.FilePath.normalizePath fname) abbrev SearchPath := HashMap String String def mkSearchPathRef : IO (IO.Ref SearchPath) := IO.mkRef ∅ @[init mkSearchPathRef] constant searchPathRef : IO.Ref SearchPath := arbitrary _ def parseSearchPath (path : String) (sp : SearchPath := ∅) : IO SearchPath := do let ps := System.FilePath.splitSearchPath path; sp ← ps.foldlM (fun (sp : SearchPath) s => match s.splitOn "=" with | [pkg, path] => pure $ sp.insert pkg path | _ => throw $ IO.userError $ "ill-formed search path entry '" ++ s ++ "', should be of form 'pkg=path'") sp; pure sp def getBuiltinSearchPath : IO SearchPath := do appDir ← IO.appDir; let map := HashMap.empty; let map := map.insert "Init" $ appDir ++ pathSep ++ ".." ++ pathSep ++ "lib" ++ pathSep ++ "lean" ++ pathSep ++ "Init"; let map := map.insert "Std" $ appDir ++ pathSep ++ ".." ++ pathSep ++ "lib" ++ pathSep ++ "lean" ++ pathSep ++ "Std"; pure map def addSearchPathFromEnv (sp : SearchPath) : IO SearchPath := do val ← IO.getEnv "LEAN_PATH"; match val with | none => pure sp | some val => parseSearchPath val sp @[export lean_init_search_path] def initSearchPath (path : Option String := "") : IO Unit := match path with | some path => parseSearchPath path >>= searchPathRef.set | none => do sp ← getBuiltinSearchPath; sp ← addSearchPathFromEnv sp; searchPathRef.set sp def modPathToFilePath : Name → String | Name.str p h _ => modPathToFilePath p ++ pathSep ++ h | Name.anonymous => "" | Name.num p _ _ => panic! "ill-formed import" /- Given `A.B.C, return ("A", `B.C). -/ def splitAtRoot : Name → String × Name | Name.str Name.anonymous s _ => (s, Name.anonymous) | Name.str n s _ => let (pkg, path) := splitAtRoot n; (pkg, mkNameStr path s) | _ => panic! "ill-formed import" def findOLean (mod : Name) : IO String := do sp ← searchPathRef.get; let (pkg, path) := splitAtRoot mod; some root ← pure $ sp.find? pkg | throw $ IO.userError $ "unknown package '" ++ pkg ++ "'"; let fname := root ++ modPathToFilePath path ++ ".olean"; pure fname /-- Infer module name of source file name, assuming that `lean` is called from the package source root. -/ @[export lean_module_name_of_file] def moduleNameOfFileName (fname : String) : IO Name := do fname ← realPathNormalized fname; root ← IO.currentDir >>= realPathNormalized; when (!root.isPrefixOf fname) $ throw $ IO.userError $ "input file '" ++ fname ++ "' must be contained in current directory (" ++ root ++ ")"; let fnameSuffix := fname.drop root.length; let fnameSuffix := if fnameSuffix.get 0 == pathSeparator then fnameSuffix.drop 1 else fnameSuffix; some extPos ← pure (fnameSuffix.revPosOf '.') | throw (IO.userError ("failed to convert file name '" ++ fname ++ "' to module name, extension is missing")); let modNameStr := fnameSuffix.extract 0 extPos; let extStr := fnameSuffix.extract (extPos + 1) fnameSuffix.bsize; let parts := modNameStr.splitOn pathSep; let modName := parts.foldl mkNameStr Name.anonymous; pure modName end Lean
c16ab08116d584b7d14397c59f8c0a6123f7b175
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/apply.lean
228e02f27fce0d70ef44c01e04e408b9d38acc4f
[ "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,556
lean
import tactic.apply import topology.instances.real -- algebra.pi_instances example : ∀ n m : ℕ, n + m = m + n := begin apply' nat.rec, -- refine nat.rec _ _, { intro m, ring }, { intros n h m, ring, }, end instance : partial_order unit := { le := λ _ _, ∀ (x : ℕ), x = x, lt := λ _ _, false, le_refl := λ _ _, rfl, le_trans := λ _ _ _ _ _ _, rfl, lt_iff_le_not_le := λ _ _, by simp, le_antisymm := λ ⟨⟩ ⟨⟩ _ _, rfl } example : unit.star ≤ unit.star := begin have u : unit := unit.star, apply' le_trans, -- refine le_trans _ _, -- exact unit.star, do { gs ← tactic.get_goals, guard (gs.length = 3) }, change () ≤ u, all_goals { cases u, refl', } , -- refine le_rfl, refine le_rfl, end example {α β : Type*} [partial_order β] (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin transitivity', do { gs ← tactic.get_goals, guard (gs.length = 2) }, exact h₀, exact h₁, end example : continuous (λ (x : ℝ), x + x) := begin apply' continuous.add, guard_target' continuous (λ (x : ℝ), x), apply @continuous_id ℝ _, guard_target' continuous (λ (x : ℝ), x), apply @continuous_id ℝ _, -- guard_target' has_continuous_add ℝ, admit, end example (y : ℝ) : continuous (λ (x : ℝ), x + y) := begin apply' continuous.add, guard_target' continuous (λ (x : ℝ), x), apply @continuous_id ℝ _, guard_target' continuous (λ (x : ℝ), y), apply @continuous_const ℝ _ _, -- guard_target' has_continuous_add ℝ, admit, end
dd2c4d7bd30a6f0b16dae8703846c7bfe9f4860b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/order.lean
2f404c709d4427981096b5b569eb7734113e4e26
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,348
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Aaron Anderson -/ import data.finsupp.defs /-! # Pointwise order on finitely supported functions This file lifts order structures on `α` to `ι →₀ α`. ## Main declarations * `finsupp.order_embedding_to_fun`: The order embedding from finitely supported functions to functions. * `finsupp.order_iso_multiset`: The order isomorphism between `ℕ`-valued finitely supported functions and multisets. -/ noncomputable theory open_locale classical big_operators open finset variables {ι α : Type*} namespace finsupp /-! ### Order structures -/ section has_zero variables [has_zero α] section has_le variables [has_le α] instance : has_le (ι →₀ α) := ⟨λ f g, ∀ i, f i ≤ g i⟩ lemma le_def {f g : ι →₀ α} : f ≤ g ↔ ∀ i, f i ≤ g i := iff.rfl /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun : (ι →₀ α) ↪o (ι → α) := { to_fun := λ f, f, inj' := λ f g h, finsupp.ext $ λ i, by { dsimp at h, rw h }, map_rel_iff' := λ a b, (@le_def _ _ _ _ a b).symm } @[simp] lemma order_embedding_to_fun_apply {f : ι →₀ α} {i : ι} : order_embedding_to_fun f i = f i := rfl end has_le section preorder variables [preorder α] instance : preorder (ι →₀ α) := { le_refl := λ f i, le_rfl, le_trans := λ f g h hfg hgh i, (hfg i).trans (hgh i), .. finsupp.has_le } lemma monotone_to_fun : monotone (finsupp.to_fun : (ι →₀ α) → (ι → α)) := λ f g h a, le_def.1 h a end preorder instance [partial_order α] : partial_order (ι →₀ α) := { le_antisymm := λ f g hfg hgf, ext $ λ i, (hfg i).antisymm (hgf i), .. finsupp.preorder } instance [semilattice_inf α] : semilattice_inf (ι →₀ α) := { inf := zip_with (⊓) inf_idem, inf_le_left := λ f g i, inf_le_left, inf_le_right := λ f g i, inf_le_right, le_inf := λ f g i h1 h2 s, le_inf (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma inf_apply [semilattice_inf α] {i : ι} {f g : ι →₀ α} : (f ⊓ g) i = f i ⊓ g i := rfl instance [semilattice_sup α] : semilattice_sup (ι →₀ α) := { sup := zip_with (⊔) sup_idem, le_sup_left := λ f g i, le_sup_left, le_sup_right := λ f g i, le_sup_right, sup_le := λ f g h hf hg i, sup_le (hf i) (hg i), ..finsupp.partial_order } @[simp] lemma sup_apply [semilattice_sup α] {i : ι} {f g : ι →₀ α} : (f ⊔ g) i = f i ⊔ g i := rfl instance lattice [lattice α] : lattice (ι →₀ α) := { .. finsupp.semilattice_inf, .. finsupp.semilattice_sup } end has_zero /-! ### Algebraic order structures -/ instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (ι →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), .. finsupp.add_comm_monoid, .. finsupp.partial_order } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid (ι →₀ α) := { le_of_add_le_add_left := λ f g i h s, le_of_add_le_add_left (h s), .. finsupp.ordered_add_comm_monoid } instance [ordered_add_comm_monoid α] [contravariant_class α α (+) (≤)] : contravariant_class (ι →₀ α) (ι →₀ α) (+) (≤) := ⟨λ f g h H x, le_of_add_le_add_left $ H x⟩ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] instance : order_bot (ι →₀ α) := { bot := 0, bot_le := by simp only [le_def, coe_zero, pi.zero_apply, implies_true_iff, zero_le]} protected lemma bot_eq_zero : (⊥ : ι →₀ α) = 0 := rfl @[simp] lemma add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := by simp [ext_iff, forall_and_distrib] lemma le_iff' (f g : ι →₀ α) {s : finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s (hf H) else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ lemma le_iff (f g : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i := le_iff' f g $ subset.refl _ instance decidable_le [decidable_rel (@has_le.le α _)] : decidable_rel (@has_le.le (ι →₀ α) _) := λ f g, decidable_of_iff _ (le_iff f g).symm @[simp] lemma single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i := (le_iff' _ _ support_single_subset).trans $ by simp variables [has_sub α] [has_ordered_sub α] {f g : ι →₀ α} {i : ι} {a b : α} /-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an additive group. -/ instance tsub : has_sub (ι →₀ α) := ⟨zip_with (λ m n, m - n) (tsub_self 0)⟩ instance : has_ordered_sub (ι →₀ α) := ⟨λ n m k, forall_congr $ λ x, tsub_le_iff_right⟩ instance : canonically_ordered_add_monoid (ι →₀ α) := { exists_add_of_le := λ f g h, ⟨g - f, ext $ λ x, (add_tsub_cancel_of_le $ h x).symm⟩, le_self_add := λ f g x, le_self_add, .. finsupp.order_bot, .. finsupp.ordered_add_comm_monoid } @[simp] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl lemma tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a := rfl @[simp] lemma single_tsub : single i (a - b) = single i a - single i b := begin ext j, obtain rfl | h := eq_or_ne i j, { rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self] } end lemma support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.support := by simp only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff, ne.def, coe_tsub, pi.sub_apply, not_imp_not, zero_le, implies_true_iff] {contextual := tt} lemma subset_support_tsub {f1 f2 : ι →₀ α} : f1.support \ f2.support ⊆ (f1 - f2).support := by simp [subset_iff] {contextual := tt} end canonically_ordered_add_monoid section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] @[simp] lemma support_inf [decidable_eq ι] (f g : ι →₀ α) : (f ⊓ g).support = f.support ∩ g.support := begin ext, simp only [inf_apply, mem_support_iff, ne.def, finset.mem_union, finset.mem_filter, finset.mem_inter], simp only [inf_eq_min, ←nonpos_iff_eq_zero, min_le_iff, not_or_distrib], end @[simp] lemma support_sup [decidable_eq ι] (f g : ι →₀ α) : (f ⊔ g).support = f.support ∪ g.support := begin ext, simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ←bot_eq_zero], rw [_root_.sup_eq_bot_iff, not_and_distrib], end lemma disjoint_iff {f g : ι →₀ α} : disjoint f g ↔ disjoint f.support g.support := begin rw [disjoint_iff, disjoint_iff, finsupp.bot_eq_zero, ← finsupp.support_eq_empty, finsupp.support_inf], refl, end end canonically_linear_ordered_add_monoid /-! ### Some lemmas about `ℕ` -/ section nat lemma sub_single_one_add {a : ι} {u u' : ι →₀ ℕ} (h : u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := tsub_add_eq_add_tsub $ single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h lemma add_sub_single_one {a : ι} {u u' : ι →₀ ℕ} (h : u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := (add_tsub_assoc_of_le (single_le_iff.mpr $ nat.one_le_iff_ne_zero.mpr h) _).symm end nat end finsupp
c6daaf29897af30932def32612fbb431aa65be17
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0507.lean
f8ef49e94ced993e67cd20e6504f6917128d8112
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
349
lean
variable f : ℕ → ℕ variable h : ∀ x : ℕ, f x ≤ f (x + 1) example : f 0 ≥ f 1 → f 1 ≥ f 2 → f 0 = f 2 := assume : f 0 ≥ f 1, assume : f 1 ≥ f 2, have f 0 ≥ f 2, from le_trans ‹f 2 ≤ f 1› ‹f 1 ≤ f 0›, have f 0 ≤ f 2, from le_trans (h 0) (h 1), show f 0 = f 2, from le_antisymm this ‹f 0 ≥ f 2›
d627368c2a0258cf77425dc60c3751dc0c51c57f
e151e9053bfd6d71740066474fc500a087837323
/src/hott/init/logic.lean
d48178cb3f5e7955a615005c144969557c2fb137
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
21,980
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Floris van Doorn -/ import .path .meta.rewrite universes u v w hott_theory /- prod -/ @[reducible] def pair := @prod.mk @[hott] protected def prod.elim {a b c} (H₁ : a × b) (H₂ : a → b → c) : c := prod.rec H₂ H₁ @[hott] def prod.flip {α : Type u} {β : Type v} : α × β → β × α | ⟨a,b⟩ := ⟨b,a⟩ @[hott] def prod.swap {α : Type u} {β : Type v} : α × β → β × α | ⟨a,b⟩ := ⟨b,a⟩ @[hott, elab_as_eliminator] def prod.destruct {α : Type u} {β : Type v} {C} := @prod.cases_on α β C /- sum -/ infixr ` ⊎ `:30 := sum @[hott] protected def sum.elim {a b c} (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → c) : c := sum.rec H₂ H₃ H₁ @[hott] def sum.swap {a b} : a ⊎ b → b ⊎ a | (sum.inl ha) := sum.inr ha | (sum.inr hb) := sum.inl hb @[hott] def sum.functor {A A' B B'} (f : A → A') (g : B → B') : A ⊎ B → A' ⊎ B' | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr (g b) @[hott] def sum.functor_right (A) {B B'} (g : B → B') : A ⊎ B → A ⊎ B' := sum.functor id g @[hott] def sum.functor_left {A A'} (B) (f : A → A') : A ⊎ B → A' ⊎ B := sum.functor f id namespace hott open unit /- not -/ @[hott] def not (a : Type _) := a → empty hott_theory_cmd "local prefix ¬ := hott.not" @[hott] def absurd {a b : Type _} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) @[hott] def mt {a b : Type _} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ @[hott] def not_empty : ¬empty := assume H : empty, H @[hott] def non_contradictory (a : Type _) : Type _ := ¬¬a @[hott] def non_contradictory_intro {a : Type _} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna @[hott] def not.intro {a : Type _} (H : a → empty) : ¬a := H /- empty -/ @[hott] def empty.elim {c : Type _} (H : empty) : c := empty.rec _ H @[hott, reducible] def ne {A : Type _} (a b : A) := ¬(a = b) hott_theory_cmd "local notation a ≠ b := hott.ne a b" namespace ne variable {A : Type _} variables {a b : A} @[hott] def intro (H : a = b → empty) : a ≠ b := H @[hott] def elim (H : a ≠ b) : a = b → empty := H @[hott] def irrefl (H : a ≠ a) : empty := H rfl @[hott] def symm (H : a ≠ b) : b ≠ a := assume (H₁ : b = a), H (H₁⁻¹) end ne @[hott] def empty_of_ne {A : Type _} {a : A} : a ≠ a → empty := ne.irrefl section variables {p : Type} @[hott] def ne_empty_of_self : p → p ≠ empty := assume (Hp : p) (Heq : p = empty), Heq ▸ Hp @[hott] def ne_unit_of_not : ¬p → p ≠ unit := assume (Hnp : ¬p) (Heq : p = unit), (Heq ▸ Hnp) star @[hott] def unit_ne_empty : ¬unit = empty := ne_empty_of_self star end @[hott] def hott.non_contradictory_em (a : Type _) : ¬¬(a ⊎ ¬a) := assume not_em : ¬(a ⊎ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (sum.inl pos_a) not_em, absurd (sum.inr neg_a) not_em variables {a : Type _} {b : Type _} {c : Type _} {d : Type _} /- iff -/ @[hott] def iff (a b : Type _) := (a → b) × (b → a) hott_theory_cmd "local notation a <-> b := hott.iff a b" hott_theory_cmd "local notation a ↔ b := hott.iff a b" @[hott, intro!] def iff.intro : (a → b) → (b → a) → (a ↔ b) := prod.mk @[hott] def iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := λ H₁ H₂, prod.rec H₁ H₂ @[hott] def iff.elim_left : (a ↔ b) → a → b := prod.fst @[hott] def iff.mp := @iff.elim_left @[hott] def iff.elim_right : (a ↔ b) → b → a := prod.snd @[hott] def iff.mpr := @iff.elim_right @[hott, refl] def iff.refl (a : Type _) : a ↔ a := iff.intro (assume H, H) (assume H, H) @[hott] def iff.rfl {a : Type _} : a ↔ a := iff.refl a @[hott] def iff.of_eq {a b : Type _} (H : a = b) : a ↔ b := eq.rec_on H iff.rfl @[hott, trans] def iff.trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := iff.intro (assume Ha, iff.mp H₂ (iff.mp H₁ Ha)) (assume Hc, iff.mpr H₁ (iff.mpr H₂ Hc)) @[hott, trans] def iff.trans_eq {a b c : Type _} (H₁ : a ↔ b) (H₂ : b = c) : a ↔ c := iff.trans H₁ (iff.of_eq H₂) @[hott, trans] def iff.eq_trans {a b c : Type _} (H₁ : a = b) (H₂ : b ↔ c) : a ↔ c := iff.trans (iff.of_eq H₁) H₂ @[hott, symm] def iff.symm (H : a ↔ b) : b ↔ a := iff.intro (iff.elim_right H) (iff.elim_left H) @[hott] def iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm @[hott] def not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb)) (assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha)) @[hott] def of_iff_unit (H : a ↔ unit) : a := iff.mp (iff.symm H) () @[hott] def not_of_iff_empty : (a ↔ empty) → ¬a := iff.mp @[hott] def iff_unit_intro (H : a) : a ↔ unit := iff.intro (λ Hl, ()) (λ Hr, H) @[hott] def iff_empty_intro (H : ¬a) : a ↔ empty := iff.intro H (empty.rec _) @[hott] def not_non_contradictory_iff_absurd (a : Type _) : ¬¬¬a ↔ ¬a := iff.intro (λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha)) absurd @[hott, congr] def imp_congr (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc))) (λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha))) @[hott] def not_not_intro (Ha : a) : ¬¬a := assume Hna : ¬a, Hna Ha @[hott] def not_of_not_not_not (H : ¬¬¬a) : ¬a := λ Ha, absurd (not_not_intro Ha) H @[hott, hsimp] def not_unit : (¬ unit) ↔ empty := iff_empty_intro (not_not_intro ()) @[hott, hsimp] def not_empty_iff : (¬ empty) ↔ unit := iff_unit_intro not_empty @[hott] def not_congr (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂)) @[hott, hsimp] def ne_self_iff_empty {A : Type _} (a : A) : (not (a = a)) ↔ empty := iff.intro empty_of_ne empty.elim @[hott, hsimp] def eq_self_iff_unit {A : Type _} (a : A) : (a = a) ↔ unit := iff_unit_intro rfl @[hott, hsimp] def iff_not_self (a : Type _) : (a ↔ ¬a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha), H' (iff.mpr H H')) @[hott, hsimp] def not_iff_self (a : Type _) : (¬a ↔ a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha), H' (iff.mp H H')) @[hott, hsimp] def unit_iff_empty : (unit ↔ empty) ↔ empty := iff_empty_intro (λ H, iff.mp H ()) @[hott, hsimp] def empty_iff_unit : (empty ↔ unit) ↔ empty := iff_empty_intro (λ H, iff.mpr H ()) @[hott] def empty_of_unit_iff_empty : (unit ↔ empty) → empty := assume H, iff.mp H () /- prod simp rules -/ @[hott] def prod.imp {a b c d} (H₂ : a → c) (H₃ : b → d) : a × b → c × d | ⟨ha, hb⟩ := ⟨H₂ ha, H₃ hb⟩ @[hott, congr] def prod_congr (H1 : a ↔ c) (H2 : b ↔ d) : (a × b) ↔ (c × d) := iff.intro (prod.imp (iff.mp H1) (iff.mp H2)) (prod.imp (iff.mpr H1) (iff.mpr H2)) @[hott, hsimp] def prod.comm : a × b ↔ b × a := iff.intro prod.swap prod.swap @[hott, hsimp] def prod.assoc : (a × b) × c ↔ a × (b × c) := iff.intro (λ ⟨⟨Ha, Hb⟩, Hc⟩, ⟨Ha, ⟨Hb, Hc⟩⟩) (λ ⟨Ha, ⟨Hb, Hc⟩⟩, ⟨⟨Ha, Hb⟩, Hc⟩) @[hott, hsimp] def prod.fst_comm : a × (b × c) ↔ b × (a × c) := iff.intro (λ ⟨Ha, ⟨Hb, Hc⟩⟩, ⟨Hb, ⟨Ha, Hc⟩⟩) (λ ⟨Hb, ⟨Ha, Hc⟩⟩, ⟨Ha, ⟨Hb, Hc⟩⟩) @[hott] def prod_iff_left {a b : Type _} (Hb : b) : (a × b) ↔ a := iff.intro prod.fst (λHa, prod.mk Ha Hb) @[hott] def prod_iff_right {a b : Type _} (Ha : a) : (a × b) ↔ b := iff.intro prod.snd (prod.mk Ha) @[hott, hsimp] def prod_unit (a : Type _) : a × unit ↔ a := prod_iff_left () @[hott, hsimp] def unit_prod (a : Type _) : unit × a ↔ a := prod_iff_right () @[hott, hsimp] def prod_empty (a : Type _) : a × empty ↔ empty := iff_empty_intro prod.snd @[hott, hsimp] def empty_prod (a : Type _) : empty × a ↔ empty := iff_empty_intro prod.fst @[hott, hsimp] def not_prod_self (a : Type _) : (¬a × a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₂ H₁)) @[hott, hsimp] def prod_not_self (a : Type _) : (a × ¬a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₁ H₂)) @[hott, hsimp] def prod_self (a : Type _) : a × a ↔ a := iff.intro prod.fst (assume H, prod.mk H H) /- sum simp rules -/ @[hott] def sum.imp (H₂ : a → c) (H₃ : b → d) : a ⊎ b → c ⊎ d | (sum.inl H) := sum.inl (H₂ H) | (sum.inr H) := sum.inr (H₃ H) @[hott] def sum.imp_left (H : a → b) : a ⊎ c → b ⊎ c := sum.imp H id @[hott] def sum.imp_right (H : a → b) : c ⊎ a → c ⊎ b := sum.imp id H @[hott, congr] def sum_congr (H1 : a ↔ c) (H2 : b ↔ d) : (a ⊎ b) ↔ (c ⊎ d) := iff.intro (sum.imp (iff.mp H1) (iff.mp H2)) (sum.imp (iff.mpr H1) (iff.mpr H2)) @[hott, hsimp] def sum.comm : a ⊎ b ↔ b ⊎ a := iff.intro sum.swap sum.swap @[hott, hsimp] def sum.assoc : (a ⊎ b) ⊎ c ↔ a ⊎ (b ⊎ c) := iff.intro (λ Habc, match Habc with | sum.inl (sum.inl Ha) := sum.inl Ha | sum.inl (sum.inr Hb) := sum.inr (sum.inl Hb) | sum.inr Hc := sum.inr (sum.inr Hc) end) (λ Habc, match Habc with | sum.inl Ha := sum.inl (sum.inl Ha) | sum.inr (sum.inl Hb) := sum.inl (sum.inr Hb) | sum.inr (sum.inr Hc) := sum.inr Hc end) @[hott, hsimp] def sum.left_comm : a ⊎ (b ⊎ c) ↔ b ⊎ (a ⊎ c) := begin transitivity, {symmetry, exact sum.assoc}, transitivity, {apply sum_congr, apply sum.comm, refl}, apply sum.assoc end @[hott, hsimp] def sum_unit (a : Type _) : a ⊎ unit ↔ unit := iff_unit_intro (sum.inr ()) @[hott, hsimp] def unit_sum (a : Type _) : unit ⊎ a ↔ unit := iff_unit_intro (sum.inl ()) @[hott, hsimp] def sum_empty (a : Type _) : a ⊎ empty ↔ a := iff.intro (λ Hae, match Hae with sum.inl Ha := Ha end) sum.inl @[hott, hsimp] def empty_sum (a : Type _) : empty ⊎ a ↔ a := iff.trans sum.comm (sum_empty _) @[hott, hsimp] def sum_self (a : Type _) : a ⊎ a ↔ a := iff.intro (λ Haa, Haa.elim id id) sum.inl /- sum resolution rulse -/ @[hott] def sum.resolve_left {a b : Type _} (H : a ⊎ b) (na : ¬ a) : b := sum.elim H (λ Ha, absurd Ha na) id @[hott] def sum.neg_resolve_left {a b : Type _} (H : ¬ a ⊎ b) (Ha : a) : b := sum.elim H (λ na, absurd Ha na) id @[hott] def sum.resolve_right {a b : Type _} (H : a ⊎ b) (nb : ¬ b) : a := sum.elim H id (λ Hb, absurd Hb nb) @[hott] def sum.neg_resolve_right {a b : Type _} (H : a ⊎ ¬ b) (Hb : b) : a := sum.elim H id (λ nb, absurd Hb nb) /- iff simp rules -/ @[hott, hsimp] def iff_unit (a : Type _) : (a ↔ unit) ↔ a := iff.intro (assume H, iff.mpr H star) iff_unit_intro @[hott, hsimp] def unit_iff (a : Type _) : (unit ↔ a) ↔ a := iff.trans iff.comm (iff_unit _) @[hott, hsimp] def iff_empty (a : Type _) : (a ↔ empty) ↔ ¬ a := iff.intro prod.fst iff_empty_intro @[hott, hsimp] def empty_iff (a : Type _) : (empty ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_empty _) @[hott, hsimp] def iff_self (a : Type _) : (a ↔ a) ↔ unit := iff_unit_intro iff.rfl @[hott, congr] def iff_congr (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := prod_congr (imp_congr H1 H2) (imp_congr H2 H1) /- decidable -/ class inductive decidable (p : Type u) : Type u | inl : p → decidable | inr : ¬p → decidable @[hott, instance] def decidable_unit : decidable unit := decidable.inl () @[hott, instance] def decidable_empty : decidable empty := decidable.inr not_empty -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[hott] def dite (c : Type _) [H : decidable c] {A : Type _} (Hp : c → A) (Hn : ¬ c → A): A := decidable.rec_on H Hp Hn /- if-then-else -/ @[hott] def ite (c : Type _) [H : decidable c] {A : Type _} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) hott_theory_cmd "local notation `if' ` c ` then ` t:45 ` else ` e:45 := hott.ite c t e" hott_theory_cmd "local notation `if ` binder ` :: ` c ` then ` t:scoped ` else ` e:scoped := hott.dite c t e" namespace decidable variables {p : Type _} {q : Type _} @[hott] def by_cases {q : Type _} [C : decidable p] : (p → q) → (¬p → q) → q := dite _ @[hott] theorem em (p : Type _) [H : decidable p] : p ⊎ ¬p := by_cases sum.inl sum.inr @[hott] theorem by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := if H1 :: p then H1 else empty.rec _ (H H1) end decidable section variables {p : Type _} {q : Type _} open hott.decidable @[hott] def decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q := if Hp :: p then inl (iff.mp H Hp) else inr (iff.mp (not_iff_not_of_iff H) Hp) @[hott] def decidable_of_decidable_of_eq {p q : Type _} (Hp : decidable p) (H : p = q) : decidable q := decidable_of_decidable_of_iff Hp (iff.of_eq H) @[hott] protected def sum.by_cases [Hp : decidable p] [Hq : decidable q] {A : Type _} (h : p ⊎ q) (h₁ : p → A) (h₂ : q → A) : A := if hp :: p then h₁ hp else if hq :: q then h₂ hq else empty.rec _ (sum.elim h hp hq) end section variables {p : Type _} {q : Type _} open hott.decidable @[hott, instance] def decidable_prod [Hp : decidable p] [Hq : decidable q] : decidable (p × q) := if hp :: p then if hq :: q then inl (prod.mk hp hq) else inr (assume H : p × q, hq H.snd) else inr (assume H : p × q, hp H.fst) @[hott, instance] def decidable_sum [Hp : decidable p] [Hq : decidable q] : decidable (p ⊎ q) := if hp :: p then inl (sum.inl hp) else if hq :: q then inl (sum.inr hq) else inr (λ hpq, sum.rec hp hq hpq) @[hott, instance] def decidable_not [Hp : decidable p] : decidable (¬p) := if hp :: p then inr (absurd hp) else inl hp @[hott, instance] def decidable_implies [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := if hp :: p then if hq :: q then inl (assume H, hq) else inr (assume H : p → q, absurd (H hp) hq) else inl (assume Hp, absurd Hp hp) @[hott, instance] def decidable_iff [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := decidable_prod end @[hott, reducible] def decidable_pred {A : Type _} (R : A → Type _) := Π (a : A), decidable (R a) @[hott, reducible] def decidable_rel {A : Type _} (R : A → A → Type _) := Π (a b : A), decidable (R a b) @[hott, reducible] def decidable_eq (A : Type _) := decidable_rel (@eq A) @[hott, reducible, instance] def decidable_ne {A : Type _} [H : decidable_eq A] (a b : A) : decidable (a ≠ b) := decidable_implies namespace bool protected def no_confusion {P : Sort u} {v1 v2 : bool} (H12 : v1 = v2) : bool.no_confusion_type P v1 v2 := eq.rec (λ (H11 : v1 = v1), bool.cases_on v1 (λ (a : P), a) (λ (a : P), a)) H12 H12 @[hott] def ff_ne_tt : ff = tt → empty := bool.no_confusion end bool open hott.bool @[hott] def is_dec_eq {A : Type _} (p : A → A → bool) : Type _ := Π ⦃x y : A⦄, p x y = tt → x = y @[hott] def is_dec_refl {A : Type _} (p : A → A → bool) : Type _ := Πx, p x x = tt open hott.decidable @[hott, instance] protected def bool.has_decidable_eq : Πa b : bool, decidable (a = b) | ff ff := inl rfl | ff tt := inr ff_ne_tt | tt ff := inr (ne.symm ff_ne_tt) | tt tt := inl rfl @[hott] def decidable_eq_of_bool_pred {A : Type _} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A := λ x y : A, if Hp :: p x y = tt then inl (H₁ Hp) else inr begin intro Hxy, apply Hp, rwr Hxy, apply H₂ end /- inhabited -/ @[hott] protected def inhabited.value {A : Type _} : inhabited A → A | ⟨v⟩ := v @[hott] protected def inhabited.destruct {A : Type _} {B : Type _} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 /- subsingleton -/ class subsingleton (A : Type _) := (prop : (Π a b : A, a = b)) @[hott] protected def subsingleton.elim {A : Type _} [H : subsingleton A] : Π(a b : A), a = b := subsingleton.rec (λp, p) H @[hott] protected theorem rec_subsingleton {p : Type _} [H : decidable p] {H1 : p → Type _} {H2 : ¬p → Type _} [H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)] : subsingleton (decidable.rec_on H H1 H2) := decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" @[hott] def if_pos {c : Type _} [H : decidable c] (Hc : c) {A : Type _} {t e : A} : (ite c t e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H @[hott] def if_neg {c : Type _} [H : decidable c] (Hnc : ¬c) {A : Type _} {t e : A} : (ite c t e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H @[hott, hsimp] theorem if_t_t (c : Type _) [H : decidable c] {A : Type _} (t : A) : (ite c t t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H @[hott] theorem implies_of_if_pos {c t e : Type _} [H : decidable c] (h : ite c t e) : c → t := assume Hc, transport id (if_pos Hc) h @[hott] theorem implies_of_if_neg {c t e : Type _} [H : decidable c] (h : ite c t e) : ¬c → e := assume Hc, transport id (if_neg Hc) h @[hott] theorem if_ctx_congr {A : Type _} {b c : Type _} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := if hp :: b then calc ite b x y = x : if_pos hp ... = u : h_t (iff.mp h_c hp) ... = ite c u v : (if_pos (iff.mp h_c hp)).inverse else calc ite b x y = y : if_neg hp ... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hp) ... = ite c u v : (if_neg (iff.mp (not_iff_not_of_iff h_c) hp)).inverse @[hott, congr] theorem if_congr {A : Type _} {b c : Type _} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[hott, congr] theorem if_ctx_simp_congr {A : Type _} {b c : Type _} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e @[hott, congr] theorem if_simp_congr {A : Type _} {b c : Type _} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) @[hott, hsimp] def if_unit {A : Type _} (t e : A) : (if' unit then t else e) = t := if_pos star @[hott, hsimp] def if_empty {A : Type _} (t e : A) : (if' empty then t else e) = e := if_neg not_empty @[hott] theorem if_ctx_congr_prop {b c x y u v : Type _} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := if hp :: b then calc ite b x y ↔ x : iff.of_eq (if_pos hp) ... ↔ u : h_t (iff.mp h_c hp) ... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp)).inverse else calc ite b x y ↔ y : iff.of_eq (if_neg hp) ... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hp) ... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hp)).inverse @[hott, congr] theorem if_congr_prop {b c x y u v : Type _} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) @[hott] theorem if_ctx_simp_congr_prop {b c x y u v : Type _} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) _ u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[hott, congr] theorem if_simp_congr_prop {b c x y u v : Type _} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) _ u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. @[hott] theorem dite_ite_eq (c : Type _) [H : decidable c] {A : Type _} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := by refl @[hott] def is_unit (c : Type _) [H : decidable c] : Type := if' c then unit else empty @[hott] def is_empty (c : Type _) [H : decidable c] : Type := if' c then empty else unit @[hott] def of_is_unit {c : Type _} [H₁ : decidable c] (H₂ : is_unit c) : c := if Hc :: c then Hc else begin unfreezeI, induction H₁, assumption, cases H₂ end notation `dec_star` := of_is_unit star @[hott] theorem not_of_not_is_unit {c : Type _} [H₁ : decidable c] (H₂ : ¬ is_unit c) : ¬ c := if Hc :: c then absurd star (if_pos Hc ▸ H₂) else Hc @[hott] theorem not_of_is_empty {c : Type _} [H₁ : decidable c] (H₂ : is_empty c) : ¬ c := if Hc :: c then begin unfreezeI, induction H₁, cases H₂, assumption end else Hc @[hott] theorem of_not_is_empty {c : Type _} [H₁ : decidable c] (H₂ : ¬ is_empty c) : c := if Hc :: c then Hc else absurd star (if_neg Hc ▸ H₂) end hott
74118897be5ba5785d9a7a5a54205b51be51822b
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/tools/mini_crush/default.lean
64c2fccf685ff93ee889c2201bf26e107f787f3a
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,624
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura We implement a crush-like strategy using simplifier, SMT gadgets, and robust simplifier. This is just a demo. -/ declare_trace mini_crush namespace mini_crush open tactic meta def size (e : expr) : nat := e.fold 1 (λ e _ n, n+1) /- Collect relevant functions -/ meta def is_auto_construction : name → bool | (name.mk_string "brec_on" p) := tt | (name.mk_string "cases_on" p) := tt | (name.mk_string "rec_on" p) := tt | (name.mk_string "no_confusion" p) := tt | (name.mk_string "below" p) := tt | _ := ff meta def is_relevant_fn (n : name) : tactic bool := do env ← get_env, if ¬env.is_definition n ∨ is_auto_construction n then return ff else if env.in_current_file n then return tt else in_open_namespaces n meta def collect_revelant_fns_aux : name_set → expr → tactic name_set | s e := e.mfold s $ λ t _ s, match t with | expr.const c _ := if s.contains c then return s else mcond (is_relevant_fn c) (do new_s ← return $ if c.is_internal then s else s.insert c, d ← get_decl c, collect_revelant_fns_aux new_s d.value) (return s) | _ := return s end meta def collect_revelant_fns : tactic name_set := do ctx ← local_context, s₁ ← ctx.mfoldl (λ s e, infer_type e >>= collect_revelant_fns_aux s) mk_name_set, target >>= collect_revelant_fns_aux s₁ meta def add_relevant_eqns (s : simp_lemmas) : tactic simp_lemmas := do fns ← collect_revelant_fns, fns.mfold s (λ fn s, get_eqn_lemmas_for tt fn >>= mfoldl simp_lemmas.add_simp s) meta def add_relevant_eqns_h (hs : hinst_lemmas) : tactic hinst_lemmas := do fns ← collect_revelant_fns, fns.mfold hs (λ fn hs, get_eqn_lemmas_for tt fn >>= mfoldl (λ hs d, hs.add <$> hinst_lemma.mk_from_decl d) hs) /- Collect terms that are inductive datatypes -/ meta def is_inductive (e : expr) : tactic bool := do type ← infer_type e, C ← return type.get_app_fn, env ← get_env, return $ C.is_constant && env.is_inductive C.const_name meta def collect_inductive_aux : expr_set → expr → tactic expr_set | S e := if S.contains e then return S else do new_S ← mcond (is_inductive e) (return $ S.insert e) (return S), match e with | expr.app _ _ := fold_explicit_args e new_S collect_inductive_aux | expr.pi _ _ d b := if e.is_arrow then collect_inductive_aux S d >>= flip collect_inductive_aux b else return new_S | _ := return new_S end meta def collect_inductive : expr → tactic expr_set := collect_inductive_aux mk_expr_set meta def collect_inductive_from_target : tactic (list expr) := do S ← target >>= collect_inductive, return $ list.qsort (λ e₁ e₂, size e₁ < size e₂) $ S.to_list meta def collect_inductive_hyps : tactic (list expr) := local_context >>= mfoldl (λ r h, mcond (is_inductive h) (return $ h::r) (return r)) [] /- Induction -/ meta def try_induction_aux (cont : expr → tactic unit) : list expr → tactic unit | [] := failed | (e::es) := (step (induction e); cont e; now) <|> try_induction_aux es meta def try_induction (cont : expr → tactic unit) : tactic unit := focus1 $ collect_inductive_hyps >>= try_induction_aux cont /- Trace messages -/ meta def report {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := when_tracing `mini_crush $ trace a meta def report_failure (s : name) (e : option expr := none) : tactic unit := when_tracing `mini_crush $ match e with | none := trace ("FAILED '" ++ to_string s ++ "' at") | some e := (do p ← pp e, trace (to_fmt "FAILED '" ++ to_fmt s ++ "' processing '" ++ p ++ to_fmt "' at")) <|> trace ("FAILED '" ++ to_string s ++ "' at") end >> trace_state >> trace "--------------" /- Simple tactic -/ meta def close_aux (hs : hinst_lemmas) : tactic unit := triv <|> reflexivity reducible <|> contradiction <|> try_for 100 (rsimp {} hs >> now) <|> try_for 100 reflexivity meta def close (hs : hinst_lemmas) (s : name) (e : option expr) : tactic unit := now <|> close_aux hs <|> report_failure s e >> failed meta def simple (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) (h : option expr) : tactic unit := simph_intros_using s cfg >> close hs s_name h /- Best first search -/ meta def snapshot := tactic_state meta def save : tactic snapshot := tactic.read meta def restore : snapshot → tactic unit := tactic.write meta def try_snapshots {α} (cont : α → tactic unit) : list (α × snapshot) → tactic unit | [] := failed | ((a, s)::ss) := (restore s >> cont a >> now) <|> try_snapshots ss meta def search {α} (max_depth : nat) (act : nat → α → tactic (list (α × snapshot))) : nat → α → tactic unit | n s := do now <|> if n > max_depth then when_tracing `mini_crush (trace "max depth reached" >> trace_state) >> failed else all_goals $ try intros >> act n s >>= try_snapshots (search (n+1)) meta def try_and_save {α} (t : tactic α) : tactic (option (α × nat × snapshot)) := do { s ← save, a ← t, new_s ← save, n ← num_goals, restore s, return (a, n, new_s) } <|> return none meta def try_all_aux {α β : Type} (ts : α → tactic β) : list α → list (α × β × nat × snapshot) → tactic (list (α × β × nat × snapshot)) | [] [] := failed | [] rs := return rs.reverse | (v::vs) rs := do r ← try_and_save (ts v), match r with | some (b, 0, s) := return [(v, b, 0, s)] | some (b, n, s) := try_all_aux vs ((v, b, n, s)::rs) | none := try_all_aux vs rs end meta def try_all {α β : Type} (ts : α → tactic β) (vs : list α) : tactic (list (α × β × nat × snapshot)) := try_all_aux ts vs [] /- Destruct and simplify -/ meta def try_cases (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) : tactic (list (unit × snapshot)) := do es ← collect_inductive_from_target, rs ← try_all (λ e, do when_tracing `mini_crush (do p ← pp e, trace (to_fmt "Splitting on '" ++ p ++ to_fmt "'")), cases e; simph_intros_using s cfg; try (close_aux hs)) es, rs ← return $ flip list.qsort rs (λ ⟨e₁, _, n₁, _⟩ ⟨e₂, _, n₂, _⟩, if n₁ ≠ n₂ then n₁ < n₂ else size e₁ < size e₂), return $ rs.map (λ ⟨_, _, _, s⟩, ((), s)) meta def search_cases (max_depth : nat) (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) : tactic unit := search max_depth (λ d _, do when_tracing `mini_crush (trace ("Depth #" ++ to_string d)), try_cases s hs cfg s_name) 0 () /- Strategies -/ meta def mk_simp_lemmas (s : option simp_lemmas := none) : tactic simp_lemmas := match s with | some s := return s | none := simp_lemmas.mk_default >>= add_relevant_eqns end meta def mk_hinst_lemmas (s : option hinst_lemmas := none) : tactic hinst_lemmas := match s with | some s := return s | none := add_relevant_eqns_h hinst_lemmas.mk end meta def strategy_1 (cfg : simp_config := {}) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) (s_name : name := "strategy 1") : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, try_induction (λ h, simple s hs cfg s_name (some h)) meta def strategy_2_aux (cfg : simp_config) (hs : hinst_lemmas) : simp_lemmas → tactic unit | s := do s ← simp_intro_aux cfg tt s tt [`_], -- Introduce next hypothesis h ← list.ilast <$> local_context, try $ solve1 (mwhen (is_inductive h) $ induction' h; simple s hs cfg "strategy 2" (some h)), now <|> strategy_2_aux s meta def strategy_2 (cfg : simp_config := {}) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, strategy_2_aux cfg hs s meta def strategy_3 (cfg : simp_config := {}) (max_depth : nat := 1) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, try_induction (λ h, try (simph_intros_using s cfg); try (close_aux hs); (now <|> search_cases max_depth s hs cfg "strategy 3")) end mini_crush open tactic mini_crush meta def mini_crush (cfg : simp_config := {}) (max_depth : nat := 1) := do s ← mk_simp_lemmas, hs ← mk_hinst_lemmas, strategy_1 cfg (some s) (some hs) <|> strategy_2 cfg (some s) (some hs) <|> strategy_3 cfg max_depth (some s) (some hs)
efce75c8a7fff7de79d494f1ad95beee6bff4660
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/core/hook.lean
7f7be44c6402670a6e562b759c64932ffbd26bd1
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
1,601
lean
import lib.tactic import tactic.rewrite_all import .common open tactic namespace tactic.rewrite_search meta def rewrite_progress := mllist tactic rewrite meta def progress_init (rs : list (expr × bool)) (exp : expr) (cfg : rewrite_all.cfg) : rewrite_progress := (all_rewrites rs exp cfg) .map $ λ t, ⟨t.1.exp, t.1.proof, how.rewrite t.2.1 t.2.2 t.1.addr⟩ meta def progress_next (prog : rewrite_progress) : tactic (rewrite_progress × option rewrite) := do u ← mllist.uncons prog, match u with | (some (r, p)) := return (p, (some r)) | none := return (mllist.nil, none) end meta def simp_rewrite (exp : expr) : tactic rewrite := do (simp_exp, simp_prf) ← exp.simp, return ⟨simp_exp, pure simp_prf, how.simp⟩ -- FIXME I don't know how to extract a proof of equality from `simp_lemmas.dsimplify` -- meta def dsimp_rewrite (exp : expr) : tactic rewrite := do -- dsimp_exp ← tactic.dsimp_expr exp, -- return $ some ⟨dsimp_exp, ???, how.defeq⟩ meta def discover_more_rewrites (rs : list (expr × bool)) (exp : expr) (cfg : rewrite_all.cfg) (_ : side) (prog : option rewrite_progress) : tactic (option rewrite_progress × list rewrite) := do (prog, head) ← match prog with | some prog := pure (prog, []) | none := do let prog := progress_init rs exp cfg, sl ← if cfg.try_simp then option.to_list <$> tactic.try_core (simp_rewrite exp) else pure [], pure (prog, sl) end, (prog, rw) ← progress_next prog, return (some prog, head.append rw.to_list) end tactic.rewrite_search
66c9df9ea26b769c6ecd24a7d8ad035d61691ff0
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/analysis/special_functions/trigonometric.lean
7fe9f53401a1b4a299c22bad1008510d6c8a8785
[ "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
103,002
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.exp_log import data.set.intervals.infinite import algebra.quadratic_discriminant import ring_theory.polynomial.chebyshev.defs /-! # Trigonometric functions ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on complex numbers ## Main statements Many basic inequalities on trigonometric functions are established. The continuity and differentiability of the usual trigonometric functions are proved, and their derivatives are computed. * `polynomial.chebyshev₁_complex_cos`: the `n`-th Chebyshev polynomial evaluates on `complex.cos θ` to the value `n * complex.cos θ`. ## Tags log, sin, cos, tan, arcsin, arccos, arctan, angle, argument -/ noncomputable theory open_locale classical open set namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end lemma times_cont_diff_sin {n} : times_cont_diff ℂ n sin := (((times_cont_diff_neg.mul times_cont_diff_const).cexp.sub (times_cont_diff_id.mul times_cont_diff_const).cexp).mul times_cont_diff_const).div_const lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma continuous_on_sin {s : set ℂ} : continuous_on sin s := continuous_sin.continuous_on lemma measurable_sin : measurable sin := continuous_sin.measurable /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end lemma times_cont_diff_cos {n} : times_cont_diff ℂ n cos := ((times_cont_diff_id.mul times_cont_diff_const).cexp.add (times_cont_diff_neg.mul times_cont_diff_const).cexp).div_const lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_on_cos {s : set ℂ} : continuous_on cos s := continuous_cos.continuous_on lemma measurable_cos : measurable cos := continuous_cos.measurable /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, neg_neg] end lemma times_cont_diff_sinh {n} : times_cont_diff ℂ n sinh := (times_cont_diff_exp.sub times_cont_diff_neg.cexp).div_const lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma measurable_sinh : measurable sinh := continuous_sinh.measurable /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end lemma times_cont_diff_cosh {n} : times_cont_diff ℂ n cosh := (times_cont_diff_exp.add times_cont_diff_neg.cexp).div_const lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous lemma measurable_cosh : measurable cosh := continuous_cosh.measurable end complex section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! #### `complex.cos` -/ lemma measurable.ccos {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable (λ x, complex.cos (f x)) := complex.measurable_cos.comp hf lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x := (complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccos.deriv_within hxs @[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) : deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) := hc.has_deriv_at.ccos.deriv /-! #### `complex.sin` -/ lemma measurable.csin {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable (λ x, complex.sin (f x)) := complex.measurable_sin.comp hf lemma has_deriv_at.csin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x := (complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csin.deriv_within hxs @[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) : deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) := hc.has_deriv_at.csin.deriv /-! #### `complex.cosh` -/ lemma measurable.ccosh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable (λ x, complex.cosh (f x)) := complex.measurable_cosh.comp hf lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccosh.deriv_within hxs @[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) : deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) := hc.has_deriv_at.ccosh.deriv /-! #### `complex.sinh` -/ lemma measurable.csinh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) : measurable (λ x, complex.sinh (f x)) := complex.measurable_sinh.comp hf lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csinh.deriv_within hxs @[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) : deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) := hc.has_deriv_at.csinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/ variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ} {x : E} {s : set E} /-! #### `complex.cos` -/ lemma has_fderiv_at.ccos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') s x := (complex.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_fderiv_within_at.ccos.differentiable_within_at @[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cos (f x)) x := hc.has_fderiv_at.ccos.differentiable_at lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cos (f x)) s := λx h, (hc x h).ccos @[simp] lemma differentiable.ccos (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cos (f x)) := λx, (hc x).ccos lemma fderiv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cos (f x)) s x = - complex.sin (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccos.fderiv_within hxs @[simp] lemma fderiv_ccos (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cos (f x)) x = - complex.sin (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccos.fderiv lemma times_cont_diff.ccos {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.cos (f x)) := complex.times_cont_diff_cos.comp h lemma times_cont_diff_at.ccos {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.cos (f x)) x := complex.times_cont_diff_cos.times_cont_diff_at.comp x hf lemma times_cont_diff_on.ccos {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.cos (f x)) s := complex.times_cont_diff_cos.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.ccos {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.cos (f x)) s x := complex.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.sin` -/ lemma has_fderiv_at.csin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') s x := (complex.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_fderiv_within_at.csin.differentiable_within_at @[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sin (f x)) x := hc.has_fderiv_at.csin.differentiable_at lemma differentiable_on.csin (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sin (f x)) s := λx h, (hc x h).csin @[simp] lemma differentiable.csin (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sin (f x)) := λx, (hc x).csin lemma fderiv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sin (f x)) s x = complex.cos (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csin.fderiv_within hxs @[simp] lemma fderiv_csin (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sin (f x)) x = complex.cos (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csin.fderiv lemma times_cont_diff.csin {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.sin (f x)) := complex.times_cont_diff_sin.comp h lemma times_cont_diff_at.csin {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.sin (f x)) x := complex.times_cont_diff_sin.times_cont_diff_at.comp x hf lemma times_cont_diff_on.csin {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.sin (f x)) s := complex.times_cont_diff_sin.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.csin {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.sin (f x)) s x := complex.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.cosh` -/ lemma has_fderiv_at.ccosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.ccosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_fderiv_within_at.ccosh.differentiable_within_at @[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cosh (f x)) x := hc.has_fderiv_at.ccosh.differentiable_at lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cosh (f x)) s := λx h, (hc x h).ccosh @[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cosh (f x)) := λx, (hc x).ccosh lemma fderiv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.cosh (f x)) s x = complex.sinh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.ccosh.fderiv_within hxs @[simp] lemma fderiv_ccosh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.cosh (f x)) x = complex.sinh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.ccosh.fderiv lemma times_cont_diff.ccosh {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.cosh (f x)) := complex.times_cont_diff_cosh.comp h lemma times_cont_diff_at.ccosh {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.cosh (f x)) x := complex.times_cont_diff_cosh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.ccosh {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.cosh (f x)) s := complex.times_cont_diff_cosh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.ccosh {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.cosh (f x)) s x := complex.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `complex.sinh` -/ lemma has_fderiv_at.csinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.csinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_fderiv_within_at.csinh.differentiable_within_at @[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sinh (f x)) x := hc.has_fderiv_at.csinh.differentiable_at lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sinh (f x)) s := λx h, (hc x h).csinh @[simp] lemma differentiable.csinh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sinh (f x)) := λx, (hc x).csinh lemma fderiv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : fderiv_within ℂ (λx, complex.sinh (f x)) s x = complex.cosh (f x) • (fderiv_within ℂ f s x) := hf.has_fderiv_within_at.csinh.fderiv_within hxs @[simp] lemma fderiv_csinh (hc : differentiable_at ℂ f x) : fderiv ℂ (λx, complex.sinh (f x)) x = complex.cosh (f x) • (fderiv ℂ f x) := hc.has_fderiv_at.csinh.fderiv lemma times_cont_diff.csinh {n} (h : times_cont_diff ℂ n f) : times_cont_diff ℂ n (λ x, complex.sinh (f x)) := complex.times_cont_diff_sinh.comp h lemma times_cont_diff_at.csinh {n} (hf : times_cont_diff_at ℂ n f x) : times_cont_diff_at ℂ n (λ x, complex.sinh (f x)) x := complex.times_cont_diff_sinh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.csinh {n} (hf : times_cont_diff_on ℂ n f s) : times_cont_diff_on ℂ n (λ x, complex.sinh (f x)) s := complex.times_cont_diff_sinh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.csinh {n} (hf : times_cont_diff_within_at ℂ n f s x) : times_cont_diff_within_at ℂ n (λ x, complex.sinh (f x)) s x := complex.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf end namespace real variables {x y z : ℝ} lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := (complex.has_deriv_at_sin x).real_of_complex lemma times_cont_diff_sin {n} : times_cont_diff ℝ n sin := complex.times_cont_diff_sin.real_of_complex lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin : differentiable_at ℝ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma measurable_sin : measurable sin := continuous_sin.measurable lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (complex.has_deriv_at_cos x).real_of_complex lemma times_cont_diff_cos {n} : times_cont_diff ℝ n cos := complex.times_cont_diff_cos.real_of_complex lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos : differentiable_at ℝ cos x := differentiable_cos x lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_on_cos {s} : continuous_on cos s := continuous_cos.continuous_on lemma measurable_cos : measurable cos := continuous_cos.measurable lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := (complex.has_deriv_at_sinh x).real_of_complex lemma times_cont_diff_sinh {n} : times_cont_diff ℝ n sinh := complex.times_cont_diff_sinh.real_of_complex lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma measurable_sinh : measurable sinh := continuous_sinh.measurable lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := (complex.has_deriv_at_cosh x).real_of_complex lemma times_cont_diff_cosh {n} : times_cont_diff ℝ n cosh := complex.times_cont_diff_cosh.real_of_complex lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous lemma measurable_cosh : measurable cosh := continuous_cosh.measurable /-- `sinh` is strictly monotone. -/ lemma sinh_strict_mono : strict_mono sinh := strict_mono_of_deriv_pos differentiable_sinh (by { rw [real.deriv_sinh], exact cosh_pos }) end real section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! #### `real.cos` -/ lemma measurable.cos {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.cos (f x)) := real.measurable_cos.comp hf lemma has_deriv_at.cos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x := (real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cos.deriv_within hxs @[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) : deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) := hc.has_deriv_at.cos.deriv /-! #### `real.sin` -/ lemma measurable.sin {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.sin (f x)) := real.measurable_sin.comp hf lemma has_deriv_at.sin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x := (real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sin.deriv_within hxs @[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) : deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) := hc.has_deriv_at.sin.deriv /-! #### `real.cosh` -/ lemma measurable.cosh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.cosh (f x)) := real.measurable_cosh.comp hf lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x := (real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cosh.deriv_within hxs @[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) : deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) := hc.has_deriv_at.cosh.deriv /-! #### `real.sinh` -/ lemma measurable.sinh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.sinh (f x)) := real.measurable_sinh.comp hf lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x := (real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sinh.deriv_within hxs @[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) : deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) := hc.has_deriv_at.sinh.deriv end section /-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E} {s : set E} /-! #### `real.cos` -/ lemma has_fderiv_at.cos (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cos (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cos (f x)) (- real.sin (f x) • f') s x := (real.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_fderiv_within_at.cos.differentiable_within_at @[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cos (f x)) x := hc.has_fderiv_at.cos.differentiable_at lemma differentiable_on.cos (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cos (f x)) s := λx h, (hc x h).cos @[simp] lemma differentiable.cos (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cos (f x)) := λx, (hc x).cos lemma fderiv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cos (f x)) s x = - real.sin (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cos.fderiv_within hxs @[simp] lemma fderiv_cos (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cos (f x)) x = - real.sin (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cos.fderiv lemma times_cont_diff.cos {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.cos (f x)) := real.times_cont_diff_cos.comp h lemma times_cont_diff_at.cos {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.cos (f x)) x := real.times_cont_diff_cos.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cos {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.cos (f x)) s := real.times_cont_diff_cos.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cos {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.cos (f x)) s x := real.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.sin` -/ lemma has_fderiv_at.sin (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sin (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sin (f x)) (real.cos (f x) • f') s x := (real.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_fderiv_within_at.sin.differentiable_within_at @[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sin (f x)) x := hc.has_fderiv_at.sin.differentiable_at lemma differentiable_on.sin (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sin (f x)) s := λx h, (hc x h).sin @[simp] lemma differentiable.sin (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sin (f x)) := λx, (hc x).sin lemma fderiv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sin (f x)) s x = real.cos (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sin.fderiv_within hxs @[simp] lemma fderiv_sin (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sin (f x)) x = real.cos (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sin.fderiv lemma times_cont_diff.sin {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.sin (f x)) := real.times_cont_diff_sin.comp h lemma times_cont_diff_at.sin {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.sin (f x)) x := real.times_cont_diff_sin.times_cont_diff_at.comp x hf lemma times_cont_diff_on.sin {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.sin (f x)) s := real.times_cont_diff_sin.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.sin {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.sin (f x)) s x := real.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.cosh` -/ lemma has_fderiv_at.cosh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.cosh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') s x := (real.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_fderiv_within_at.cosh.differentiable_within_at @[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cosh (f x)) x := hc.has_fderiv_at.cosh.differentiable_at lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cosh (f x)) s := λx h, (hc x h).cosh @[simp] lemma differentiable.cosh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cosh (f x)) := λx, (hc x).cosh lemma fderiv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.cosh (f x)) s x = real.sinh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.cosh.fderiv_within hxs @[simp] lemma fderiv_cosh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.cosh (f x)) x = real.sinh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.cosh.fderiv lemma times_cont_diff.cosh {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.cosh (f x)) := real.times_cont_diff_cosh.comp h lemma times_cont_diff_at.cosh {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.cosh (f x)) x := real.times_cont_diff_cosh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.cosh {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.cosh (f x)) s := real.times_cont_diff_cosh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.cosh {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.cosh (f x)) s x := real.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf /-! #### `real.sinh` -/ lemma has_fderiv_at.sinh (hf : has_fderiv_at f f' x) : has_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf lemma has_fderiv_within_at.sinh (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') s x := (real.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_fderiv_within_at.sinh.differentiable_within_at @[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sinh (f x)) x := hc.has_fderiv_at.sinh.differentiable_at lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sinh (f x)) s := λx h, (hc x h).sinh @[simp] lemma differentiable.sinh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sinh (f x)) := λx, (hc x).sinh lemma fderiv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, real.sinh (f x)) s x = real.cosh (f x) • (fderiv_within ℝ f s x) := hf.has_fderiv_within_at.sinh.fderiv_within hxs @[simp] lemma fderiv_sinh (hc : differentiable_at ℝ f x) : fderiv ℝ (λx, real.sinh (f x)) x = real.cosh (f x) • (fderiv ℝ f x) := hc.has_fderiv_at.sinh.fderiv lemma times_cont_diff.sinh {n} (h : times_cont_diff ℝ n f) : times_cont_diff ℝ n (λ x, real.sinh (f x)) := real.times_cont_diff_sinh.comp h lemma times_cont_diff_at.sinh {n} (hf : times_cont_diff_at ℝ n f x) : times_cont_diff_at ℝ n (λ x, real.sinh (f x)) x := real.times_cont_diff_sinh.times_cont_diff_at.comp x hf lemma times_cont_diff_on.sinh {n} (hf : times_cont_diff_on ℝ n f s) : times_cont_diff_on ℝ n (λ x, real.sinh (f x)) s := real.times_cont_diff_sinh.comp_times_cont_diff_on hf lemma times_cont_diff_within_at.sinh {n} (hf : times_cont_diff_within_at ℝ n f s x) : times_cont_diff_within_at ℝ n (λ x, real.sinh (f x)) s x := real.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf end namespace real lemma exists_cos_eq_zero : 0 ∈ cos '' Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_on_cos ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.2 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_ne_zero : pi ≠ 0 := ne_of_gt pi_pos lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_mem_Ioo {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_mem_Icc {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_mem_Ioo hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_mem_Ioo (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_mem_Icc (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff, ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := begin rw [← sub_lt_zero, cos_sub_cos], have : 0 < sin ((y + x) / 2), { refine sin_pos_of_pos_of_lt_pi _ _; linarith }, have : 0 < sin ((y - x) / 2), { refine sin_pos_of_pos_of_lt_pi _ _; linarith }, nlinarith, end lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_mem_Ioo (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_right_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : Icc (-1:ℝ) 1 ⊆ sin '' Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] lemma exists_cos_eq : (Icc (-1) 1 : set ℝ) ⊆ cos '' Icc 0 π := by convert intermediate_value_Icc' real.pi_pos.le real.continuous_on_cos; simp only [real.cos_pi, real.cos_zero] lemma range_cos : range cos = (Icc (-1) 1 : set ℝ) := begin ext, split, { rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_cos, y.cos_le_one⟩ }, { rintros h, rcases real.exists_cos_eq h with ⟨y, -, hy⟩, exact ⟨y, hy⟩ } end lemma range_sin : range sin = (Icc (-1) 1 : set ℝ) := begin ext, split, { rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_sin, y.sin_le_one⟩ }, { rintros h, rcases real.exists_sin_eq h with ⟨y, -, hy⟩, exact ⟨y, hy⟩ } end lemma range_cos_infinite : (range real.cos).infinite := by { rw real.range_cos, exact Icc.infinite (by norm_num) } lemma range_sin_infinite : (range real.sin).infinite := by { rw real.range_sin, exact Icc.infinite (by norm_num) } lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, ← mul_sub]; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end section cos_div_pow_two variable (x : ℝ) /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ | 0 := x | (n+1) := sqrt (2 + sqrt_two_add_series n) lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), 0 ≤ sqrt_two_add_series 0 n | 0 := le_refl 0 | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), 0 ≤ sqrt_two_add_series x n | 0 := h | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2 | 0 := by norm_num | (n+1) := begin refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt zero_lt_two), rw [sqrt_two_add_series, sqrt_lt], apply add_lt_of_lt_sub_left, apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n), norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num end lemma sqrt_two_add_series_succ (x : ℝ) : ∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n | 0 := rfl | (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series] lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) : ∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n | 0 := h | (n+1) := begin rw [sqrt_two_add_series, sqrt_two_add_series], apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left end @[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2 | 0 := by simp | (n+1) := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc, nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul], congr, norm_num, rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc, mul_div_cancel_left], norm_num, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num, apply le_of_lt, apply cos_pos_of_mem_Ioo, { transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos, apply div_pos pi_pos, apply pow_pos, norm_num }, apply div_lt_div' (le_refl pi) _ pi_pos _, refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num} end lemma sin_square_pi_over_two_pow (n : ℕ) : sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 := by rw [sin_square, cos_pi_over_two_pow] lemma sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 := begin rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub], congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, end @[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul], { congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num }, { rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two }, apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi, { apply div_pos pi_pos, apply pow_pos, norm_num }, refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left], refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos, apply pow_pos, all_goals {norm_num} end @[simp] lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 := by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp } @[simp] lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 := by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp } @[simp] lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 := by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp } @[simp] lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 := by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp } @[simp] lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 := by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp } @[simp] lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 := by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp } @[simp] lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp } @[simp] lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp } -- This section is also a convenient location for other explicit values of `sin` and `cos`. /-- The cosine of `π / 3` is `1 / 2`. -/ @[simp] lemma cos_pi_div_three : cos (π / 3) = 1 / 2 := begin have h₁ : (2 * cos (π / 3) - 1) ^ 2 * (2 * cos (π / 3) + 2) = 0, { have : cos (3 * (π / 3)) = cos π := by { congr' 1, ring }, linarith [cos_pi, cos_three_mul (π / 3)] }, cases mul_eq_zero.mp h₁ with h h, { linarith [pow_eq_zero h] }, { have : cos π < cos (π / 3), { refine cos_lt_cos_of_nonneg_of_le_pi _ rfl.ge _; linarith [pi_pos] }, linarith [cos_pi] } end /-- The square of the cosine of `π / 6` is `3 / 4` (this is sometimes more convenient than the result for cosine itself). -/ lemma square_cos_pi_div_six : cos (π / 6) ^ 2 = 3 / 4 := begin have h1 : cos (π / 6) ^ 2 = 1 / 2 + 1 / 2 / 2, { convert cos_square (π / 6), have h2 : 2 * (π / 6) = π / 3 := by cancel_denoms, rw [h2, cos_pi_div_three] }, rw ← sub_eq_zero at h1 ⊢, convert h1 using 1, ring end /-- The cosine of `π / 6` is `√3 / 2`. -/ @[simp] lemma cos_pi_div_six : cos (π / 6) = (sqrt 3) / 2 := begin suffices : sqrt 3 = cos (π / 6) * 2, { field_simp [(by norm_num : 0 ≠ 2)], exact this.symm }, rw sqrt_eq_iff_sqr_eq, { have h1 := (mul_right_inj' (by norm_num : (4:ℝ) ≠ 0)).mpr square_cos_pi_div_six, rw ← sub_eq_zero at h1 ⊢, convert h1 using 1, ring }, { norm_num }, { have : 0 < cos (π / 6) := by { apply cos_pos_of_mem_Ioo; linarith [pi_pos] }, linarith }, end /-- The sine of `π / 6` is `1 / 2`. -/ @[simp] lemma sin_pi_div_six : sin (π / 6) = 1 / 2 := begin rw [← cos_pi_div_two_sub, ← cos_pi_div_three], congr, ring end /-- The square of the sine of `π / 3` is `3 / 4` (this is sometimes more convenient than the result for cosine itself). -/ lemma square_sin_pi_div_three : sin (π / 3) ^ 2 = 3 / 4 := begin rw [← cos_pi_div_two_sub, ← square_cos_pi_div_six], congr, ring end /-- The sine of `π / 3` is `√3 / 2`. -/ @[simp] lemma sin_pi_div_three : sin (π / 3) = (sqrt 3) / 2 := begin rw [← cos_pi_div_two_sub, ← cos_pi_div_six], congr, ring end end cos_div_pow_two /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (add_subgroup.gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑((n : ℝ) * x) = n •ℕ (↑x : angle) := by simpa using add_monoid_hom.map_nsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp, norm_cast] lemma coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) : ↑((n : ℝ) * x : ℝ) = n •ℤ (↑x : angle) := by simpa using add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, show (-1 : ℤ) •ℤ (2 * π) = _, by rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, add_subgroup.gmultiples_eq_closure, add_subgroup.mem_closure_singleton, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] }, apply_instance, }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_right_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, change n •ℤ _ = _ at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_mem_Icc (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 @[simp] lemma tan_pi_div_four : tan (π / 4) = 1 := begin rw [tan_eq_sin_div_cos, cos_pi_div_four, sin_pi_div_four], have h : (sqrt 2) / 2 > 0 := by cancel_denoms, exact div_self (ne_of_gt h), end lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_mem_Ioo (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith)) (cos_pos_of_mem_Ioo (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← mul_right_inj' (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma arctan_mem_Ioo (x : ℝ) : arctan x ∈ Ioo (-(π / 2)) (π / 2) := ⟨neg_pi_div_two_lt_arctan x, arctan_lt_pi_div_two x⟩ lemma tan_surjective : function.surjective tan := function.right_inverse.surjective tan_arctan lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_one : arctan 1 = π / 4 := begin refine tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan 1) (arctan_lt_pi_div_two 1) _ _ _; linarith [pi_pos, tan_arctan 1, tan_pi_div_four], end @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_nonneg _))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (mt abs_eq_zero.1 h)] end lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_mem_Icc hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma range_exp : range exp = {x | x ≠ 0} := set.ext $ λ x, ⟨by { rintro ⟨x, rfl⟩, exact exp_ne_zero x }, λ hx, ⟨log x, exp_log hx⟩⟩ lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re] @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exists_pow_nat_eq (x : ℂ) {n : ℕ} (hn : 0 < n) : ∃ z, z ^ n = x := begin by_cases hx : x = 0, { use 0, simp only [hx, zero_pow_eq_zero, hn] }, { use exp (log x / n), rw [← exp_nat_mul, mul_div_cancel', exp_log hx], exact_mod_cast (nat.pos_iff_ne_zero.mp hn) } end lemma exists_eq_mul_self (x : ℂ) : ∃ z, x = z * z := begin obtain ⟨z, rfl⟩ := exists_pow_nat_eq x zero_lt_two, exact ⟨z, pow_two z⟩ end lemma two_pi_I_ne_zero : (2 * π * I : ℂ) ≠ 0 := by norm_num [real.pi_ne_zero, I_ne_zero] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℂ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℂ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℂ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℂ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℂ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℂ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_add_pi_div_two (x : ℂ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℂ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℂ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℂ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℂ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℂ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma exp_pi_mul_I : exp (π * I) = -1 := by { rw exp_mul_I, simp, } theorem cos_eq_zero_iff {θ : ℂ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 := begin have h : (exp (θ * I) + exp (-θ * I)) / 2 = 0 ↔ exp (2 * θ * I) = -1, { rw [@div_eq_iff _ _ (exp (θ * I) + exp (-θ * I)) 2 0 (by norm_num), zero_mul, add_eq_zero_iff_eq_neg, neg_eq_neg_one_mul (exp (-θ * I)), ← div_eq_iff (exp_ne_zero (-θ * I)), ← exp_sub], field_simp, ring }, rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int], split; simp; intros x h2; use x, { field_simp, ring at h2, rwa [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero, mul_comm 2 θ] at h2}, { field_simp at h2, ring, rw [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero, mul_comm 2 θ, h2] }, end theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] theorem sin_eq_zero_iff {θ : ℂ} : sin θ = 0 ↔ ∃ k : ℤ, θ = k * π := begin rw [← complex.cos_sub_pi_div_two, cos_eq_zero_iff], split, { rintros ⟨k, hk⟩, use k + 1, field_simp [eq_add_of_sub_eq hk], ring }, { rintros ⟨k, rfl⟩, use k - 1, field_simp, ring } end theorem sin_ne_zero_iff {θ : ℂ} : sin θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π := by rw [← not_exists, not_iff_not, sin_eq_zero_iff] lemma cos_eq_cos_iff {x y : ℂ} : cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x := calc cos x = cos y ↔ cos x - cos y = 0 : sub_eq_zero.symm ... ↔ -2 * sin((x + y)/2) * sin((x - y)/2) = 0 : by rw cos_sub_cos ... ↔ sin((x + y)/2) = 0 ∨ sin((x - y)/2) = 0 : by { field_simp [(by norm_num : -(2:ℂ) ≠ 0)] } ... ↔ sin((x - y)/2) = 0 ∨ sin((x + y)/2) = 0 : or.comm ... ↔ (∃ k : ℤ, y = 2 * k * π + x) ∨ (∃ k :ℤ, y = 2 * k * π - x) : begin apply or_congr; rw sin_eq_zero_iff; field_simp [(by norm_num : -(2:ℂ) ≠ 0)], work_on_goal 0 -- material specific to the left of the `or`, when x ≅ y mod 2π { split, all_goals { rintros ⟨k, hk⟩, refine ⟨-k, eq.symm _⟩ } }, work_on_goal 2 -- material specific to the right of the `or`, when x ≅ -y mod 2π { refine exists_congr (λ k, ⟨λ hk, _, λ hk, _⟩) }, all_goals -- joint material for showing two equations differ by a constant { rw ← sub_eq_zero at hk ⊢, convert hk using 1, try { push_cast }, ring } end ... ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x : exists_or_distrib.symm lemma sin_eq_sin_iff {x y : ℂ} : sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x := begin rw [←complex.cos_sub_pi_div_two, ←complex.cos_sub_pi_div_two, cos_eq_cos_iff], simp only [exists_or_distrib], apply or_congr; refine exists_congr (λ k, ⟨_, _⟩); { intros h, rw ← sub_eq_zero at ⊢ h, convert h using 1, field_simp, ring }, end lemma has_deriv_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : has_deriv_at tan (1 / (cos x)^2) x := begin convert has_deriv_at.div (has_deriv_at_sin x) (has_deriv_at_cos x) (cos_ne_zero_iff.mpr h), rw ← sin_sq_add_cos_sq x, ring, end lemma differentiable_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℂ tan x := (has_deriv_at_tan h).differentiable_at @[simp] lemma deriv_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan h).deriv lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := continuous_on_sin.div continuous_on_cos $ λ x, id lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := continuous_on_iff_continuous_restrict.1 continuous_on_tan lemma cos_surjective : function.surjective cos := begin intro x, obtain ⟨w, hw⟩ : ∃ w, 1 * w * w + (-2 * x) * w + 1 = 0, { exact exists_quadratic_eq_zero one_ne_zero (exists_eq_mul_self _) }, have hw' : exp (log w / I * I) = w, { rw [div_mul_cancel _ I_ne_zero, exp_log], rintro rfl, simpa only [zero_add, one_ne_zero, mul_zero] using hw }, obtain ⟨z, hz⟩ : ∃ z : ℂ, (exp (z * I)) ^ 2 - 2 * x * exp (z * I) + 1 = 0, { use log w / I, rw [hw', ← hw], ring }, use z, delta cos, rw ← mul_left_inj' (exp_ne_zero (z * I)), rw [sub_add_eq_add_sub, sub_eq_zero, pow_two, ← exp_add, mul_comm _ x, mul_right_comm] at hz, field_simp [add_mul, ← exp_add, hz] end @[simp] lemma range_cos : range cos = set.univ := cos_surjective.range_eq lemma sin_surjective : function.surjective sin := begin intro x, rcases cos_surjective x with ⟨z, rfl⟩, exact ⟨z+π/2, sin_add_pi_div_two z⟩ end @[simp] lemma range_sin : range sin = set.univ := sin_surjective.range_eq end complex section chebyshev₁ open polynomial complex /-- the `n`-th Chebyshev polynomial evaluates on `cos θ` to the value `cos (n * θ)`. -/ lemma chebyshev₁_complex_cos (θ : ℂ) : ∀ n, (chebyshev₁ ℂ n).eval (cos θ) = cos (n * θ) | 0 := by simp only [chebyshev₁_zero, eval_one, nat.cast_zero, zero_mul, cos_zero] | 1 := by simp only [eval_X, one_mul, chebyshev₁_one, nat.cast_one] | (n + 2) := begin simp only [eval_X, eval_one, chebyshev₁_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul], rw [chebyshev₁_complex_cos (n + 1), chebyshev₁_complex_cos n], have aux : sin θ * sin θ = 1 - cos θ * cos θ, { rw ← sin_sq_add_cos_sq θ, ring, }, simp only [nat.cast_add, nat.cast_one, add_mul, cos_add, one_mul, sin_add, mul_assoc, aux], ring, end /-- `cos (n * θ)` is equal to the `n`-th Chebyshev polynomial evaluated on `cos θ`. -/ lemma cos_nat_mul (n : ℕ) (θ : ℂ) : cos (n * θ) = (chebyshev₁ ℂ n).eval (cos θ) := (chebyshev₁_complex_cos θ n).symm end chebyshev₁ namespace real open_locale real theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 := begin rw [← complex.of_real_eq_zero, complex.of_real_cos θ], convert @complex.cos_eq_zero_iff θ, norm_cast, end theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] lemma cos_eq_cos_iff {x y : ℝ} : cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x := begin have := @complex.cos_eq_cos_iff x y, rw [← complex.of_real_cos, ← complex.of_real_cos] at this, norm_cast at this, simp [this], end lemma sin_eq_sin_iff {x y : ℝ} : sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x := begin have := @complex.sin_eq_sin_iff x y, rw [← complex.of_real_sin, ← complex.of_real_sin] at this, norm_cast at this, simp [this], end lemma has_deriv_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : has_deriv_at tan (1 / (cos x)^2) x := begin convert (complex.has_deriv_at_tan (by { convert h, norm_cast } )).real_of_complex, rw ← complex.of_real_re (1/((cos x)^2)), simp, end lemma differentiable_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℝ tan x := (has_deriv_at_tan h).differentiable_at @[simp] lemma deriv_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan h).deriv lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := by { rw continuous_on_iff_continuous_restrict, convert continuous_tan } lemma has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : has_deriv_at tan (1 / (cos x)^2) x := has_deriv_at_tan (cos_ne_zero_iff.mp (ne_of_gt (cos_pos_of_mem_Ioo h.1 h.2))) lemma differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : differentiable_at ℝ tan x := (has_deriv_at_tan_of_mem_Ioo h).differentiable_at lemma deriv_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan_of_mem_Ioo h).deriv lemma continuous_on_tan_Ioo : continuous_on tan (Ioo (-(π/2)) (π/2)) := begin refine continuous_on_tan.mono _, intros x hx, simp only [mem_set_of_eq], exact ne_of_gt (cos_pos_of_mem_Ioo hx.1 hx.2), end open filter open_locale topological_space lemma tendsto_sin_pi_div_two : tendsto sin (𝓝[Iio (π/2)] (π/2)) (𝓝 1) := by { convert continuous_sin.continuous_within_at, simp } lemma tendsto_cos_pi_div_two : tendsto cos (𝓝[Iio (π/2)] (π/2)) (𝓝[Ioi 0] 0) := begin apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within, { convert continuous_cos.continuous_within_at, simp }, { filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.mpr (norm_num.lt_neg_pos _ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx.1 hx.2 }, end lemma tendsto_tan_pi_div_two : tendsto tan (𝓝[Iio (π/2)] (π/2)) at_top := begin convert tendsto_mul_at_top (by norm_num) (tendsto.inv_tendsto_zero tendsto_cos_pi_div_two) tendsto_sin_pi_div_two, ext x, rw tan_eq_sin_div_cos x, ring, end lemma tendsto_sin_neg_pi_div_two : tendsto sin (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝 (-1)) := by { convert continuous_sin.continuous_within_at, simp } lemma tendsto_cos_neg_pi_div_two : tendsto cos (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝[Ioi 0] 0) := begin apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within, { convert continuous_cos.continuous_within_at, simp }, { filter_upwards [Ioo_mem_nhds_within_Ioi (set.left_mem_Ico.mpr (norm_num.lt_neg_pos _ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx.1 hx.2 }, end lemma tendsto_tan_neg_pi_div_two : tendsto tan (𝓝[Ioi (-(π/2))] (-(π/2))) at_bot := begin convert tendsto_mul_at_bot (by norm_num) (tendsto.inv_tendsto_zero tendsto_cos_neg_pi_div_two) tendsto_sin_neg_pi_div_two, ext x, rw tan_eq_sin_div_cos x, ring, end /-! ### Continuity and differentiability of arctan The continuity of `arctan` is difficult to prove due to `arctan` being (indirectly) defined naively via `classical.some`. The proof therefore uses the general theorem that monotone functions are homeomorphisms: `homeomorph_of_strict_mono_continuous_Ioo`. We first prove that `tan` (restricted) is a homeomorphism whose inverse is definitionally equal to `arctan`. The fact that `arctan` is continuous is then derived from the fact that it is equal to a homeomorphism, and its differentiability is in turn derived from its continuity using `has_deriv_at.of_local_left_inverse`. -/ /-- The function `tan`, restricted to the open interval (-π/2, π/2), is a homeomorphism. The inverse function of that homeomorphism is definitionally equal to `arctan` via `homeomorph.change_inv`. -/ def tan_homeomorph : (Ioo (-(π/2)) (π/2)) ≃ₜ ℝ := (homeomorph_of_strict_mono_continuous_Ioo tan (by linarith [pi_div_two_pos]) (λ x y, tan_lt_tan_of_lt_of_lt_pi_div_two) continuous_on_tan_Ioo tendsto_tan_pi_div_two tendsto_tan_neg_pi_div_two).change_inv (λ x, ⟨arctan x, arctan_mem_Ioo x⟩) tan_arctan lemma tan_homeomorph_inv_fun_eq_arctan : coe ∘ tan_homeomorph.inv_fun = arctan := rfl lemma continuous_arctan : continuous arctan := continuous_subtype_coe.comp tan_homeomorph.continuous_inv_fun lemma has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x^2)) x := begin have h1 : 0 < 1 + x^2 := by nlinarith, have h2 : cos (arctan x) ≠ 0 := by { rw cos_arctan, exact ne_of_gt (one_div_pos.mpr (sqrt_pos.mpr h1)) }, simpa [(cos_arctan x), sqr_sqrt (le_of_lt h1)] using has_deriv_at.of_local_left_inverse continuous_arctan.continuous_at (has_deriv_at_tan (cos_ne_zero_iff.mp h2)) (one_div_ne_zero (pow_ne_zero 2 h2)) (by {apply eventually_of_forall, exact tan_arctan} ), end lemma differentiable_at_arctan (x : ℝ) : differentiable_at ℝ arctan x := (has_deriv_at_arctan x).differentiable_at @[simp] lemma deriv_arctan : deriv arctan = (λ x, 1 / (1 + x^2)) := funext $ λ x, (has_deriv_at_arctan x).deriv end real section /-! Register lemmas for the derivatives of the composition of `real.arctan` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} lemma has_deriv_at.arctan (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.arctan (f x)) ((1 / (1 + (f x)^2)) * f') x := (real.has_deriv_at_arctan (f x)).comp x hf lemma has_deriv_within_at.arctan (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.arctan (f x)) ((1 / (1 + (f x)^2)) * f') s x := (real.has_deriv_at_arctan (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.arctan (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.arctan (f x)) s x := hf.has_deriv_within_at.arctan.differentiable_within_at @[simp] lemma differentiable_at.arctan (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λ x, real.arctan (f x)) x := hc.has_deriv_at.arctan.differentiable_at lemma differentiable_on.arctan (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λ x, real.arctan (f x)) s := λ x h, (hc x h).arctan @[simp] lemma differentiable.arctan (hc : differentiable ℝ f) : differentiable ℝ (λ x, real.arctan (f x)) := λ x, (hc x).arctan lemma deriv_within_arctan (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λ x, real.arctan (f x)) s x = (1 / (1 + (f x)^2)) * (deriv_within f s x) := hf.has_deriv_within_at.arctan.deriv_within hxs @[simp] lemma deriv_arctan (hc : differentiable_at ℝ f x) : deriv (λ x, real.arctan (f x)) x = (1 / (1 + (f x)^2)) * (deriv f x) := hc.has_deriv_at.arctan.deriv end
80370466bc53d4fa3587d005c4c2bf11a410fe59
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/adjunction/limits.lean
b549411e07059c01d9d4aae7720fb0a41e1a4701
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
7,835
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.preserves open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ @[priority 100] -- see Note [lower instance priority] instance left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $ is_colimit.iso_unique_cocone_morphism.hom hc _ ) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := adjunction.left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves E h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves E (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ @[priority 100] -- see Note [lower instance priority] instance right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $ is_limit.iso_unique_cone_morphism.hom hc _) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := adjunction.right_adjoint_preserves_limits E.inv.adjunction -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves E h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves E (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp } /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
7c545f24316edc507a426764809aa04ab41a3797
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/cast/defs.lean
d508ddac3e2daa3f9622fcd52ce486b622b8fcc7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,424
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Gabriel Ebner -/ import algebra.group.defs import algebra.ne_zero /-! # Cast of natural numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the *canonical* homomorphism from the natural numbers into an `add_monoid` with a one. In additive monoids with one, there exists a unique such homomorphism and we store it in the `nat_cast : ℕ → R` field. Preferentially, the homomorphism is written as a coercion. ## Main declarations * `add_monoid_with_one`: Type class for `nat.cast`. * `nat.cast`: Canonical homomorphism `ℕ → R`. -/ universes u set_option old_structure_cmd true /-- The numeral `((0+1)+⋯)+1`. -/ protected def nat.unary_cast {R : Type u} [has_one R] [has_zero R] [has_add R] : ℕ → R | 0 := 0 | (n + 1) := nat.unary_cast n + 1 /-- Type class for the canonical homomorphism `ℕ → R`. -/ @[protect_proj] class has_nat_cast (R : Type u) := (nat_cast : ℕ → R) /-- An `add_monoid_with_one` is an `add_monoid` with a `1`. It also contains data for the unique homomorphism `ℕ → R`. -/ @[protect_proj, ancestor has_nat_cast add_monoid has_one] class add_monoid_with_one (R : Type u) extends has_nat_cast R, add_monoid R, has_one R := (nat_cast := nat.unary_cast) (nat_cast_zero : nat_cast 0 = (0 : R) . control_laws_tac) (nat_cast_succ : ∀ n, nat_cast (n + 1) = (nat_cast n + 1 : R) . control_laws_tac) /-- Canonical homomorphism from `ℕ` to a additive monoid `R` with a `1`. -/ protected def nat.cast {R : Type u} [has_nat_cast R] : ℕ → R := has_nat_cast.nat_cast /-- An `add_comm_monoid_with_one` is an `add_monoid_with_one` satisfying `a + b = b + a`. -/ @[protect_proj, ancestor add_monoid_with_one add_comm_monoid] class add_comm_monoid_with_one (R : Type*) extends add_monoid_with_one R, add_comm_monoid R section variables {R : Type*} [add_monoid_with_one R] /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `R` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ R := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t R (option R)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t R (with_top R)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ R` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ library_note "coercion into rings" attribute [instance, priority 950] coe_base attribute [instance, priority 500] coe_trans namespace nat -- see note [coercion into rings] @[priority 900] instance cast_coe {R} [has_nat_cast R] : has_coe_t ℕ R := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : R) = 0 := add_monoid_with_one.nat_cast_zero -- Lemmas about nat.succ need to get a low priority, so that they are tried last. -- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : R) = n + 1 := add_monoid_with_one.nat_cast_succ _ theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : R) = n + 1 := cast_succ _ @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : R) = ite P (m : R) (n : R) := by { split_ifs; refl, } end nat end namespace nat variables {R : Type*} @[simp, norm_cast] theorem cast_one [add_monoid_with_one R] : ((1 : ℕ) : R) = 1 := by rw [cast_succ, cast_zero, zero_add] @[simp, norm_cast] theorem cast_add [add_monoid_with_one R] (m n : ℕ) : ((m + n : ℕ) : R) = m + n := by induction n; simp [add_succ, add_assoc, nat.add_zero, *] /-- Computationally friendlier cast than `nat.unary_cast`, using binary representation. -/ protected def bin_cast [has_zero R] [has_one R] [has_add R] (n : ℕ) : R := @nat.binary_rec (λ _, R) 0 (λ odd k a, cond odd (a + a + 1) (a + a)) n @[simp] lemma bin_cast_eq [add_monoid_with_one R] (n : ℕ) : (nat.bin_cast n : R) = ((n : ℕ) : R) := begin rw nat.bin_cast, apply binary_rec _ _ n, { rw [binary_rec_zero, cast_zero] }, { intros b k h, rw [binary_rec_eq, h], { cases b; simp [bit, bit0, bit1] }, { simp } }, end @[simp, norm_cast] theorem cast_bit0 [add_monoid_with_one R] (n : ℕ) : ((bit0 n : ℕ) : R) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [add_monoid_with_one R] (n : ℕ) : ((bit1 n : ℕ) : R) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two [add_monoid_with_one R] : ((2 : ℕ) : R) = 2 := by rw [cast_add_one, cast_one, bit0] attribute [simp, norm_cast] int.nat_abs_of_nat end nat /-- `add_monoid_with_one` implementation using unary recursion. -/ @[reducible] protected def add_monoid_with_one.unary {R : Type*} [add_monoid R] [has_one R] : add_monoid_with_one R := { .. ‹has_one R›, .. ‹add_monoid R› } /-- `add_monoid_with_one` implementation using binary recursion. -/ @[reducible] protected def add_monoid_with_one.binary {R : Type*} [add_monoid R] [has_one R] : add_monoid_with_one R := { nat_cast := nat.bin_cast, nat_cast_zero := by simp [nat.bin_cast, nat.cast], nat_cast_succ := λ n, begin simp only [nat.cast], letI : add_monoid_with_one R := add_monoid_with_one.unary, erw [nat.bin_cast_eq, nat.bin_cast_eq, nat.cast_succ], refl, end, .. ‹has_one R›, .. ‹add_monoid R› } namespace ne_zero lemma nat_cast_ne (n : ℕ) (R) [add_monoid_with_one R] [h : ne_zero (n : R)] : (n : R) ≠ 0 := h.out lemma of_ne_zero_coe (R) [add_monoid_with_one R] {n : ℕ} [h : ne_zero (n : R)] : ne_zero n := ⟨by {casesI h, rintro rfl, by simpa using h}⟩ lemma pos_of_ne_zero_coe (R) [add_monoid_with_one R] {n : ℕ} [ne_zero (n : R)] : 0 < n := nat.pos_of_ne_zero (of_ne_zero_coe R).out end ne_zero
371f5d3f3f3c17bb7e65f53f6d324ed2e98d8107
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/integral/mean_inequalities.lean
e323bac178bdf3146e353e04bbf12d2c20943aef
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
19,550
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.integral.lebesgue import analysis.mean_inequalities import analysis.mean_inequalities_pow import measure_theory.function.special_functions.basic /-! # Mean value inequalities for integrals In this file we prove several inequalities on integrals, notably the Hölder inequality and the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`. ## Main results Hölder's inequality for the Lebesgue integral of `ℝ≥0∞` and `ℝ≥0` functions: we prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in two cases, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0 functions. Minkowski's inequality for the Lebesgue integral of measurable functions with `ℝ≥0∞` values: we prove `(∫ (f + g)^p ∂μ) ^ (1/p) ≤ (∫ f^p ∂μ) ^ (1/p) + (∫ g^p ∂μ) ^ (1/p)` for `1 ≤ p`. -/ section lintegral /-! ### Hölder's inequality for the Lebesgue integral of ℝ≥0∞ and nnreal functions We prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in several cases, the first two being useful only to prove the more general results: * `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ℝ≥0∞ functions for which the integrals on the right are equal to 1, * `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ℝ≥0∞ functions for which the integrals on the right are neither ⊤ nor 0, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions. -/ noncomputable theory open_locale classical big_operators nnreal ennreal open measure_theory variables {α : Type*} [measurable_space α] {μ : measure α} namespace ennreal lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_norm : ∫⁻ a, (f a)^p ∂μ = 1) (hg_norm : ∫⁻ a, (g a)^q ∂μ = 1) : ∫⁻ a, (f * g) a ∂μ ≤ 1 := begin calc ∫⁻ (a : α), ((f * g) a) ∂μ ≤ ∫⁻ (a : α), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) ∂μ : lintegral_mono (λ a, young_inequality (f a) (g a) hpq) ... = 1 : begin simp only [div_eq_mul_inv], rw lintegral_add_left', { rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const', hf_norm, hg_norm, ← div_eq_mul_inv, ← div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal], simp [hpq.symm.pos], }, { exact (hf.pow_const _).mul_const _, }, end end /-- Function multiplied by the inverse of its p-seminorm `(∫⁻ f^p ∂μ) ^ 1/p`-/ def fun_mul_inv_snorm (f : α → ℝ≥0∞) (p : ℝ) (μ : measure α) : α → ℝ≥0∞ := λ a, (f a) * ((∫⁻ c, (f c) ^ p ∂μ) ^ (1 / p))⁻¹ lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : ℝ} (f : α → ℝ≥0∞) (hf_nonzero : ∫⁻ a, (f a) ^ p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) {a : α} : f a = (fun_mul_inv_snorm f p μ a) * (∫⁻ c, (f c)^p ∂μ)^(1/p) := by simp [fun_mul_inv_snorm, mul_assoc, ennreal.inv_mul_cancel, hf_nonzero, hf_top] lemma fun_mul_inv_snorm_rpow {p : ℝ} (hp0 : 0 < p) {f : α → ℝ≥0∞} {a : α} : (fun_mul_inv_snorm f p μ a) ^ p = (f a)^p * (∫⁻ c, (f c) ^ p ∂μ)⁻¹ := begin rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)], suffices h_inv_rpow : ((∫⁻ (c : α), f c ^ p ∂μ) ^ (1 / p))⁻¹ ^ p = (∫⁻ (c : α), f c ^ p ∂μ)⁻¹, by rw h_inv_rpow, rw [inv_rpow, ← rpow_mul, one_div_mul_cancel hp0.ne', rpow_one] end lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) : ∫⁻ c, (fun_mul_inv_snorm f p μ c)^p ∂μ = 1 := begin simp_rw fun_mul_inv_snorm_rpow hp0_lt, rw [lintegral_mul_const', ennreal.mul_inv_cancel hf_nonzero hf_top], rwa inv_ne_top end /-- Hölder's inequality in case of finite non-zero integrals -/ lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_nontop : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) (hg_nontop : ∫⁻ a, (g a)^q ∂μ ≠ ⊤) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin let npf := (∫⁻ (c : α), (f c) ^ p ∂μ) ^ (1/p), let nqg := (∫⁻ (c : α), (g c) ^ q ∂μ) ^ (1/q), calc ∫⁻ (a : α), (f * g) a ∂μ = ∫⁻ (a : α), ((fun_mul_inv_snorm f p μ * fun_mul_inv_snorm g q μ) a) * (npf * nqg) ∂μ : begin refine lintegral_congr (λ a, _), rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop, fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply], ring, end ... ≤ npf * nqg : begin rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]), nth_rewrite 1 ←one_mul (npf * nqg), refine mul_le_mul _ (le_refl (npf * nqg)), have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf_nonzero hf_nontop, have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg_nonzero hg_nontop, exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _) hf1 hg1, end end lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0 : 0 ≤ p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : f =ᵐ[μ] 0 := begin rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x, _)), dsimp only, rw [pi.zero_apply, ← not_imp_not], exact λ hx, (rpow_pos_of_nonneg (pos_iff_ne_zero.2 hx) hp0).ne' end lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0 : 0 ≤ p) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : ∫⁻ a, (f * g) a ∂μ = 0 := begin rw ←@lintegral_zero_fun α _ μ, refine lintegral_congr_ae _, suffices h_mul_zero : f * g =ᵐ[μ] 0 * g , by rwa zero_mul at h_mul_zero, have hf_eq_zero : f =ᵐ[μ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0 hf hf_zero, exact hf_eq_zero.mul (ae_eq_refl g), end lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : ℝ} (hp0_lt : 0 < p) (hq0 : 0 ≤ q) {f g : α → ℝ≥0∞} (hf_top : ∫⁻ a, (f a)^p ∂μ = ⊤) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin refine le_trans le_top (le_of_eq _), have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt], rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt], simp [hq0, hg_nonzero], end /-- Hölder's inequality for functions `α → ℝ≥0∞`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem lintegral_mul_le_Lp_mul_Lq (μ : measure α) {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin by_cases hf_zero : ∫⁻ a, (f a) ^ p ∂μ = 0, { refine eq.trans_le _ (zero_le _), exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.nonneg hf hf_zero, }, by_cases hg_zero : ∫⁻ a, (g a) ^ q ∂μ = 0, { refine eq.trans_le _ (zero_le _), rw mul_comm, exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.nonneg hg hg_zero, }, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, }, by_cases hg_top : ∫⁻ a, (g a) ^ q ∂μ = ⊤, { rw [mul_comm, mul_comm ((∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p))], exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, }, -- non-⊤ non-zero case exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hf_top hg_top hf_zero hg_zero end lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ < ⊤) (hg_top : ∫⁻ a, (g a) ^ p ∂μ < ⊤) (hp1 : 1 ≤ p) : ∫⁻ a, ((f + g) a) ^ p ∂μ < ⊤ := begin have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, calc ∫⁻ (a : α), (f a + g a) ^ p ∂μ ≤ ∫⁻ a, ((2:ℝ≥0∞)^(p-1) * (f a) ^ p + (2:ℝ≥0∞)^(p-1) * (g a) ^ p) ∂ μ : begin refine lintegral_mono (λ a, _), dsimp only, have h_zero_lt_half_rpow : (0 : ℝ≥0∞) < (1 / 2) ^ p, { rw [←ennreal.zero_rpow_of_pos hp0_lt], exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, }, have h_rw : (1 / 2) ^ p * (2:ℝ≥0∞) ^ (p - 1) = 1 / 2, { rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top, ←mul_assoc, ←ennreal.mul_rpow_of_nonneg _ _ hp0, one_div, ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow, one_mul, ennreal.rpow_neg_one], }, rw ←ennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _, { rw [mul_add, ← mul_assoc, ← mul_assoc, h_rw, ←ennreal.mul_rpow_of_nonneg _ _ hp0, mul_add], refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ℝ≥0∞) (1/2 : ℝ≥0∞) (f a) (g a) _ hp1, rw [ennreal.div_add_div_same, one_add_one_eq_two, ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], }, { rw ← lt_top_iff_ne_top, refine ennreal.rpow_lt_top_of_nonneg hp0 _, rw [one_div, ennreal.inv_ne_top], exact ennreal.two_ne_zero, }, end ... < ⊤ : begin have h_two : (2 : ℝ≥0∞) ^ (p - 1) ≠ ⊤, from ennreal.rpow_ne_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top, rw [lintegral_add_left', lintegral_const_mul'' _ (hf.pow_const p), lintegral_const_mul' _ _ h_two, ennreal.add_lt_top], { exact ⟨ennreal.mul_lt_top h_two hf_top.ne, ennreal.mul_lt_top h_two hg_top.ne⟩ }, { exact (hf.pow_const p).const_mul _ } end end lemma lintegral_Lp_mul_le_Lq_mul_Lr {α} [measurable_space α] {p q r : ℝ} (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (μ : measure α) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, ((f * g) a)^p ∂μ) ^ (1/p) ≤ (∫⁻ a, (f a)^q ∂μ) ^ (1/q) * (∫⁻ a, (g a)^r ∂μ) ^ (1/r) := begin have hp0_ne : p ≠ 0, from (ne_of_lt hp0_lt).symm, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq, have hq0_ne : q ≠ 0, from (ne_of_lt hq0_lt).symm, have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr], have hr0_ne : r ≠ 0, { have hr_inv_pos : 0 < 1/r, by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt], rw [one_div, _root_.inv_pos] at hr_inv_pos, exact (ne_of_lt hr_inv_pos).symm, }, let p2 := q/p, let q2 := p2.conjugate_exponent, have hp2q2 : p2.is_conjugate_exponent q2, from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]), calc (∫⁻ (a : α), ((f * g) a) ^ p ∂μ) ^ (1 / p) = (∫⁻ (a : α), (f a)^p * (g a)^p ∂μ) ^ (1 / p) : by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0] ... ≤ ((∫⁻ a, (f a)^(p * p2) ∂ μ)^(1/p2) * (∫⁻ a, (g a)^(p * q2) ∂ μ)^(1/q2)) ^ (1/p) : begin refine ennreal.rpow_le_rpow _ (by simp [hp0]), simp_rw ennreal.rpow_mul, exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hp2q2 (hf.pow_const _) (hg.pow_const _) end ... = (∫⁻ (a : α), (f a) ^ q ∂μ) ^ (1 / q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1 / r) : begin rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), ←ennreal.rpow_mul, ←ennreal.rpow_mul], have hpp2 : p * p2 = q, { symmetry, rw [mul_comm, ←div_eq_iff hp0_ne], }, have hpq2 : p * q2 = r, { rw [← inv_inv r, ← one_div, ← one_div, h_one_div_r], field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] }, simp_rw [div_mul_div_comm, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2], end end lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, (f a) * (g a) ^ (p - 1) ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^p ∂μ) ^ (1/q) := begin refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf (hg.pow_const _)) _, by_cases hf_zero_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) = 0, { rw [hf_zero_rpow, zero_mul], exact zero_le _, }, have hf_top_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) ≠ ⊤, { by_contra h, refine hf_top _, have hp_not_neg : ¬ p < 0, by simp [hpq.nonneg], simpa [hpq.pos, hp_not_neg] using h, }, refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _), congr, ext1 a, rw [←ennreal.rpow_mul, hpq.sub_one_mul_conj], end lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, ((f + g) a)^p ∂ μ ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) := begin calc ∫⁻ a, ((f+g) a) ^ p ∂μ ≤ ∫⁻ a, ((f + g) a) * ((f + g) a) ^ (p - 1) ∂μ : begin refine lintegral_mono (λ a, _), dsimp only, by_cases h_zero : (f + g) a = 0, { rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos], exact zero_le _, }, by_cases h_top : (f + g) a = ⊤, { rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top], exact le_top, }, refine le_of_eq _, nth_rewrite 1 ←ennreal.rpow_one ((f + g) a), rw [←ennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right], end ... = ∫⁻ (a : α), f a * (f + g) a ^ (p - 1) ∂μ + ∫⁻ (a : α), g a * (f + g) a ^ (p - 1) ∂μ : begin have h_add_m : ae_measurable (λ (a : α), ((f + g) a) ^ (p-1)) μ, from (hf.add hg).pow_const _, have h_add_apply : ∫⁻ (a : α), (f + g) a * (f + g) a ^ (p - 1) ∂μ = ∫⁻ (a : α), (f a + g a) * (f + g) a ^ (p - 1) ∂μ, from rfl, simp_rw [h_add_apply, add_mul], rw lintegral_add_left' (hf.mul h_add_m), end ... ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) : begin rw add_mul, exact add_le_add (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top) (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top), end end private lemma lintegral_Lp_add_le_aux {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) (h_add_zero : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ 0) (h_add_top : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_not_nonpos : ¬ p ≤ 0, by simp [hpq.pos], have htop_rpow : (∫⁻ a, ((f+g) a) ^ p ∂μ)^(1/p) ≠ ⊤, { by_contra h, exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), }, have h0_rpow : (∫⁻ a, ((f+g) a) ^ p ∂ μ) ^ (1/p) ≠ 0, by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply], suffices h : 1 ≤ (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ -(1/p) * ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)), by rwa [←mul_le_mul_left h0_rpow htop_rpow, ←mul_assoc, ←rpow_add _ _ h_add_zero h_add_top, ←sub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h, have h : ∫⁻ (a : α), ((f+g) a)^p ∂μ ≤ ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)) * (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ (1/q), from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top, have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 ←hpq.inv_add_inv_conj, ring, }, simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top, rpow_one] at h, nth_rewrite 1 mul_comm at h, nth_rewrite 0 ←one_mul (∫⁻ (a : α), ((f+g) a) ^ p ∂μ) at h, rwa [←mul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h, end /-- Minkowski's inequality for functions `α → ℝ≥0∞`: the `ℒp` seminorm of the sum of two functions is bounded by the sum of their `ℒp` seminorms. -/ theorem lintegral_Lp_add_le {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { simp [hf_top, hp_pos], }, by_cases hg_top : ∫⁻ a, (g a) ^ p ∂μ = ⊤, { simp [hg_top, hp_pos], }, by_cases h1 : p = 1, { refine le_of_eq _, simp_rw [h1, one_div_one, ennreal.rpow_one], exact lintegral_add_left' hf _, }, have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt, by_cases h0 : ∫⁻ a, ((f+g) a) ^ p ∂ μ = 0, { rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])], exact zero_le _, }, have htop : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤, { rw ← ne.def at hf_top hg_top, rw ← lt_top_iff_ne_top at hf_top hg_top ⊢, exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg_top hp1, }, exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop, end end ennreal /-- Hölder's inequality for functions `α → ℝ≥0`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin simp_rw [pi.mul_apply, ennreal.coe_mul], exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal, end end lintegral
34e90a187d556a2cc423b15ac1fafb3855e77641
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/elseIfConfusion.lean
d39bc928c1eb49e7d299fa5ab780f1d3bef0cfba
[ "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
175
lean
def tst (x : Nat) : IO Unit := do if x == 0 then IO.println "x is zero" else if x == 1 then IO.println "x is one" throw $ IO.userError "x is not zero" #eval tst 0
c212066f38f6bb2969b8cfa05b159839e0ea14e4
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/tc_inout1.lean
6d1582ef8383c9695ecde980f92328aacaed48fd
[ "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
2,125
lean
universe variables u v /- Type class parameter can be annotated with out_param. Given (C a_1 ... a_n), we replace a_i with a temporary metavariable ?m_i IF 1- a_i is an out_param and it contains metavariables. 3- a_i depends on a_j for j < i, and a_j was replaced with a temporary metavariable ?m_j. This case is needed to make sure the new C-application is type correct. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we solve the unification constraints ?m_i =?= a_i. If we succeed, we return the result. Otherwise, we fail. We also fail if ?m_i is not assigned. Remark: we do not cache results when temporary metavariables ?m_i are used. -/ class is_monoid (α : Type) (op : inout α → α → α) (e : inout α) := (op_assoc : associative op) (left_neutral : ∀ a : α, op e a = a) (right_neutral : ∀ a : α, op a e = a) lemma assoc {α : Type} {op : α → α → α} {e : α} [is_monoid α op e] : ∀ a b c : α, op (op a b) c = op a (op b c) := @is_monoid.op_assoc α op e _ instance nat_add_monoid : is_monoid nat nat.add 0 := sorry instance nat_mul_monoid : is_monoid nat nat.mul 1 := sorry instance int_mul_monoid : is_monoid int int.mul 1 := sorry open tactic run_cmd do M ← to_expr `(is_monoid nat), m₁ ← mk_mvar, m₂ ← mk_mvar, i ← mk_instance (M m₁ m₂), /- found nat_mul_monoid -/ trace i, instantiate_mvars (M m₁ m₂) >>= trace run_cmd do M ← to_expr `(is_monoid nat nat.add), m₁ ← mk_mvar, i ← mk_instance (M m₁), /- found nat_add_monoid -/ trace i, instantiate_mvars (M m₁) >>= trace section local infix + := nat.add example (a b c : nat) : (a + b) + c = a + (b + c) := assoc a b c end section class has_mem2 (α : inout Type u) (γ : Type v) := (mem : α → γ → Prop) def mem2 {α : Type u} {γ : Type v} [has_mem2 α γ] : α → γ → Prop := has_mem2.mem local infix ∈ := mem2 instance (α : Type u) : has_mem2 α (list α) := ⟨list.mem⟩ #check λ a (s : list nat), a ∈ s set_option pp.notation false #check ∀ a ∈ [1, 2, 3], a > 0 end
60dcb182a908dd7bc8f949f239f6affb4915b56c
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/rewrite.lean
460518de443e86f73f8f8b8d65d2c501b2f78ee2
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,385
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.rewrite open tactic example : ∀ x y z a b c : ℕ, true := begin intros, have : x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc ← mk_mapp ``add_monoid.add_assoc [`(ℕ),none], (l,p) ← assoc_rewrite_intl assoc this tgt, note `h none p ), erw h, guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end example : ∀ x y z a b c : ℕ, true := begin intros, have : ∀ y, x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc_rewrite_target this ), guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end variables x y z a b c : ℕ variables h₀ : ∀ (y : ℕ), x + (y + z) = 3 + y variables h₁ : a + (b + x) + y + (z + b + a) ≤ 0 variables h₂ : y + b + c = y + b + a include h₀ h₁ h₂ example : a + (b + x) + y + (z + b + c) ≤ 0 := by { assoc_rw [h₀,h₂] at *, guard_hyp _inst := is_associative ℕ has_add.add, -- keep a local instance of is_associative to cache -- type class queries exact h₁ }
72ce1378daebdecfd0be855a6177d61a7eb4024c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/polynomial/group_ring_action_auto.lean
9d04d5d50509458dbf7c70a9acfe5f5adf83242d
[]
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,890
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.monic import Mathlib.algebra.group_ring_action import Mathlib.algebra.group_action_hom import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Group action on rings applied to polynomials This file contains instances and definitions relating `mul_semiring_action` to `polynomial`. -/ namespace polynomial protected instance mul_semiring_action (M : Type u_1) [monoid M] (R : Type u_2) [semiring R] [mul_semiring_action M R] : mul_semiring_action M (polynomial R) := mul_semiring_action.mk sorry sorry protected instance faithful_mul_semiring_action (M : Type u_1) [monoid M] (R : Type u_2) [semiring R] [faithful_mul_semiring_action M R] : faithful_mul_semiring_action M (polynomial R) := faithful_mul_semiring_action.mk sorry @[simp] theorem coeff_smul' {M : Type u_1} [monoid M] {R : Type u_2} [semiring R] [mul_semiring_action M R] (m : M) (p : polynomial R) (n : ℕ) : coeff (m • p) n = m • coeff p n := coeff_map (mul_semiring_action.to_semiring_hom M R m) n @[simp] theorem smul_C {M : Type u_1} [monoid M] {R : Type u_2} [semiring R] [mul_semiring_action M R] (m : M) (r : R) : m • coe_fn C r = coe_fn C (m • r) := map_C (mul_semiring_action.to_semiring_hom M R m) @[simp] theorem smul_X {M : Type u_1} [monoid M] {R : Type u_2} [semiring R] [mul_semiring_action M R] (m : M) : m • X = X := map_X (mul_semiring_action.to_semiring_hom M R m) theorem smul_eval_smul {M : Type u_1} [monoid M] (S : Type u_3) [comm_semiring S] [mul_semiring_action M S] (m : M) (f : polynomial S) (x : S) : eval (m • x) (m • f) = m • eval x f := sorry theorem eval_smul' (S : Type u_3) [comm_semiring S] (G : Type u_4) [group G] [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : eval (g • x) f = g • eval x (g⁻¹ • f) := eq.mpr (id (Eq._oldrec (Eq.refl (eval (g • x) f = g • eval x (g⁻¹ • f))) (Eq.symm (smul_eval_smul S g (g⁻¹ • f) x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (eval (g • x) f = eval (g • x) (g • g⁻¹ • f))) (smul_inv_smul g f))) (Eq.refl (eval (g • x) f))) theorem smul_eval (S : Type u_3) [comm_semiring S] (G : Type u_4) [group G] [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : eval x (g • f) = g • eval (g⁻¹ • x) f := eq.mpr (id (Eq._oldrec (Eq.refl (eval x (g • f) = g • eval (g⁻¹ • x) f)) (Eq.symm (smul_eval_smul S g f (g⁻¹ • x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (eval x (g • f) = eval (g • g⁻¹ • x) (g • f))) (smul_inv_smul g x))) (Eq.refl (eval x (g • f)))) end polynomial /-- the product of `(X - g • x)` over distinct `g • x`. -/ def prod_X_sub_smul (G : Type u_2) [group G] [fintype G] (R : Type u_3) [comm_ring R] [mul_semiring_action G R] (x : R) : polynomial R := finset.prod finset.univ fun (g : quotient_group.quotient (mul_action.stabilizer G x)) => polynomial.X - coe_fn polynomial.C (mul_action.of_quotient_stabilizer G x g) theorem prod_X_sub_smul.monic (G : Type u_2) [group G] [fintype G] (R : Type u_3) [comm_ring R] [mul_semiring_action G R] (x : R) : polynomial.monic (prod_X_sub_smul G R x) := sorry theorem prod_X_sub_smul.eval (G : Type u_2) [group G] [fintype G] (R : Type u_3) [comm_ring R] [mul_semiring_action G R] (x : R) : polynomial.eval x (prod_X_sub_smul G R x) = 0 := sorry theorem prod_X_sub_smul.smul (G : Type u_2) [group G] [fintype G] (R : Type u_3) [comm_ring R] [mul_semiring_action G R] (x : R) (g : G) : g • prod_X_sub_smul G R x = prod_X_sub_smul G R x := sorry theorem prod_X_sub_smul.coeff (G : Type u_2) [group G] [fintype G] (R : Type u_3) [comm_ring R] [mul_semiring_action G R] (x : R) (g : G) (n : ℕ) : g • polynomial.coeff (prod_X_sub_smul G R x) n = polynomial.coeff (prod_X_sub_smul G R x) n := sorry namespace mul_semiring_action_hom /-- An equivariant map induces an equivariant map on polynomials. -/ protected def polynomial {M : Type u_1} [monoid M] {P : Type u_2} [comm_semiring P] [mul_semiring_action M P] {Q : Type u_3} [comm_semiring Q] [mul_semiring_action M Q] (g : mul_semiring_action_hom M P Q) : mul_semiring_action_hom M (polynomial P) (polynomial Q) := mk (polynomial.map ↑g) sorry sorry sorry sorry sorry @[simp] theorem coe_polynomial {M : Type u_1} [monoid M] {P : Type u_2} [comm_semiring P] [mul_semiring_action M P] {Q : Type u_3} [comm_semiring Q] [mul_semiring_action M Q] (g : mul_semiring_action_hom M P Q) : ⇑(mul_semiring_action_hom.polynomial g) = polynomial.map ↑g := rfl end Mathlib
3271436fd28f52623266754f6465acf1526e3725
4fa161becb8ce7378a709f5992a594764699e268
/src/data/padics/hensel.lean
6e8b2234b3a003399b6b1beed4ab510a002425ae
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
21,544
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_integers import topology.metric_space.cau_seq_filter import analysis.specific_limits import topology.algebra.polynomial /-! # Hensel's lemma on ℤ_p This file proves Hensel's lemma on ℤ_p, roughly following Keith Conrad's writeup: <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> Hensel's lemma gives a simple condition for the existence of a root of a polynomial. The proof and motivation are described in the paper [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019]. ## References * <http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/hensel.pdf> * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/Hensel%27s_lemma> ## Tags p-adic, p adic, padic, p-adic integer -/ noncomputable theory open_locale classical topological_space -- We begin with some general lemmas that are used below in the computation. lemma padic_polynomial_dist {p : ℕ} [fact p.prime] (F : polynomial ℤ_[p]) (x y : ℤ_[p]) : ∥F.eval x - F.eval y∥ ≤ ∥x - y∥ := let ⟨z, hz⟩ := F.eval_sub_factor x y in calc ∥F.eval x - F.eval y∥ = ∥z∥ * ∥x - y∥ : by simp [hz] ... ≤ 1 * ∥x - y∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥x - y∥ : by simp open filter metric private lemma comp_tendsto_lim {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} (ncs : cau_seq ℤ_[p] norm) : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 (F.eval ncs.lim)) := (F.continuous_eval.tendsto _).comp ncs.tendsto_limit section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} {a : ℤ_[p]} (ncs_der_val : ∀ n, ∥F.derivative.eval (ncs n)∥ = ∥F.derivative.eval a∥) include ncs_der_val private lemma ncs_tendsto_const : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 ∥F.derivative.eval a∥) := by convert tendsto_const_nhds; ext; rw ncs_der_val private lemma ncs_tendsto_lim : tendsto (λ i, ∥F.derivative.eval (ncs i)∥) at_top (𝓝 (∥F.derivative.eval ncs.lim∥)) := tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) (comp_tendsto_lim _) private lemma norm_deriv_eq : ∥F.derivative.eval ncs.lim∥ = ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot ncs_tendsto_lim ncs_tendsto_const end section parameters {p : ℕ} [fact p.prime] {ncs : cau_seq ℤ_[p] norm} {F : polynomial ℤ_[p]} (hnorm : tendsto (λ i, ∥F.eval (ncs i)∥) at_top (𝓝 0)) include hnorm private lemma tendsto_zero_of_norm_tendsto_zero : tendsto (λ i, F.eval (ncs i)) at_top (𝓝 0) := tendsto_iff_norm_tendsto_zero.2 (by simpa using hnorm) lemma limit_zero_of_norm_tendsto_zero : F.eval ncs.lim = 0 := tendsto_nhds_unique at_top_ne_bot (comp_tendsto_lim _) tendsto_zero_of_norm_tendsto_zero end section hensel open nat parameters {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) (hnsol : F.eval a ≠ 0) include hnorm /-- `T` is an auxiliary value that is used to control the behavior of the polynomial `F`. -/ private def T : ℝ := ∥(F.eval a / (F.derivative.eval a)^2 : ℚ_[p])∥ private lemma deriv_sq_norm_pos : 0 < ∥F.derivative.eval a∥ ^ 2 := lt_of_le_of_lt (norm_nonneg _) hnorm private lemma deriv_sq_norm_ne_zero : ∥F.derivative.eval a∥^2 ≠ 0 := ne_of_gt deriv_sq_norm_pos private lemma deriv_norm_ne_zero : ∥F.derivative.eval a∥ ≠ 0 := λ h, deriv_sq_norm_ne_zero (by simp [*, _root_.pow_two]) private lemma deriv_norm_pos : 0 < ∥F.derivative.eval a∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm deriv_norm_ne_zero) private lemma deriv_ne_zero : F.derivative.eval a ≠ 0 := mt norm_eq_zero.2 deriv_norm_ne_zero private lemma T_def : T = ∥F.eval a∥ / ∥F.derivative.eval a∥^2 := calc T = ∥F.eval a∥ / ∥((F.derivative.eval a)^2 : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval a∥ / ∥(F.derivative.eval a)^2∥ : by simp [norm, padic_norm_z] ... = ∥F.eval a∥ / ∥(F.derivative.eval a)∥^2 : by simp [pow, monoid.pow] private lemma T_lt_one : T < 1 := let h := (div_lt_one_iff_lt deriv_sq_norm_pos).2 hnorm in by rw T_def; apply h private lemma T_pow {n : ℕ} (hn : n > 0) : T ^ n < 1 := have T ^ n ≤ T ^ 1, from pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) (succ_le_of_lt hn), lt_of_le_of_lt (by simpa) T_lt_one private lemma T_pow' (n : ℕ) : T ^ (2 ^ n) < 1 := (T_pow (nat.pow_pos (by norm_num) _)) private lemma T_pow_nonneg (n : ℕ) : T ^ n ≥ 0 := pow_nonneg (norm_nonneg _) _ /-- We will construct a sequence of elements of ℤ_p satisfying successive values of `ih`. -/ private def ih (n : ℕ) (z : ℤ_[p]) : Prop := ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∥F.eval z∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) private lemma ih_0 : ih 0 a := ⟨ rfl, by simp [T_def, mul_div_cancel' _ (ne_of_gt (deriv_sq_norm_pos hnorm))] ⟩ private lemma calc_norm_le_one {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1 := calc ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ = ∥(↑(F.eval z) : ℚ_[p])∥ / ∥(↑(F.derivative.eval z) : ℚ_[p])∥ : normed_field.norm_div _ _ ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : by simp [hz.1] ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ ... ≤ 1 : mul_le_one (padic_norm_z.le_one _) (T_pow_nonneg _) (le_of_lt (T_pow' _)) private lemma calc_deriv_dist {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) (hz1 : ∥z1∥ = ∥F.eval z∥ / ∥F.derivative.eval a∥) {n} (hz : ih n z) : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥ := calc ∥F.derivative.eval z' - F.derivative.eval z∥ ≤ ∥z' - z∥ : padic_polynomial_dist _ _ _ ... = ∥z1∥ : by simp only [sub_eq_add_neg, add_assoc, hz', add_add_neg_cancel'_right, norm_neg] ... = ∥F.eval z∥ / ∥F.derivative.eval a∥ : hz1 ... ≤ ∥F.derivative.eval a∥^2 * T^(2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 hz.2 ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel deriv_norm_ne_zero _ ... < ∥F.derivative.eval a∥ : (mul_lt_iff_lt_one_right deriv_norm_pos).2 (T_pow (pow_pos (by norm_num) _)) private def calc_eval_z' {z z' z1 : ℤ_[p]} (hz' : z' = z - z1) {n} (hz : ih n z) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : {q : ℤ_[p] // F.eval z' = q * z1^2} := have hdzne' : (↑(F.derivative.eval z) : ℚ_[p]) ≠ 0, from have hdzne : F.derivative.eval z ≠ 0, from mt norm_eq_zero.2 (by rw hz.1; apply deriv_norm_ne_zero; assumption), λ h, hdzne $ subtype.ext.2 h, let ⟨q, hq⟩ := F.binom_expansion z (-z1) in have ∥(↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)) : ℚ_[p])∥ ≤ 1, by {rw padic_norm_e.mul, apply mul_le_one, apply padic_norm_z.le_one, apply norm_nonneg, apply h1}, have F.derivative.eval z * (-z1) = -F.eval z, from calc F.derivative.eval z * (-z1) = (F.derivative.eval z) * -⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩ : by rw [hzeq] ... = -((F.derivative.eval z) * ⟨↑(F.eval z) / ↑(F.derivative.eval z), h1⟩) : by simp [subtype.coe_ext] ... = -(⟨↑(F.derivative.eval z) * (↑(F.eval z) / ↑(F.derivative.eval z)), this⟩) : subtype.ext.2 $ by simp ... = -(F.eval z) : by simp [mul_div_cancel' _ hdzne'], have heq : F.eval z' = q * z1^2, by simpa [this, hz'] using hq, ⟨q, heq⟩ private def calc_eval_z'_norm {z z' z1 : ℤ_[p]} {n} (hz : ih n z) {q} (heq : F.eval z' = q * z1^2) (h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1) (hzeq : z1 = ⟨_, h1⟩) : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)) := calc ∥F.eval z'∥ = ∥q∥ * ∥z1∥^2 : by simp [heq] ... ≤ 1 * ∥z1∥^2 : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (pow_nonneg (norm_nonneg _) _) ... = ∥F.eval z∥^2 / ∥F.derivative.eval a∥^2 : by simp [hzeq, hz.1, div_pow] ... ≤ (∥F.derivative.eval a∥^2 * T^(2^n))^2 / ∥F.derivative.eval a∥^2 : (div_le_div_right deriv_sq_norm_pos).2 (pow_le_pow_of_le_left (norm_nonneg _) hz.2 _) ... = (∥F.derivative.eval a∥^2)^2 * (T^(2^n))^2 / ∥F.derivative.eval a∥^2 : by simp only [_root_.mul_pow] ... = ∥F.derivative.eval a∥^2 * (T^(2^n))^2 : div_sq_cancel deriv_sq_norm_ne_zero _ ... = ∥F.derivative.eval a∥^2 * T^(2^(n + 1)) : by rw [←pow_mul]; refl set_option eqn_compiler.zeta true /-- Given `z : ℤ_[p]` satisfying `ih n z`, construct `z' : ℤ_[p]` satisfying `ih (n+1) z'`. We need the hypothesis `ih n z`, since otherwise `z'` is not necessarily an integer. -/ private def ih_n {n : ℕ} {z : ℤ_[p]} (hz : ih n z) : {z' : ℤ_[p] // ih (n+1) z'} := have h1 : ∥(↑(F.eval z) : ℚ_[p]) / ↑(F.derivative.eval z)∥ ≤ 1, from calc_norm_le_one hz, let z1 : ℤ_[p] := ⟨_, h1⟩, z' : ℤ_[p] := z - z1 in ⟨ z', have hdist : ∥F.derivative.eval z' - F.derivative.eval z∥ < ∥F.derivative.eval a∥, from calc_deriv_dist rfl (by simp [z1, hz.1]) hz, have hfeq : ∥F.derivative.eval z'∥ = ∥F.derivative.eval a∥, begin rw [sub_eq_add_neg, ← hz.1, ←norm_neg (F.derivative.eval z)] at hdist, have := padic_norm_z.eq_of_norm_add_lt_right hdist, rwa [norm_neg, hz.1] at this end, let ⟨q, heq⟩ := calc_eval_z' rfl hz h1 rfl in have hnle : ∥F.eval z'∥ ≤ ∥F.derivative.eval a∥^2 * T^(2^(n+1)), from calc_eval_z'_norm hz heq h1 rfl, ⟨hfeq, hnle⟩⟩ set_option eqn_compiler.zeta false -- why doesn't "noncomputable theory" stick here? private noncomputable def newton_seq_aux : Π n : ℕ, {z : ℤ_[p] // ih n z} | 0 := ⟨a, ih_0⟩ | (k+1) := ih_n (newton_seq_aux k).2 private def newton_seq (n : ℕ) : ℤ_[p] := (newton_seq_aux n).1 private lemma newton_seq_deriv_norm (n : ℕ) : ∥F.derivative.eval (newton_seq n)∥ = ∥F.derivative.eval a∥ := (newton_seq_aux n).2.1 private lemma newton_seq_norm_le (n : ℕ) : ∥F.eval (newton_seq n)∥ ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) := (newton_seq_aux n).2.2 private lemma newton_seq_norm_eq (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ := by simp [newton_seq, newton_seq_aux, ih_n, sub_eq_add_neg, add_comm] private lemma newton_seq_succ_dist (n : ℕ) : ∥newton_seq (n+1) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := calc ∥newton_seq (n+1) - newton_seq n∥ = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval (newton_seq n)∥ : newton_seq_norm_eq _ ... = ∥F.eval (newton_seq n)∥ / ∥F.derivative.eval a∥ : by rw newton_seq_deriv_norm ... ≤ ∥F.derivative.eval a∥^2 * T ^ (2^n) / ∥F.derivative.eval a∥ : (div_le_div_right deriv_norm_pos).2 (newton_seq_norm_le _) ... = ∥F.derivative.eval a∥ * T^(2^n) : div_sq_cancel (ne_of_gt deriv_norm_pos) _ include hnsol private lemma T_pos : T > 0 := begin rw T_def, exact div_pos_of_pos_of_pos (norm_pos_iff.2 hnsol) (deriv_sq_norm_pos hnorm) end private lemma newton_seq_succ_dist_weak (n : ℕ) : ∥newton_seq (n+2) - newton_seq (n+1)∥ < ∥F.eval a∥ / ∥F.derivative.eval a∥ := have 2 ≤ 2^(n+1), from have _, from pow_le_pow (by norm_num : 1 ≤ 2) (nat.le_add_left _ _ : 1 ≤ n + 1), by simpa using this, calc ∥newton_seq (n+2) - newton_seq (n+1)∥ ≤ ∥F.derivative.eval a∥ * T^(2^(n+1)) : newton_seq_succ_dist _ ... ≤ ∥F.derivative.eval a∥ * T^2 : mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) ... < ∥F.derivative.eval a∥ * T^1 : mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_one T_pos T_lt_one (by norm_num)) deriv_norm_pos ... = ∥F.eval a∥ / ∥F.derivative.eval a∥ : begin rw [T, _root_.pow_two, _root_.pow_one, normed_field.norm_div, ←mul_div_assoc, padic_norm_e.mul], apply mul_div_mul_left, apply deriv_norm_ne_zero; assumption end private lemma newton_seq_dist_aux (n : ℕ) : ∀ k : ℕ, ∥newton_seq (n + k) - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) | 0 := begin simp, apply mul_nonneg, {apply norm_nonneg}, {apply T_pow_nonneg} end | (k+1) := have 2^n ≤ 2^(n+k), by {rw [←nat.pow_eq_pow, ←nat.pow_eq_pow], apply pow_le_pow, norm_num, apply nat.le_add_right}, calc ∥newton_seq (n + (k + 1)) - newton_seq n∥ = ∥newton_seq ((n + k) + 1) - newton_seq n∥ : by rw add_assoc ... = ∥(newton_seq ((n + k) + 1) - newton_seq (n+k)) + (newton_seq (n+k) - newton_seq n)∥ : by rw ←sub_add_sub_cancel ... ≤ max (∥newton_seq ((n + k) + 1) - newton_seq (n+k)∥) (∥newton_seq (n+k) - newton_seq n∥) : padic_norm_z.nonarchimedean _ _ ... ≤ max (∥F.derivative.eval a∥ * T^(2^((n + k)))) (∥F.derivative.eval a∥ * T^(2^n)) : max_le_max (newton_seq_succ_dist _) (newton_seq_dist_aux _) ... = ∥F.derivative.eval a∥ * T^(2^n) : max_eq_right $ mul_le_mul_of_nonneg_left (pow_le_pow_of_le_one (norm_nonneg _) (le_of_lt T_lt_one) this) (norm_nonneg _) private lemma newton_seq_dist {n k : ℕ} (hnk : n ≤ k) : ∥newton_seq k - newton_seq n∥ ≤ ∥F.derivative.eval a∥ * T^(2^n) := have hex : ∃ m, k = n + m, from exists_eq_add_of_le hnk, let ⟨_, hex'⟩ := hex in by rw hex'; apply newton_seq_dist_aux; assumption private lemma newton_seq_dist_to_a : ∀ n : ℕ, 0 < n → ∥newton_seq n - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ | 1 h := by simp [sub_eq_add_neg, add_assoc, newton_seq, newton_seq_aux, ih_n]; apply normed_field.norm_div | (k+2) h := have hlt : ∥newton_seq (k+2) - newton_seq (k+1)∥ < ∥newton_seq (k+1) - a∥, by rw newton_seq_dist_to_a (k+1) (succ_pos _); apply newton_seq_succ_dist_weak; assumption, have hne' : ∥newton_seq (k + 2) - newton_seq (k+1)∥ ≠ ∥newton_seq (k+1) - a∥, from ne_of_lt hlt, calc ∥newton_seq (k + 2) - a∥ = ∥(newton_seq (k + 2) - newton_seq (k+1)) + (newton_seq (k+1) - a)∥ : by rw ←sub_add_sub_cancel ... = max (∥newton_seq (k + 2) - newton_seq (k+1)∥) (∥newton_seq (k+1) - a∥) : padic_norm_z.add_eq_max_of_ne hne' ... = ∥newton_seq (k+1) - a∥ : max_eq_right_of_lt hlt ... = ∥polynomial.eval a F∥ / ∥polynomial.eval a (polynomial.derivative F)∥ : newton_seq_dist_to_a (k+1) (succ_pos _) private lemma bound' : tendsto (λ n : ℕ, ∥F.derivative.eval a∥ * T^(2^n)) at_top (𝓝 0) := begin rw ←mul_zero (∥F.derivative.eval a∥), exact tendsto_const_nhds.mul (tendsto.comp (tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) (T_lt_one hnorm)) (nat.tendsto_pow_at_top_at_top_of_one_lt (by norm_num))) end private lemma bound : ∀ {ε}, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → ∥F.derivative.eval a∥ * T^(2^n) < ε := have mtn : ∀ n : ℕ, ∥polynomial.eval a (polynomial.derivative F)∥ * T ^ (2 ^ n) ≥ 0, from λ n, mul_nonneg (norm_nonneg _) (T_pow_nonneg _), begin have := bound' hnorm hnsol, simp [tendsto, nhds] at this, intros ε hε, cases this (ball 0 ε) (mem_ball_self hε) (is_open_ball) with N hN, existsi N, intros n hn, simpa [normed_field.norm_mul, real.norm_eq_abs, abs_of_nonneg (mtn n)] using hN _ hn end private lemma bound'_sq : tendsto (λ n : ℕ, ∥F.derivative.eval a∥^2 * T^(2^n)) at_top (𝓝 0) := begin rw [←mul_zero (∥F.derivative.eval a∥), _root_.pow_two], simp only [mul_assoc], apply tendsto.mul, { apply tendsto_const_nhds }, { apply bound', assumption } end private theorem newton_seq_is_cauchy : is_cau_seq norm newton_seq := begin intros ε hε, cases bound hnorm hnsol hε with N hN, existsi N, intros j hj, apply lt_of_le_of_lt, { apply newton_seq_dist _ _ hj, assumption }, { apply hN, apply le_refl } end private def newton_cau_seq : cau_seq ℤ_[p] norm := ⟨_, newton_seq_is_cauchy⟩ private def soln : ℤ_[p] := newton_cau_seq.lim private lemma soln_spec {ε : ℝ} (hε : ε > 0) : ∃ (N : ℕ), ∀ {i : ℕ}, i ≥ N → ∥soln - newton_cau_seq i∥ < ε := setoid.symm (cau_seq.equiv_lim newton_cau_seq) _ hε private lemma soln_deriv_norm : ∥F.derivative.eval soln∥ = ∥F.derivative.eval a∥ := norm_deriv_eq newton_seq_deriv_norm private lemma newton_seq_norm_tendsto_zero : tendsto (λ i, ∥F.eval (newton_cau_seq i)∥) at_top (𝓝 0) := squeeze_zero (λ _, norm_nonneg _) newton_seq_norm_le bound'_sq private lemma newton_seq_dist_tendsto : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 (∥F.eval a∥ / ∥F.derivative.eval a∥)) := tendsto.congr' (suffices ∃ k, ∀ n ≥ k, ∥F.eval a∥ / ∥F.derivative.eval a∥ = ∥newton_cau_seq n - a∥, by simpa, ⟨1, λ _ hx, (newton_seq_dist_to_a _ hx).symm⟩) (tendsto_const_nhds) private lemma newton_seq_dist_tendsto' : tendsto (λ n, ∥newton_cau_seq n - a∥) at_top (𝓝 ∥soln - a∥) := (continuous_norm.tendsto _).comp (newton_cau_seq.tendsto_limit.sub tendsto_const_nhds) private lemma soln_dist_to_a : ∥soln - a∥ = ∥F.eval a∥ / ∥F.derivative.eval a∥ := tendsto_nhds_unique at_top_ne_bot newton_seq_dist_tendsto' newton_seq_dist_tendsto private lemma soln_dist_to_a_lt_deriv : ∥soln - a∥ < ∥F.derivative.eval a∥ := begin rw soln_dist_to_a, apply div_lt_of_mul_lt_of_pos, { apply deriv_norm_pos; assumption }, { rwa _root_.pow_two at hnorm } end private lemma eval_soln : F.eval soln = 0 := limit_zero_of_norm_tendsto_zero newton_seq_norm_tendsto_zero private lemma soln_unique (z : ℤ_[p]) (hev : F.eval z = 0) (hnlt : ∥z - a∥ < ∥F.derivative.eval a∥) : z = soln := have soln_dist : ∥z - soln∥ < ∥F.derivative.eval a∥, from calc ∥z - soln∥ = ∥(z - a) + (a - soln)∥ : by rw sub_add_sub_cancel ... ≤ max (∥z - a∥) (∥a - soln∥) : padic_norm_z.nonarchimedean _ _ ... < ∥F.derivative.eval a∥ : max_lt hnlt (by rw norm_sub_rev; apply soln_dist_to_a_lt_deriv), let h := z - soln, ⟨q, hq⟩ := F.binom_expansion soln h in have (F.derivative.eval soln + q * h) * h = 0, from eq.symm (calc 0 = F.eval (soln + h) : by simp [hev, h] ... = F.derivative.eval soln * h + q * h^2 : by rw [hq, eval_soln, zero_add] ... = (F.derivative.eval soln + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval soln + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval soln = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval soln∥ (calc ∥F.derivative.eval soln∥ = ∥(-q) * h∥ : by rw this ... ≤ 1 * ∥h∥ : by rw [padic_norm_z.mul]; exact mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... = ∥z - soln∥ : by simp [h] ... < ∥F.derivative.eval soln∥ : by rw soln_deriv_norm; apply soln_dist), eq_of_sub_eq_zero (by rw ←this; refl) end hensel variables {p : ℕ} [fact p.prime] {F : polynomial ℤ_[p]} {a : ℤ_[p]} private lemma a_soln_is_unique (ha : F.eval a = 0) (z' : ℤ_[p]) (hz' : F.eval z' = 0) (hnormz' : ∥z' - a∥ < ∥F.derivative.eval a∥) : z' = a := let h := z' - a, ⟨q, hq⟩ := F.binom_expansion a h in have (F.derivative.eval a + q * h) * h = 0, from eq.symm (calc 0 = F.eval (a + h) : show 0 = F.eval (a + (z' - a)), by rw add_comm; simp [hz'] ... = F.derivative.eval a * h + q * h^2 : by rw [hq, ha, zero_add] ... = (F.derivative.eval a + q * h) * h : by rw [_root_.pow_two, right_distrib, mul_assoc]), have h = 0, from by_contradiction $ λ hne, have F.derivative.eval a + q * h = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hne, have F.derivative.eval a = (-q) * h, by simpa using eq_neg_of_add_eq_zero this, lt_irrefl ∥F.derivative.eval a∥ (calc ∥F.derivative.eval a∥ = ∥q∥*∥h∥ : by simp [this] ... ≤ 1*∥h∥ : mul_le_mul_of_nonneg_right (padic_norm_z.le_one _) (norm_nonneg _) ... < ∥F.derivative.eval a∥ : by simpa [h]), eq_of_sub_eq_zero (by rw ←this; refl) variable (hnorm : ∥F.eval a∥ < ∥F.derivative.eval a∥^2) include hnorm private lemma a_is_soln (ha : F.eval a = 0) : F.eval a = 0 ∧ ∥a - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval a∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = a := ⟨ha, by simp; apply deriv_norm_pos; apply hnorm, rfl, a_soln_is_unique ha⟩ lemma hensels_lemma : ∃ z : ℤ_[p], F.eval z = 0 ∧ ∥z - a∥ < ∥F.derivative.eval a∥ ∧ ∥F.derivative.eval z∥ = ∥F.derivative.eval a∥ ∧ ∀ z', F.eval z' = 0 → ∥z' - a∥ < ∥F.derivative.eval a∥ → z' = z := if ha : F.eval a = 0 then ⟨a, a_is_soln hnorm ha⟩ else by refine ⟨soln _ _, eval_soln _ _, soln_dist_to_a_lt_deriv _ _, soln_deriv_norm _ _, soln_unique _ _⟩; assumption
1a7111b0d999130449472527e6ec00b18cba4fd2
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/star/module.lean
17e971650b8e8f074e65831c803171295e8d4121
[ "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
5,944
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Frédéric Dupuis -/ import algebra.star.self_adjoint import algebra.module.equiv import linear_algebra.prod /-! # The star operation, bundled as a star-linear equiv > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `star_linear_equiv`, which is the star operation bundled as a star-linear map. It is defined on a star algebra `A` over the base ring `R`. This file also provides some lemmas that need `algebra.module.basic` imported to prove. ## TODO - Define `star_linear_equiv` for noncommutative `R`. We only the commutative case for now since, in the noncommutative case, the ring hom needs to reverse the order of multiplication. This requires a ring hom of type `R →+* Rᵐᵒᵖ`, which is very undesirable in the commutative case. One way out would be to define a new typeclass `is_op R S` and have an instance `is_op R R` for commutative `R`. - Also note that such a definition involving `Rᵐᵒᵖ` or `is_op R S` would require adding the appropriate `ring_hom_inv_pair` instances to be able to define the semilinear equivalence. -/ section smul_lemmas variables {R M : Type*} @[simp] lemma star_nat_cast_smul [semiring R] [add_comm_monoid M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_int_cast_smul [ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_nat_cast_smul [division_semiring R] [add_comm_monoid M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_int_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_rat_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℚ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_rat_cast_smul (star_add_equiv : M ≃+ M) _ _ _ x @[simp] lemma star_rat_smul {R : Type*} [add_comm_group R] [star_add_monoid R] [module ℚ R] (x : R) (n : ℚ) : star (n • x) = n • star x := map_rat_smul (star_add_equiv : R ≃+ R) _ _ end smul_lemmas /-- If `A` is a module over a commutative `R` with compatible actions, then `star` is a semilinear equivalence. -/ @[simps] def star_linear_equiv (R : Type*) {A : Type*} [comm_ring R] [star_ring R] [semiring A] [star_ring A] [module R A] [star_module R A] : A ≃ₗ⋆[R] A := { to_fun := star, map_smul' := star_smul, .. star_add_equiv } variables (R : Type*) (A : Type*) [semiring R] [star_semigroup R] [has_trivial_star R] [add_comm_group A] [module R A] [star_add_monoid A] [star_module R A] /-- The self-adjoint elements of a star module, as a submodule. -/ def self_adjoint.submodule : submodule R A := { smul_mem' := λ r x, (is_self_adjoint.all _).smul, ..self_adjoint A } /-- The skew-adjoint elements of a star module, as a submodule. -/ def skew_adjoint.submodule : submodule R A := { smul_mem' := skew_adjoint.smul_mem, ..skew_adjoint A } variables {A} [invertible (2 : R)] /-- The self-adjoint part of an element of a star module, as a linear map. -/ @[simps] def self_adjoint_part : A →ₗ[R] self_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x + star x), by simp only [self_adjoint.mem_iff, star_smul, add_comm, star_add_monoid.star_add, star_inv', star_bit0, star_one, star_star, star_inv_of (2 : R), star_trivial]⟩, map_add' := λ x y, by { ext, simp [add_add_add_comm] }, map_smul' := λ r x, by { ext, simp [←mul_smul, show ⅟ 2 * r = r * ⅟ 2, from commute.inv_of_left (commute.one_left r).bit0_left] } } /-- The skew-adjoint part of an element of a star module, as a linear map. -/ @[simps] def skew_adjoint_part : A →ₗ[R] skew_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x - star x), by simp only [skew_adjoint.mem_iff, star_smul, star_sub, star_star, star_trivial, ←smul_neg, neg_sub]⟩, map_add' := λ x y, by { ext, simp only [sub_add, ←smul_add, sub_sub_eq_add_sub, star_add, add_subgroup.coe_mk, add_subgroup.coe_add] }, map_smul' := λ r x, by { ext, simp [←mul_smul, ←smul_sub, show r * ⅟ 2 = ⅟ 2 * r, from commute.inv_of_right (commute.one_right r).bit0_right] } } lemma star_module.self_adjoint_part_add_skew_adjoint_part (x : A) : (self_adjoint_part R x : A) + skew_adjoint_part R x = x := by simp only [smul_sub, self_adjoint_part_apply_coe, smul_add, skew_adjoint_part_apply_coe, add_add_sub_cancel, inv_of_two_smul_add_inv_of_two_smul] variables (A) /-- The decomposition of elements of a star module into their self- and skew-adjoint parts, as a linear equivalence. -/ @[simps] def star_module.decompose_prod_adjoint : A ≃ₗ[R] self_adjoint A × skew_adjoint A := linear_equiv.of_linear ((self_adjoint_part R).prod (skew_adjoint_part R)) ((self_adjoint.submodule R A).subtype.coprod (skew_adjoint.submodule R A).subtype) (by ext; simp) (linear_map.ext $ star_module.self_adjoint_part_add_skew_adjoint_part R) @[simp] lemma algebra_map_star_comm {R A : Type*} [comm_semiring R] [star_ring R] [semiring A] [star_semigroup A] [algebra R A] [star_module R A] (r : R) : algebra_map R A (star r) = star (algebra_map R A r) := by simp only [algebra.algebra_map_eq_smul_one, star_smul, star_one]
9b07a12b29eb1014fe308e00d94c28afb9627843
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/integral/lebesgue.lean
68dcde814ee355c92dde983dee7c0d148bd90412
[ "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
123,946
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import measure_theory.measure.mutually_singular import measure_theory.constructions.borel_space import algebra.indicator_function import algebra.support import dynamics.ergodic.measure_preserving /-! # Lebesgue integral for `ℝ≥0∞`-valued functions We define simple functions and show that each Borel measurable function on `ℝ≥0∞` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ℝ≥0∞`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ℝ≥0∞`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ℝ≥0∞` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal function (support) open_locale classical topological_space big_operators nnreal ennreal measure_theory namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_set_fiber' : ∀ x, measurable_set (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) (λ _, α → β) := ⟨to_fun⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : (f : α → β) = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma measurable_set_fiber (f : α →ₛ β) (x : β) : measurable_set (f ⁻¹' {x}) := f.measurable_set_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset _ theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm lemma exists_forall_le [nonempty β] [preorder β] [is_directed β (≤)] (f : α →ₛ β) : ∃ C, ∀ x, f x ≤ C := f.range.exists_le.imp $ λ C, forall_range_iff.1 /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, measurable_set.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ default⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma range_const_subset (α) [measurable_space α] (b : β) : (const α b).range ⊆ {b} := finset.coe_subset.1 $ by simp lemma measurable_set_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, measurable_set {a | r a b}) : measurable_set {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact measurable_set.bUnion f.finite_range.countable (λ b _, measurable_set.inter (h b) (f.measurable_set_fiber _)) end @[measurability] theorem measurable_set_preimage (f : α →ₛ β) (s) : measurable_set (f ⁻¹' s) := measurable_set_cut (λ _ b, b ∈ s) f (λ b, measurable_set.const (b ∈ s)) /-- A simple function is measurable -/ @[measurability] protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, measurable_set_preimage f s @[measurability] protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) : ae_measurable f μ := f.measurable.ae_measurable protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) : ∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (λ _ _, f.measurable_set_fiber _) lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) : ∑ y in f.range, μ (f ⁻¹' {y}) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : measurable_set s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : measurable_set s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : measurable_set s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : measurable_set sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ measurable_set.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ measurable_set.empty f g = g := coe_injective $ by simp lemma support_indicator [has_zero β] {s : set α} (hs : measurable_set s) (f : α →ₛ β) : function.support (f.piecewise s hs (simple_func.const α 0)) = s ∩ function.support f := set.support_indicator lemma range_indicator {s : set α} (hs : measurable_set s) (hs_nonempty : s.nonempty) (hs_ne_univ : s ≠ univ) (x y : β) : (piecewise s hs (const α x) (const α y)).range = {x, y} := begin ext1 z, rw [mem_range, set.mem_range, finset.mem_insert, finset.mem_singleton], simp_rw piecewise_apply, split; intro h, { obtain ⟨a, haz⟩ := h, by_cases has : a ∈ s, { left, simp only [has, function.const_apply, if_true, coe_const] at haz, exact haz.symm, }, { right, simp only [has, function.const_apply, if_false, coe_const] at haz, exact haz.symm, }, }, { cases h, { obtain ⟨a, has⟩ : ∃ a, a ∈ s, from hs_nonempty, exact ⟨a, by simpa [has] using h.symm⟩, }, { obtain ⟨a, has⟩ : ∃ a, a ∉ s, { by_contra' h, refine hs_ne_univ _, ext1 a, simp [h a], }, exact ⟨a, by simpa [has] using h.symm⟩, }, }, end lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.measurable_set_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.measurable_set_cut (λ a b, g b a = c) $ λ b, (g b).measurable_set_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp only [coe_range, coe_map, finset.coe_image, range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, measurable_set_fiber' := λ z, hgm (f.measurable_set_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- Extend a `simple_func` along a measurable embedding: `f₁.extend g hg f₂` is the function `F : β →ₛ γ` such that `F ∘ g = f₁` and `F y = f₂ y` whenever `y ∉ range g`. -/ def extend [measurable_space β] (f₁ : α →ₛ γ) (g : α → β) (hg : measurable_embedding g) (f₂ : β →ₛ γ) : β →ₛ γ := { to_fun := function.extend g f₁ f₂, finite_range' := (f₁.finite_range.union $ f₂.finite_range.subset (image_subset_range _ _)).subset (range_extend_subset _ _ _), measurable_set_fiber' := begin letI : measurable_space γ := ⊤, haveI : measurable_singleton_class γ := ⟨λ _, trivial⟩, exact λ x, hg.measurable_extend f₁.measurable f₂.measurable (measurable_set_singleton _) end } @[simp] lemma extend_apply [measurable_space β] (f₁ : α →ₛ γ) {g : α → β} (hg : measurable_embedding g) (f₂ : β →ₛ γ) (x : α) : (f₁.extend g hg f₂) (g x) = f₁ x := function.extend_apply hg.injective _ _ _ @[simp] lemma extend_comp_eq' [measurable_space β] (f₁ : α →ₛ γ) {g : α → β} (hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂) ∘ g = f₁ := funext $ λ x, extend_apply _ _ _ _ @[simp] lemma extend_comp_eq [measurable_space β] (f₁ : α →ₛ γ) {g : α → β} (hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂).comp g hg.measurable = f₁ := coe_injective $ extend_comp_eq' _ _ _ /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (s ×ˢ t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] @[simp] lemma range_eq_empty_of_is_empty {β} [hα : is_empty α] (f : α →ₛ β) : f.range = ∅ := begin rw ← finset.not_nonempty_iff_eq_empty, by_contra, obtain ⟨y, hy_mem⟩ := h, rw [simple_func.mem_range, set.mem_range] at hy_mem, obtain ⟨x, hxy⟩ := hy_mem, rw is_empty_iff at hα, exact hα x, end lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl theorem map_add [has_add β] [has_add γ] {g : β → γ} (hg : ∀ x y, g (x + y) = g x + g y) (f₁ f₂ : α →ₛ β) : (f₁ + f₂).map g = f₁.map g + f₂.map g := ext $ λ x, hg _ _ instance [add_monoid β] : add_monoid (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [has_sub β] : has_sub (α →ₛ β) := ⟨λf g, (f.map (has_sub.sub)).seq g⟩ @[simp, norm_cast] lemma coe_sub [has_sub β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl lemma sub_apply [has_sub β] (f g : α →ₛ β) (x : α) : (f - g) x = f x - g x := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [module K β] : module K (α →ₛ β) := function.injective.module K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_rfl, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [has_le β] [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le } instance [has_le β] [order_top β] : order_top (α →ₛ β) := { top := const α ⊤, le_top := λf a, le_top } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [has_le β] [bounded_order β] : bounded_order (α →ₛ β) := { .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup β] [order_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : measurable_set s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬measurable_set s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : measurable_set s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : measurable_set s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ≥0∞) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : measurable_set s) (a) : restrict f s a = indicator s f a := by simp only [f.coe_restrict hs] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : measurable_set s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht, inter_comm] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : measurable_set s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : measurable_set s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : measurable_set s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : measurable_set s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup β] [order_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ℝ≥0∞` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf measurable_set_Ici) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ℝ≥0∞`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ℝ≥0∞ := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = real.to_nnreal q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ℝ≥0∞` by a sequence of simple functions. -/ def eapprox : (α → ℝ≥0∞) → ℕ → α →ₛ ℝ≥0∞ := approx ennreal_rat_embed lemma eapprox_lt_top (f : α → ℝ≥0∞) (n : ℕ) (a : α) : eapprox f n a < ∞ := begin simp only [eapprox, approx, finset_sup_apply, finset.sup_lt_iff, with_top.zero_lt_top, finset.mem_range, ennreal.bot_eq_zero, restrict], assume b hb, split_ifs, { simp only [coe_zero, coe_piecewise, piecewise_eq_indicator, coe_const], calc {a : α | ennreal_rat_embed b ≤ f a}.indicator (λ x, ennreal_rat_embed b) a ≤ ennreal_rat_embed b : indicator_le_self _ _ a ... < ⊤ : ennreal.coe_lt_top }, { exact with_top.zero_lt_top }, end @[mono] lemma monotone_eapprox (f : α → ℝ≥0∞) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ℝ≥0∞) (hf : measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ℝ≥0∞) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (real.to_nnreal q : ℝ≥0∞) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_rfl }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ℝ≥0∞} {g : α → γ} {n : ℕ} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : α → ℝ≥0∞) = (eapprox f n : γ →ₛ ℝ≥0∞) ∘ g := funext $ assume a, approx_comp a hf hg /-- Approximate a function `α → ℝ≥0∞` by a series of simple functions taking their values in `ℝ≥0`. -/ def eapprox_diff (f : α → ℝ≥0∞) : ∀ (n : ℕ), α →ₛ ℝ≥0 | 0 := (eapprox f 0).map ennreal.to_nnreal | (n+1) := (eapprox f (n+1) - eapprox f n).map ennreal.to_nnreal lemma sum_eapprox_diff (f : α → ℝ≥0∞) (n : ℕ) (a : α) : (∑ k in finset.range (n+1), (eapprox_diff f k a : ℝ≥0∞)) = eapprox f n a := begin induction n with n IH, { simp only [nat.nat_zero_eq_zero, finset.sum_singleton, finset.range_one], refl }, { rw [finset.sum_range_succ, nat.succ_eq_add_one, IH, eapprox_diff, coe_map, function.comp_app, coe_sub, pi.sub_apply, ennreal.coe_to_nnreal, add_tsub_cancel_of_le (monotone_eapprox f (nat.le_succ _) _)], apply (lt_of_le_of_lt _ (eapprox_lt_top f (n+1) a)).ne, rw tsub_le_iff_right, exact le_self_add }, end lemma tsum_eapprox_diff (f : α → ℝ≥0∞) (hf : measurable f) (a : α) : (∑' n, (eapprox_diff f n a : ℝ≥0∞)) = f a := by simp_rw [ennreal.tsum_eq_supr_nat' (tendsto_add_at_top_nat 1), sum_eapprox_diff, supr_eapprox_apply f hf a] end eapprox end measurable section measure variables {m : measurable_space α} {μ ν : measure α} /-- Integral of a simple function whose codomain is `ℝ≥0∞`. -/ def lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (μ : measure α) : ℝ≥0∞ := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end lemma lintegral_eq_of_subset' (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞} (hs : f.range \ {0} ⊆ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := f.lintegral_eq_of_subset $ λ x hfx _, hs $ finset.mem_sdiff.2 ⟨f.mem_range_self x, mt finset.mem_singleton.1 hfx⟩ /-- Calculate the integral of `(g ∘ f)`, where `g : β → ℝ≥0∞` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ℝ≥0∞) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ℝ≥0∞) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ℝ≥0∞) (x : ℝ≥0∞) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ℝ≥0∞` as a bilinear map. -/ def lintegralₗ {m : measurable_space α} : (α →ₛ ℝ≥0∞) →ₗ[ℝ≥0∞] measure α →ₗ[ℝ≥0∞] ℝ≥0∞ := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ℝ≥0∞).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ℝ≥0∞) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ℝ≥0∞) (c : ℝ≥0∞) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero [measurable_space α] (f : α →ₛ ℝ≥0∞) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {m : measurable_space α} {ι} (f : α →ₛ ℝ≥0∞) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.measurable_set_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ℝ≥0∞) {s : set α} (hs : measurable_set s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then λ _, by simp only [f.restrict_apply hs, indicator_of_mem hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.measurable_set_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ℝ≥0∞) {s : set α} (hs : measurable_set s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ℝ≥0∞) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], casesI is_empty_or_nonempty α, { simp [μ.eq_zero_of_is_empty] }, { simp [preimage_const_of_mem] }, end lemma const_lintegral_restrict (c : ℝ≥0∞) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply measurable_set.univ, univ_inter] lemma restrict_const_lintegral (c : ℝ≥0∞) {s : set α} (hs : measurable_set s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ℝ≥0∞) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, mul_le_mul_right' _ _), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ℝ≥0∞} (hfg : f ≤ g) (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.measurable_set_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ℝ≥0∞} {g : β →ₛ ℝ≥0∞} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ℝ≥0∞} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map' {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ℝ≥0∞) (g : β →ₛ ℝ≥0∞) (m' : α → β) (eq : ∀ a, f a = g (m' a)) (h : ∀s, measurable_set s → μ' s = μ (m' ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.measurable_set_preimage _)).symm } lemma lintegral_map {β} [measurable_space β] (g : β →ₛ ℝ≥0∞) {f : α → β} (hf : measurable f) : g.lintegral (measure.map f μ) = (g.comp f hf).lintegral μ := eq.symm $ lintegral_map' _ _ f (λ a, rfl) (λ s hs, measure.map_apply hf hs) end measure section fin_meas_supp open finset function lemma support_eq [measurable_space α] [has_zero β] (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [mem_support, set.mem_preimage, mem_filter, mem_range_self, true_and, exists_prop, mem_Union, set.mem_range, mem_singleton_iff, exists_eq_right'] variables {m : measurable_space α} [has_zero β] [has_zero γ] {μ : measure α} {f : α →ₛ β} lemma measurable_set_support [measurable_space α] (f : α →ₛ β) : measurable_set (support f) := by { rw f.support_eq, exact finset.measurable_set_bUnion _ (λ y hy, measurable_set_fiber _ _), } /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp {m : measurable_space α} (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support : f.fin_meas_supp μ ↔ μ (support f) < ∞ := iff.rfl lemma fin_meas_supp_iff : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, (H y (finset.mem_filter.1 hy).2).ne } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ∞ := fin_meas_supp_iff.1 h y hy protected lemma map {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a ≠ ∞) : f.lintegral μ < ∞ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_ne a ∞ with rfl|ha, { simp only [ae_iff, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_ne_top ha (fin_meas_supp_iff.1 hm _ ha0).ne } } end lemma of_lintegral_ne_top {f : α →ₛ ℝ≥0∞} (h : f.lintegral μ ≠ ∞) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [f.lintegral_eq_of_subset' (finset.subset_insert b _)] at h, refine ennreal.lt_top_of_mul_ne_top_right _ hb, exact (lt_top_of_sum_ne_top h (finset.mem_insert_self _ _)).ne end lemma iff_lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hf : ∀ᵐ a ∂μ, f a ≠ ∞) : f.fin_meas_supp μ ↔ f.lintegral μ < ∞ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_ne_top h.ne⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_add` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : measurable_set s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_add : ∀ ⦃f g : simple_func α γ⦄, disjoint (support f) (support g) → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 measurable_set.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.measurable_set_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_add _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, rintro y, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } end end simple_func section lintegral open simple_func variables {m : measurable_space α} {μ ν : measure α} /-- The **lower Lebesgue integral** of a function `f` with respect to a measure `μ`. -/ @[irreducible] def lintegral {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : ℝ≥0∞ := ⨆ (g : α →ₛ ℝ≥0∞) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := begin rw lintegral, exact le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_rfl) (le_supr_of_le f $ le_supr_of_le le_rfl le_rfl) end @[mono] lemma lintegral_mono' {m : measurable_space α} ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := begin rw [lintegral, lintegral], exact supr_le_supr (λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩) end lemma lintegral_mono ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := begin refine lintegral_mono _, intro a, rw ennreal.coe_le_coe, exact h a, end lemma supr_lintegral_measurable_le_eq_lintegral (f : α → ℝ≥0∞) : (⨆ (g : α → ℝ≥0∞) (g_meas : measurable g) (hg : g ≤ f), ∫⁻ a, g a ∂μ) = ∫⁻ a, f a ∂μ := begin apply le_antisymm, { exact supr_le (λ i, supr_le (λ hi, supr_le (λ h'i, lintegral_mono h'i))) }, { rw lintegral, refine bsupr_le (λ i hi, le_supr_of_le i (le_supr_of_le i.measurable (le_supr_of_le hi _))), exact le_of_eq (i.lintegral_eq_lintegral _).symm }, end lemma lintegral_mono_set {m : measurable_space α} ⦃μ : measure α⦄ {s t : set α} {f : α → ℝ≥0∞} (hst : s ⊆ t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (measure.restrict_mono hst (le_refl μ)) (le_refl f) lemma lintegral_mono_set' {m : measurable_space α} ⦃μ : measure α⦄ {s t : set α} {f : α → ℝ≥0∞} (hst : s ≤ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ := lintegral_mono' (measure.restrict_mono' hst (le_refl μ)) (le_refl f) lemma monotone_lintegral {m : measurable_space α} (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ℝ≥0∞) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] @[simp] lemma lintegral_one : ∫⁻ a, (1 : ℝ≥0∞) ∂μ = μ univ := by rw [lintegral_const, one_mul] lemma set_lintegral_const (s : set α) (c : ℝ≥0∞) : ∫⁻ a in s, c ∂μ = c * μ s := by rw [lintegral_const, measure.restrict_apply_univ] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [set_lintegral_const, one_mul] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ℝ≥0∞` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal {m : measurable_space α} (f : α → ℝ≥0∞) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ℝ≥0∞)).lintegral μ) := begin rw lintegral, refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ℝ≥0∞), le_rfl⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ∞, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ℝ≥0∞) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {∞}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {∞}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {∞}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.measurable_set_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end lemma exists_simple_func_forall_lintegral_sub_lt_of_pos {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) → (map coe (ψ - φ)).lintegral μ < ε := begin rw lintegral_eq_nnreal at h, have := ennreal.lt_add_right h hε, erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩], simp_rw [lt_supr_iff, supr_lt_iff, supr_le_iff] at this, rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩, refine ⟨φ, hle, λ ψ hψ, _⟩, have : (map coe φ).lintegral μ ≠ ∞, from ne_top_of_le_ne_top h (le_bsupr φ hle), rw [← add_lt_add_iff_left this, ← add_lintegral, ← map_add @ennreal.coe_add], refine (hb _ (λ x, le_trans _ (max_le (hle x) (hψ x)))).trans_lt hbφ, norm_cast, simp only [add_apply, sub_apply, add_tsub_eq_max] end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ℝ≥0∞) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ℝ≥0∞) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } lemma lintegral_mono_ae {f g : α → ℝ≥0∞} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, rw [lintegral, lintegral], refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma set_lintegral_mono_ae {s : set α} {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := lintegral_mono_ae $ (ae_restrict_iff $ measurable_set_le hf hg).2 hfg lemma set_lintegral_mono {s : set α} {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hfg : ∀ x ∈ s, f x ≤ g x) : ∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ := set_lintegral_mono_ae hf hg (ae_of_all _ hfg) lemma lintegral_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ℝ≥0∞} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ℝ≥0∞} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [measure.restrict_congr_set h] lemma set_lintegral_congr_fun {f g : α → ℝ≥0∞} {s : set α} (hs : measurable_set s) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in s, g x ∂μ := by { rw lintegral_congr_ae, rw eventually_eq, rwa ae_restrict_iff' hs, } /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : ℝ≥0 → ℝ≥0∞ := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_le (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ℝ≥0∞) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ℝ≥0∞, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, measurable_set {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_set_le (simple_func.measurable _) (hf n), calc (r:ℝ≥0∞) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... = ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : by simp only [(eq _).symm] ... = ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr (directed_of_sup $ mono x), ennreal.mul_supr], end ... = ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin rw [ennreal.finset_sum_supr_nat], assume p i j h, exact mul_le_mul_left' (measure_mono $ mono p h) _ end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), simp only [map_apply] at h_meas, simp only [coe_map, restrict_apply _ (h_meas _), (∘)], exact indicator_apply_le id, end end /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. Version with ae_measurable functions. -/ theorem lintegral_supr' {f : ℕ → α → ℝ≥0∞} (hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin simp_rw ←supr_apply, let p : α → (ℕ → ℝ≥0∞) → Prop := λ x f', monotone f', have hp : ∀ᵐ x ∂μ, p x (λ i, f i x), from h_mono, have h_ae_seq_mono : monotone (ae_seq hf p), { intros n m hnm x, by_cases hx : x ∈ ae_seq_set hf p, { exact ae_seq.prop_of_mem_ae_seq_set hf hx hnm, }, { simp only [ae_seq, hx, if_false], exact le_rfl, }, }, rw lintegral_congr_ae (ae_seq.supr hf hp).symm, simp_rw supr_apply, rw @lintegral_supr _ _ μ _ (ae_seq.measurable hf p) h_ae_seq_mono, congr, exact funext (λ n, lintegral_congr_ae (ae_seq.ae_seq_n_eq_fun_n_ae hf hp n)), end /-- Monotone convergence theorem expressed with limits -/ theorem lintegral_tendsto_of_tendsto_of_monotone {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞} (hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) (h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 $ F x)) : tendsto (λ n, ∫⁻ x, f n x ∂μ) at_top (𝓝 $ ∫⁻ x, F x ∂μ) := begin have : monotone (λ n, ∫⁻ x, f n x ∂μ) := λ i j hij, lintegral_mono_ae (h_mono.mono $ λ x hx, hx hij), suffices key : ∫⁻ x, F x ∂μ = ⨆n, ∫⁻ x, f n x ∂μ, { rw key, exact tendsto_at_top_supr this }, rw ← lintegral_supr' hf h_mono, refine lintegral_congr_ae _, filter_upwards [h_mono, h_tendsto] with _ hx_mono hx_tendsto using tendsto_nhds_unique hx_tendsto (tendsto_at_top_supr hx_mono), end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ℝ≥0∞} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ℝ≥0∞) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ℝ≥0∞) a ∂μ) : begin rw [lintegral_supr], { measurability, }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. This lemma states states this fact in terms of `ε` and `δ`. -/ lemma exists_pos_set_lintegral_lt_of_measure_lt {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (hε : ε ≠ 0) : ∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε := begin rcases exists_between hε.bot_lt with ⟨ε₂, hε₂0 : 0 < ε₂, hε₂ε⟩, rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩, rcases exists_simple_func_forall_lintegral_sub_lt_of_pos h hε₁0.ne' with ⟨φ, hle, hφ⟩, rcases φ.exists_forall_le with ⟨C, hC⟩, use [(ε₂ - ε₁) / C, ennreal.div_pos_iff.2 ⟨(tsub_pos_iff_lt.2 hε₁₂).ne', ennreal.coe_ne_top⟩], refine λ s hs, lt_of_le_of_lt _ hε₂ε, simp only [lintegral_eq_nnreal, supr_le_iff], intros ψ hψ, calc (map coe ψ).lintegral (μ.restrict s) ≤ (map coe φ).lintegral (μ.restrict s) + (map coe (ψ - φ)).lintegral (μ.restrict s) : begin rw [← simple_func.add_lintegral, ← simple_func.map_add @ennreal.coe_add], refine simple_func.lintegral_mono (λ x, _) le_rfl, simp [-ennreal.coe_add, add_tsub_eq_max, le_max_right] end ... ≤ (map coe φ).lintegral (μ.restrict s) + ε₁ : begin refine add_le_add le_rfl (le_trans _ (hφ _ hψ).le), exact simple_func.lintegral_mono le_rfl measure.restrict_le_self end ... ≤ (simple_func.const α (C : ℝ≥0∞)).lintegral (μ.restrict s) + ε₁ : by { mono*, exacts [λ x, coe_le_coe.2 (hC x), le_rfl, le_rfl] } ... = C * μ s + ε₁ : by simp [← simple_func.lintegral_eq_lintegral] ... ≤ C * ((ε₂ - ε₁) / C) + ε₁ : by { mono*, exacts [le_rfl, hs.le, le_rfl] } ... ≤ (ε₂ - ε₁) + ε₁ : add_le_add mul_div_le le_rfl ... = ε₂ : tsub_add_cancel_of_le hε₁₂.le, end /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma tendsto_set_lintegral_zero {ι} {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞) {l : filter ι} {s : ι → set α} (hl : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫⁻ x in s i, f x ∂μ) l (𝓝 0) := begin simp only [ennreal.nhds_zero, tendsto_infi, tendsto_principal, mem_Iio, ← pos_iff_ne_zero] at hl ⊢, intros ε ε0, rcases exists_pos_set_lintegral_lt_of_measure_lt h ε0.ne' with ⟨δ, δ0, hδ⟩, exact (hl δ δ0).mono (λ i, hδ _) end @[simp] lemma lintegral_add {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ℝ≥0∞) a) + (⨆n, (eapprox g n : α → ℝ≥0∞) a) ∂μ) : by simp only [supr_eapprox_apply, hf, hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ℝ≥0∞) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { measurability, }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_add' {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, hf.mk f a + hg.mk g a ∂μ) : lintegral_congr_ae (eventually_eq.add hf.ae_eq_mk hg.ae_eq_mk) ... = (∫⁻ a, hf.mk f a ∂μ) + (∫⁻ a, hg.mk g a ∂μ) : lintegral_add hf.measurable_mk hg.measurable_mk ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : begin congr' 1, { exact lintegral_congr_ae hf.ae_eq_mk.symm }, { exact lintegral_congr_ae hg.ae_eq_mk.symm }, end lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ℝ≥0∞) a ∂μ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ℝ≥0∞) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {m : measurable_space α} {ι} (f : α → ℝ≥0∞) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left le_rfl) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right le_rfl)⟩ end @[simp] lemma lintegral_add_measure {m : measurable_space α} (f : α → ℝ≥0∞) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure {m : measurable_space α} (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂(0 : measure α) = 0 := bot_unique $ by simp [lintegral] lemma set_lintegral_empty (f : α → ℝ≥0∞) : ∫⁻ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, lintegral_zero_measure] lemma set_lintegral_univ (f : α → ℝ≥0∞) : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw measure.restrict_univ lemma set_lintegral_measure_zero (s : set α) (f : α → ℝ≥0∞) (hs' : μ s = 0) : ∫⁻ x in s, f x ∂μ = 0 := begin convert lintegral_zero_measure _, exact measure.restrict_eq_zero.2 hs', end lemma lintegral_finset_sum (s : finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin induction s using finset.induction_on with a s has ih, { simp }, { simp only [finset.sum_insert has], rw [finset.forall_mem_insert] at hf, rw [lintegral_add hf.1 (s.measurable_sum hf.2), ih hf.2] } end @[simp] lemma lintegral_const_mul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact mul_le_mul_left' (monotone_eapprox _ h _) _ } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _), rw [A, B, lintegral_const_mul _ hf.measurable_mk], end lemma lintegral_const_mul_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw [← simple_func.const_mul_lintegral, lintegral], refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) le_rfl), exact mul_le_mul_left' (hs x) _ end lemma lintegral_const_mul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using mul_le_mul_left' this r end lemma lintegral_mul_const (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] lemma lintegral_mul_const_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β} {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul'' _ hg, lintegral_mul_const'' _ hf] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ℝ≥0∞) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ℝ≥0∞) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) le_rfl, by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_rfl⟩, simp [hφ x, hs, indicator_le_indicator] } end lemma set_lintegral_eq_const {f : α → ℝ≥0∞} (hf : measurable f) (r : ℝ≥0∞) : ∫⁻ x in {x | f x = r}, f x ∂μ = r * μ {x | f x = r} := begin have : ∀ᵐ x ∂μ, x ∈ {x | f x = r} → f x = r := ae_of_all μ (λ _ hx, hx), rw [set_lintegral_congr_fun _ this], dsimp, rw [lintegral_const, measure.restrict_apply measurable_set.univ, set.univ_inter], exact hf (measurable_set_singleton r) end /-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/ lemma mul_meas_ge_le_lintegral {f : α → ℝ≥0∞} (hf : measurable f) (ε : ℝ≥0∞) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : measurable_set {a : α | ε ≤ f a }, from hf measurable_set_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], exact indicator_apply_le id end lemma lintegral_eq_top_of_measure_eq_top_pos {f : α → ℝ≥0∞} (hf : measurable f) (hμf : 0 < μ {x | f x = ∞}) : ∫⁻ x, f x ∂μ = ∞ := eq_top_iff.mpr $ calc ∞ = ∞ * μ {x | ∞ ≤ f x} : by simp [mul_eq_top, hμf.ne.symm] ... ≤ ∫⁻ x, f x ∂μ : mul_meas_ge_le_lintegral hf ∞ lemma meas_ge_le_lintegral_div {f : α → ℝ≥0∞} (hf : measurable f) {ε : ℝ≥0∞} (hε : ε ≠ 0) (hε' : ε ≠ ∞) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } @[simp] lemma lintegral_eq_zero_iff {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← nonpos_iff_eq_zero, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end @[simp] lemma lintegral_eq_zero_iff' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin have : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, rw [this, lintegral_eq_zero_iff hf.measurable_mk], exact ⟨λ H, hf.ae_eq_mk.trans H, λ H, hf.ae_eq_mk.symm.trans H⟩ end lemma lintegral_pos_iff_support {f : α → ℝ≥0∞} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_nat_of_le_succ $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, tsub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact tsub_add_cancel_of_le hx end lemma lintegral_sub_le (f g : α → ℝ≥0∞) (hf : measurable f) (hg : measurable g) (h : f ≤ᵐ[μ] g) : ∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ := begin by_cases hfi : ∫⁻ x, f x ∂μ = ∞, { rw [hfi, ennreal.sub_top], exact bot_le }, { rw lintegral_sub hg hf hfi h, refl' } end lemma lintegral_strict_mono_of_ae_le_of_ae_lt_on {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) {s : set α} (hμs : μ s ≠ 0) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := begin rw [← tsub_pos_iff_lt, ← lintegral_sub hg hf hfi h_le], by_contra hnlt, rw [not_lt, nonpos_iff_eq_zero, lintegral_eq_zero_iff (hg.sub hf), filter.eventually_eq] at hnlt, simp only [ae_iff, tsub_eq_zero_iff_le, pi.zero_apply, not_lt, not_le] at hnlt h, refine hμs _, push_neg at h, have hs_eq : s = {a : α | a ∈ s ∧ g a ≤ f a} ∪ {a : α | a ∈ s ∧ f a < g a}, { ext1 x, simp_rw [set.mem_union, set.mem_set_of_eq, ← not_le], tauto, }, rw hs_eq, refine measure_union_null h (measure_mono_null _ hnlt), simp, end lemma lintegral_strict_mono {f g : α → ℝ≥0∞} (hμ : μ ≠ 0) (hf : measurable f) (hg : measurable g) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, f x < g x) : ∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ := begin rw [ne.def, ← measure.measure_univ_eq_zero] at hμ, refine lintegral_strict_mono_of_ae_le_of_ae_lt_on hf hg hfi (ae_le_of_ae_lt h) hμ _, simpa using h, end lemma set_lintegral_strict_mono {f g : α → ℝ≥0∞} {s : set α} (hsm : measurable_set s) (hs : μ s ≠ 0) (hf : measurable f) (hg : measurable g) (hfi : ∫⁻ x in s, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) : ∫⁻ x in s, f x ∂μ < ∫⁻ x in s, g x ∂μ := lintegral_strict_mono (by simp [hs]) hf hg hfi ((ae_restrict_iff' hsm).mpr h) /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 le_rfl), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 le_rfl, (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (ne_top_of_le_ne_top h_fin $ lintegral_mono (assume a, infi_le _ _)) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, tsub_le_tsub le_rfl ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_rfl}, {exact le_trans (h n) ih} end, congr_arg supr $ funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (ne_top_of_le_ne_top h_fin $ lintegral_mono_ae $ h_mono n) (h_mono n) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) (h_anti : antitone f) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_anti n.le_succ) h_fin /-- Known as Fatou's lemma, version with `ae_measurable` functions -/ lemma lintegral_liminf_le' {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, ae_measurable (f n) μ) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr' (assume n, ae_measurable_binfi _ (countable_encodable _) h_meas) (ae_of_all μ (assume a n m hnm, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = at_top.liminf (λ n, ∫⁻ a, f n a ∂μ) : filter.liminf_eq_supr_infi_of_nat.symm /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := lintegral_liminf_le' (λ n, (h_meas n).ae_measurable) lemma limsup_lintegral_le {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ ≠ ∞) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine ne_top_of_le_ne_top h_fin (lintegral_mono_ae _), refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for nonnegative functions which are just almost everywhere measurable. -/ lemma tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := begin have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk, simp_rw this, apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin, { have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := λ n, (hF_meas n).ae_eq_mk.symm, have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this, filter_upwards [this, h_lim] with a H H', simp_rw H, exact H', }, { assume n, filter_upwards [h_bound n, (hF_meas n).ae_eq_mk] with a H H', rwa H' at H, }, end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} [l.is_countably_generated] {F : ι → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ ≠ ∞) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw tendsto_iff_seq_tendsto, intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ℝ≥0∞} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ := begin casesI is_empty_or_nonempty β, { simp [supr_of_empty] }, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ℝ≥0∞} (hf : ∀i, measurable (f i)) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ (λ i _, hf i)] }, { assume b, exact finset.measurable_sum _ (λ i _, hf i) }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ℝ≥0∞) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le le_rfl end lemma lintegral_union {f : α → ℝ≥0∞} {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (hAB : disjoint A B) : ∫⁻ a in A ∪ B, f a ∂μ = ∫⁻ a in A, f a ∂μ + ∫⁻ a in B, f a ∂μ := begin rw [set.union_eq_Union, lintegral_Union, tsum_bool, add_comm], { simp only [to_bool_false_eq_ff, to_bool_true_eq_tt, cond] }, { intros i, exact measurable_set.cond hA hB }, { rwa pairwise_disjoint_on_bool } end lemma lintegral_add_compl (f : α → ℝ≥0∞) {A : set α} (hA : measurable_set A) : ∫⁻ x in A, f x ∂μ + ∫⁻ x in Aᶜ, f x ∂μ = ∫⁻ x, f x ∂μ := by rw [← lintegral_add_measure, measure.restrict_add_restrict_compl hA] lemma lintegral_map {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], congr' with n : 1, convert simple_func.lintegral_map _ hg, ext1 x, simp only [eapprox_comp hf hg, coe_comp] end lemma lintegral_map' {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β} (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) : lintegral_congr_ae hf.ae_eq_mk ... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_map hf.measurable_mk hg ... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) lemma lintegral_map_le {mβ : measurable_space β} (f : β → ℝ≥0∞) {g : α → β} (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) ≤ ∫⁻ a, f (g a) ∂μ := begin rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine bsupr_le (λ i hi, supr_le (λ h'i, _)), refine le_supr_of_le (i ∘ g) (le_supr_of_le (hi.comp hg) _), exact le_supr_of_le (λ x, h'i (g x)) (le_of_eq (lintegral_map hi hg)) end lemma lintegral_comp [measurable_space β] {f : β → ℝ≥0∞} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ℝ≥0∞} {g : α → β} {s : set β} (hs : measurable_set s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] /-- If `g : α → β` is a measurable embedding and `f : β → ℝ≥0∞` is any function (not necessarily measurable), then `∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ`. Compare with `lintegral_map` wich applies to any measurable `g : α → β` but requires that `f` is measurable as well. -/ lemma _root_.measurable_embedding.lintegral_map [measurable_space β] {g : α → β} (hg : measurable_embedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin rw [lintegral, lintegral], refine le_antisymm (bsupr_le $ λ f₀ hf₀, _) (bsupr_le $ λ f₀ hf₀, _), { rw [simple_func.lintegral_map _ hg.measurable], have : (f₀.comp g hg.measurable : α → ℝ≥0∞) ≤ f ∘ g, from λ x, hf₀ (g x), exact le_supr_of_le (comp f₀ g hg.measurable) (le_supr _ this) }, { rw [← f₀.extend_comp_eq hg (const _ 0), ← simple_func.lintegral_map, ← simple_func.lintegral_eq_lintegral, ← lintegral], refine lintegral_mono_ae (hg.ae_map_iff.2 $ eventually_of_forall $ λ x, _), exact (extend_apply _ _ _ _).trans_le (hf₀ _) } end /-- The `lintegral` transforms appropriately under a measurable equivalence `g : α ≃ᵐ β`. (Compare `lintegral_map`, which applies to a wider class of functions `g : α → β`, but requires measurability of the function being integrated.) -/ lemma lintegral_map_equiv [measurable_space β] (f : β → ℝ≥0∞) (g : α ≃ᵐ β) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := g.measurable_embedding.lintegral_map f lemma measure_preserving.lintegral_comp {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) {f : β → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, lintegral_map hf hg.measurable] lemma measure_preserving.lintegral_comp_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) : ∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν := by rw [← hg.map_eq, hge.lintegral_map] lemma measure_preserving.set_lintegral_comp_preimage {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) {s : set β} (hs : measurable_set s) {f : β → ℝ≥0∞} (hf : measurable f) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, set_lintegral_map hs hf hg.measurable] lemma measure_preserving.set_lintegral_comp_preimage_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) (s : set β) : ∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν := by rw [← hg.map_eq, hge.restrict_map, hge.lintegral_map] lemma measure_preserving.set_lintegral_comp_emb {mb : measurable_space β} {ν : measure β} {g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) (s : set α) : ∫⁻ a in s, f (g a) ∂μ = ∫⁻ b in g '' s, f b ∂ν := by rw [← hg.set_lintegral_comp_preimage_emb hge, preimage_image_eq _ hge.injective] section dirac_and_count variable [measurable_space α] lemma lintegral_dirac' (a : α) {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac' hf)] lemma lintegral_dirac [measurable_singleton_class α] (a : α) (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac f)] lemma lintegral_encodable {α : Type*} {m : measurable_space α} [encodable α] [measurable_singleton_class α] (f : α → ℝ≥0∞) (μ : measure α) : ∫⁻ a, f a ∂μ = ∑' a, f a * μ {a} := begin conv_lhs { rw [← sum_smul_dirac μ, lintegral_sum_measure] }, congr' 1 with a : 1, rw [lintegral_smul_measure, lintegral_dirac, mul_comm], end lemma lintegral_count' {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac' a hf), end lemma lintegral_count [measurable_singleton_class α] (f : α → ℝ≥0∞) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac a f), end end dirac_and_count lemma ae_lt_top {f : α → ℝ≥0∞} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, apply h2f.lt_top.not_le, have : (f ⁻¹' {∞}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {∞}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (measurable_set_singleton ∞))], simp [ennreal.top_mul, preimage, h] end lemma ae_lt_top' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) : ∀ᵐ x ∂μ, f x < ∞ := begin have h2f_meas : ∫⁻ x, hf.mk f x ∂μ ≠ ∞, by rwa ← lintegral_congr_ae hf.ae_eq_mk, exact (ae_lt_top hf.measurable_mk h2f_meas).mp (hf.ae_eq_mk.mono (λ x hx h, by rwa hx)), end lemma set_lintegral_lt_top_of_bdd_above {s : set α} (hs : μ s ≠ ∞) {f : α → ℝ≥0} (hf : measurable f) (hbdd : bdd_above (f '' s)) : ∫⁻ x in s, f x ∂μ < ∞ := begin obtain ⟨M, hM⟩ := hbdd, rw mem_upper_bounds at hM, refine lt_of_le_of_lt (set_lintegral_mono hf.coe_nnreal_ennreal (@measurable_const _ _ _ _ ↑M) _) _, { simpa using hM }, { rw lintegral_const, refine ennreal.mul_lt_top ennreal.coe_lt_top.ne _, simp [hs] } end lemma set_lintegral_lt_top_of_is_compact [topological_space α] [opens_measurable_space α] {s : set α} (hs : μ s ≠ ∞) (hsc : is_compact s) {f : α → ℝ≥0} (hf : continuous f) : ∫⁻ x in s, f x ∂μ < ∞ := set_lintegral_lt_top_of_bdd_above hs hf.measurable (hsc.image hf).bdd_above lemma _root_.is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal {α : Type*} [measurable_space α] (μ : measure α) [μ_fin : is_finite_measure μ] {f : α → ℝ≥0∞} (f_bdd : ∃ c : ℝ≥0, ∀ x, f x ≤ c) : ∫⁻ x, f x ∂μ < ∞ := begin cases f_bdd with c hc, apply lt_of_le_of_lt (@lintegral_mono _ _ μ _ _ hc), rw lintegral_const, exact ennreal.mul_lt_top ennreal.coe_lt_top.ne μ_fin.measure_univ_lt_top.ne, end /-- Given a measure `μ : measure α` and a function `f : α → ℝ≥0∞`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs lemma with_density_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) : μ.with_density f = μ.with_density g := begin apply measure.ext (λ s hs, _), rw [with_density_apply _ hs, with_density_apply _ hs], exact lintegral_congr_ae (ae_restrict_of_ae h) end lemma with_density_add {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : μ.with_density (f + g) = μ.with_density f + μ.with_density g := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.add_apply, with_density_apply _ hs, with_density_apply _ hs, ← lintegral_add hf hg], refl, end lemma with_density_smul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) : μ.with_density (r • f) = r • μ.with_density f := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply, with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul r hf], refl, end lemma with_density_smul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) : μ.with_density (r • f) = r • μ.with_density f := begin refine measure.ext (λ s hs, _), rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply, with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul' r f hr], refl, end lemma is_finite_measure_with_density {f : α → ℝ≥0∞} (hf : ∫⁻ a, f a ∂μ ≠ ∞) : is_finite_measure (μ.with_density f) := { measure_univ_lt_top := by rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ, lt_top_iff_ne_top] } lemma with_density_absolutely_continuous {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : μ.with_density f ≪ μ := begin refine absolutely_continuous.mk (λ s hs₁ hs₂, _), rw with_density_apply _ hs₁, exact set_lintegral_measure_zero _ _ hs₂ end @[simp] lemma with_density_zero : μ.with_density 0 = 0 := begin ext1 s hs, simp [with_density_apply _ hs], end @[simp] lemma with_density_one : μ.with_density 1 = μ := begin ext1 s hs, simp [with_density_apply _ hs], end lemma with_density_tsum {f : ℕ → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : μ.with_density (∑' n, f n) = sum (λ n, μ.with_density (f n)) := begin ext1 s hs, simp_rw [sum_apply _ hs, with_density_apply _ hs], change ∫⁻ x in s, (∑' n, f n) x ∂μ = ∑' (i : ℕ), ∫⁻ x, f i x ∂(μ.restrict s), rw ← lintegral_tsum h, refine lintegral_congr (λ x, tsum_apply (pi.summable.2 (λ _, ennreal.summable))), end lemma with_density_indicator {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) : μ.with_density (s.indicator f) = (μ.restrict s).with_density f := begin ext1 t ht, rw [with_density_apply _ ht, lintegral_indicator _ hs, restrict_comm hs, ← with_density_apply _ ht] end lemma with_density_indicator_one {s : set α} (hs : measurable_set s) : μ.with_density (s.indicator 1) = μ.restrict s := by rw [with_density_indicator hs, with_density_one] lemma with_density_of_real_mutually_singular {f : α → ℝ} (hf : measurable f) : μ.with_density (λ x, ennreal.of_real $ f x) ⊥ₘ μ.with_density (λ x, ennreal.of_real $ -f x) := begin set S : set α := { x | f x < 0 } with hSdef, have hS : measurable_set S := measurable_set_lt hf measurable_const, refine ⟨S, hS, _, _⟩, { rw [with_density_apply _ hS, lintegral_eq_zero_iff hf.ennreal_of_real, eventually_eq], exact (ae_restrict_mem hS).mono (λ x hx, ennreal.of_real_eq_zero.2 (le_of_lt hx)) }, { rw [with_density_apply _ hS.compl, lintegral_eq_zero_iff hf.neg.ennreal_of_real, eventually_eq], exact (ae_restrict_mem hS.compl).mono (λ x hx, ennreal.of_real_eq_zero.2 (not_lt.1 $ mt neg_pos.1 hx)) }, end lemma restrict_with_density {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) : (μ.with_density f).restrict s = (μ.restrict s).with_density f := begin ext1 t ht, rw [restrict_apply ht, with_density_apply _ ht, with_density_apply _ (ht.inter hs), restrict_restrict ht], end lemma with_density_eq_zero {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h : μ.with_density f = 0) : f =ᵐ[μ] 0 := by rw [← lintegral_eq_zero_iff' hf, ← set_lintegral_univ, ← with_density_apply _ measurable_set.univ, h, measure.coe_zero, pi.zero_apply] lemma with_density_apply_eq_zero {f : α → ℝ≥0∞} {s : set α} (hf : measurable f) : μ.with_density f s = 0 ↔ μ ({x | f x ≠ 0} ∩ s) = 0 := begin split, { assume hs, let t := to_measurable (μ.with_density f) s, apply measure_mono_null (inter_subset_inter_right _ (subset_to_measurable (μ.with_density f) s)), have A : μ.with_density f t = 0, by rw [measure_to_measurable, hs], rw [with_density_apply f (measurable_set_to_measurable _ s), lintegral_eq_zero_iff hf, eventually_eq, ae_restrict_iff, ae_iff] at A, swap, { exact hf (measurable_set_singleton 0) }, simp only [pi.zero_apply, mem_set_of_eq, filter.mem_mk] at A, convert A, ext x, simp only [and_comm, exists_prop, mem_inter_eq, iff_self, mem_set_of_eq, mem_compl_eq, not_forall] }, { assume hs, let t := to_measurable μ ({x | f x ≠ 0} ∩ s), have A : s ⊆ t ∪ {x | f x = 0}, { assume x hx, rcases eq_or_ne (f x) 0 with fx|fx, { simp only [fx, mem_union_eq, mem_set_of_eq, eq_self_iff_true, or_true] }, { left, apply subset_to_measurable _ _, exact ⟨fx, hx⟩ } }, apply measure_mono_null A (measure_union_null _ _), { apply with_density_absolutely_continuous, rwa measure_to_measurable }, { have M : measurable_set {x : α | f x = 0} := hf (measurable_set_singleton _), rw [with_density_apply _ M, (lintegral_eq_zero_iff hf)], filter_upwards [ae_restrict_mem M], simp only [imp_self, pi.zero_apply, implies_true_iff] } } end lemma ae_with_density_iff {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) : (∀ᵐ x ∂(μ.with_density f), p x) ↔ ∀ᵐ x ∂μ, f x ≠ 0 → p x := begin rw [ae_iff, ae_iff, with_density_apply_eq_zero hf], congr', ext x, simp only [exists_prop, mem_inter_eq, iff_self, mem_set_of_eq, not_forall], end lemma ae_with_density_iff_ae_restrict {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) : (∀ᵐ x ∂(μ.with_density f), p x) ↔ (∀ᵐ x ∂(μ.restrict {x | f x ≠ 0}), p x) := begin rw [ae_with_density_iff hf, ae_restrict_iff'], { refl }, { exact hf (measurable_set_singleton 0).compl }, end lemma ae_measurable_with_density_iff {E : Type*} [normed_group E] [normed_space ℝ E] [topological_space.second_countable_topology E] [measurable_space E] [borel_space E] {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : ae_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_measurable (λ x, (f x : ℝ) • g x) μ := begin split, { rintros ⟨g', g'meas, hg'⟩, have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl, refine ⟨λ x, (f x : ℝ) • g' x, hf.coe_nnreal_real.smul g'meas, _⟩, apply @ae_of_ae_restrict_of_ae_restrict_compl _ _ _ {x | f x ≠ 0}, { rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg', rw ae_restrict_iff' A, filter_upwards [hg'], assume a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl], assume x hx, simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx, simp [hx] } }, { rintros ⟨g', g'meas, hg'⟩, refine ⟨λ x, (f x : ℝ)⁻¹ • g' x, hf.coe_nnreal_real.inv.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'], assume x hx h'x, rw [← hx, smul_smul, _root_.inv_mul_cancel, one_smul], simp only [ne.def, coe_eq_zero] at h'x, simpa only [nnreal.coe_eq_zero, ne.def] using h'x } end lemma ae_measurable_with_density_ennreal_iff {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ≥0∞} : ae_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_measurable (λ x, (f x : ℝ≥0∞) * g x) μ := begin split, { rintros ⟨g', g'meas, hg'⟩, have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl, refine ⟨λ x, f x * g' x, hf.coe_nnreal_ennreal.smul g'meas, _⟩, apply ae_of_ae_restrict_of_ae_restrict_compl {x | f x ≠ 0}, { rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg', rw ae_restrict_iff' A, filter_upwards [hg'], assume a ha h'a, have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, coe_eq_zero] using h'a, rw ha this }, { filter_upwards [ae_restrict_mem A.compl], assume x hx, simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx, simp [hx] } }, { rintros ⟨g', g'meas, hg'⟩, refine ⟨λ x, (f x)⁻¹ * g' x, hf.coe_nnreal_ennreal.inv.smul g'meas, _⟩, rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal], filter_upwards [hg'], assume x hx h'x, rw [← hx, ← mul_assoc, ennreal.inv_mul_cancel h'x ennreal.coe_ne_top, one_mul] } end end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ℝ≥0∞`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_add` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ℝ≥0∞) → Prop} (h_ind : ∀ (c : ℝ≥0∞) ⦃s⦄, measurable_set s → P (indicator s (λ _, c))) (h_add : ∀ ⦃f g : α → ℝ≥0∞⦄, disjoint (support f) (support g) → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ℝ≥0∞⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ℝ≥0∞⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_add hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory variables {α : Type*} {m m0 : measurable_space α} include m /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul (μ : measure α) {f : α → ℝ≥0∞} (h_mf : measurable f) : ∀ {g : α → ℝ≥0∞}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c, ← indicator_mul_right], }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.mul (h_mea_g _), *] } end lemma set_lintegral_with_density_eq_set_lintegral_mul (μ : measure α) {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) {s : set α} (hs : measurable_set s) : ∫⁻ x in s, g x ∂μ.with_density f = ∫⁻ x in s, (f * g) x ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul _ hf hg] /-- The Lebesgue integral of `g` with respect to the measure `μ.with_density f` coincides with the integral of `f * g`. This version assumes that `g` is almost everywhere measurable. For a version without conditions on `g` but requiring that `f` is almost everywhere finite, see `lintegral_with_density_eq_lintegral_mul_non_measurable` -/ lemma lintegral_with_density_eq_lintegral_mul₀' {μ : measure α} {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g (μ.with_density f)) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin let f' := hf.mk f, have : μ.with_density f = μ.with_density f' := with_density_congr_ae hf.ae_eq_mk, rw this at ⊢ hg, let g' := hg.mk g, calc ∫⁻ a, g a ∂(μ.with_density f') = ∫⁻ a, g' a ∂(μ.with_density f') : lintegral_congr_ae hg.ae_eq_mk ... = ∫⁻ a, (f' * g') a ∂μ : lintegral_with_density_eq_lintegral_mul _ hf.measurable_mk hg.measurable_mk ... = ∫⁻ a, (f' * g) a ∂μ : begin apply lintegral_congr_ae, apply ae_of_ae_restrict_of_ae_restrict_compl {x | f' x ≠ 0}, { have Z := hg.ae_eq_mk, rw [eventually_eq, ae_with_density_iff_ae_restrict hf.measurable_mk] at Z, filter_upwards [Z], assume x hx, simp only [hx, pi.mul_apply] }, { have M : measurable_set {x : α | f' x ≠ 0}ᶜ := (hf.measurable_mk (measurable_set_singleton 0).compl).compl, filter_upwards [ae_restrict_mem M], assume x hx, simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx, simp only [hx, zero_mul, pi.mul_apply] } end ... = ∫⁻ (a : α), (f * g) a ∂μ : begin apply lintegral_congr_ae, filter_upwards [hf.ae_eq_mk], assume x hx, simp only [hx, pi.mul_apply], end end lemma lintegral_with_density_eq_lintegral_mul₀ {μ : measure α} {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g μ) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := lintegral_with_density_eq_lintegral_mul₀' hf (hg.mono' (with_density_absolutely_continuous μ f)) lemma lintegral_with_density_le_lintegral_mul (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) ≤ ∫⁻ a, (f * g) a ∂μ := begin rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine bsupr_le (λ i i_meas, supr_le (λ hi, _)), have A : f * i ≤ f * g := λ x, ennreal.mul_le_mul le_rfl (hi x), refine le_supr_of_le (f * i) (le_supr_of_le (f_meas.mul i_meas) _), exact le_supr_of_le A (le_of_eq (lintegral_with_density_eq_lintegral_mul _ f_meas i_meas)) end lemma lintegral_with_density_eq_lintegral_mul_non_measurable (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (hf : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin refine le_antisymm (lintegral_with_density_le_lintegral_mul μ f_meas g) _, rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral], refine bsupr_le (λ i i_meas, supr_le (λ hi, _)), have A : (λ x, (f x)⁻¹ * i x) ≤ g, { assume x, dsimp, rw [mul_comm, ← div_eq_mul_inv], exact div_le_of_le_mul' (hi x), }, refine le_supr_of_le (λ x, (f x)⁻¹ * i x) (le_supr_of_le (f_meas.inv.mul i_meas) _), refine le_supr_of_le A _, rw lintegral_with_density_eq_lintegral_mul _ f_meas (f_meas.inv.mul i_meas), apply lintegral_mono_ae, filter_upwards [hf], assume x h'x, rcases eq_or_ne (f x) 0 with hx|hx, { have := hi x, simp only [hx, zero_mul, pi.mul_apply, nonpos_iff_eq_zero] at this, simp [this] }, { apply le_of_eq _, dsimp, rw [← mul_assoc, ennreal.mul_inv_cancel hx h'x.ne, one_mul] } end lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable (μ : measure α) {f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) (hf : ∀ᵐ x ∂(μ.restrict s), f x < ∞) : ∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas hf] lemma lintegral_with_density_eq_lintegral_mul_non_measurable₀ (μ : measure α) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h'f : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) : ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin let f' := hf.mk f, calc ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, g a ∂(μ.with_density f') : by rw with_density_congr_ae hf.ae_eq_mk ... = ∫⁻ a, (f' * g) a ∂μ : begin apply lintegral_with_density_eq_lintegral_mul_non_measurable _ hf.measurable_mk, filter_upwards [h'f, hf.ae_eq_mk], assume x hx h'x, rwa ← h'x, end ... = ∫⁻ a, (f * g) a ∂μ : begin apply lintegral_congr_ae, filter_upwards [hf.ae_eq_mk], assume x hx, simp only [hx, pi.mul_apply], end end lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ (μ : measure α) {f : α → ℝ≥0∞} {s : set α} (hf : ae_measurable f (μ.restrict s)) (g : α → ℝ≥0∞) (hs : measurable_set s) (h'f : ∀ᵐ x ∂(μ.restrict s), f x < ∞) : ∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ := by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable₀ _ hf h'f] lemma with_density_mul (μ : measure α) {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) : μ.with_density (f * g) = (μ.with_density f).with_density g := begin ext1 s hs, simp [with_density_apply _ hs, restrict_with_density hs, lintegral_with_density_eq_lintegral_mul _ hf hg], end /-- In a sigma-finite measure space, there exists an integrable function which is positive everywhere (and with an arbitrarily small integral). -/ lemma exists_pos_lintegral_lt_of_sigma_finite (μ : measure α) [sigma_finite μ] {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, 0 < g x) ∧ measurable g ∧ (∫⁻ x, g x ∂μ < ε) := begin /- Let `s` be a covering of `α` by pairwise disjoint measurable sets of finite measure. Let `δ : ℕ → ℝ≥0` be a positive function such that `∑' i, μ (s i) * δ i < ε`. Then the function that is equal to `δ n` on `s n` is a positive function with integral less than `ε`. -/ set s : ℕ → set α := disjointed (spanning_sets μ), have : ∀ n, μ (s n) < ∞, from λ n, (measure_mono $ disjointed_subset _ _).trans_lt (measure_spanning_sets_lt_top μ n), obtain ⟨δ, δpos, δsum⟩ : ∃ δ : ℕ → ℝ≥0, (∀ i, 0 < δ i) ∧ ∑' i, μ (s i) * δ i < ε, from ennreal.exists_pos_tsum_mul_lt_of_encodable ε0 _ (λ n, (this n).ne), set N : α → ℕ := spanning_sets_index μ, have hN_meas : measurable N := measurable_spanning_sets_index μ, have hNs : ∀ n, N ⁻¹' {n} = s n := preimage_spanning_sets_index_singleton μ, refine ⟨δ ∘ N, λ x, δpos _, measurable_from_nat.comp hN_meas, _⟩, simpa [lintegral_comp measurable_from_nat.coe_nnreal_ennreal hN_meas, hNs, lintegral_encodable, measurable_spanning_sets_index, mul_comm] using δsum, end lemma lintegral_trim {μ : measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : @measurable _ _ m _ f) : ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ := begin refine @measurable.ennreal_induction α m (λ f, ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ) _ _ _ f hf, { intros c s hs, rw [lintegral_indicator _ hs, lintegral_indicator _ (hm s hs), set_lintegral_const, set_lintegral_const], suffices h_trim_s : μ.trim hm s = μ s, by rw h_trim_s, exact trim_measurable_set_eq hm hs, }, { intros f g hfg hf hg hf_prop hg_prop, have h_m := lintegral_add hf hg, have h_m0 := lintegral_add (measurable.mono hf hm le_rfl) (measurable.mono hg hm le_rfl), rwa [hf_prop, hg_prop, ← h_m0] at h_m, }, { intros f hf hf_mono hf_prop, rw lintegral_supr hf hf_mono, rw lintegral_supr (λ n, measurable.mono (hf n) hm le_rfl) hf_mono, congr, exact funext (λ n, hf_prop n), }, end lemma lintegral_trim_ae {μ : measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : ae_measurable f (μ.trim hm)) : ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ := by rw [lintegral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), lintegral_congr_ae hf.ae_eq_mk, lintegral_trim hm hf.measurable_mk] section sigma_finite variables {E : Type*} [normed_group E] [measurable_space E] [opens_measurable_space E] lemma univ_le_of_forall_fin_meas_le {μ : measure α} (hm : m ≤ m0) [@sigma_finite _ m (μ.trim hm)] (C : ℝ≥0∞) {f : set α → ℝ≥0∞} (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → f s ≤ C) (h_F_lim : ∀ S : ℕ → set α, (∀ n, measurable_set[m] (S n)) → monotone S → f (⋃ n, S n) ≤ ⨆ n, f (S n)) : f univ ≤ C := begin let S := @spanning_sets _ m (μ.trim hm) _, have hS_mono : monotone S, from @monotone_spanning_sets _ m (μ.trim hm) _, have hS_meas : ∀ n, measurable_set[m] (S n), from @measurable_spanning_sets _ m (μ.trim hm) _, rw ← @Union_spanning_sets _ m (μ.trim hm), refine (h_F_lim S hS_meas hS_mono).trans _, refine supr_le (λ n, hf (S n) (hS_meas n) _), exact ((le_trim hm).trans_lt (@measure_spanning_sets_lt_top _ m (μ.trim hm) _ n)).ne, end /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral over the whole space is bounded by that same constant. Version for a measurable function. See `lintegral_le_of_forall_fin_meas_le'` for the more general `ae_measurable` version. -/ lemma lintegral_le_of_forall_fin_meas_le_of_measurable {μ : measure α} (hm : m ≤ m0) [@sigma_finite _ m (μ.trim hm)] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : measurable f) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := begin have : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ, by simp only [measure.restrict_univ], rw ← this, refine univ_le_of_forall_fin_meas_le hm C hf (λ S hS_meas hS_mono, _), rw ← lintegral_indicator, swap, { exact hm (⋃ n, S n) (@measurable_set.Union _ _ m _ _ hS_meas), }, have h_integral_indicator : (⨆ n, ∫⁻ x in S n, f x ∂μ) = ⨆ n, ∫⁻ x, (S n).indicator f x ∂μ, { congr, ext1 n, rw lintegral_indicator _ (hm _ (hS_meas n)), }, rw [h_integral_indicator, ← lintegral_supr], { refine le_of_eq (lintegral_congr (λ x, _)), simp_rw indicator_apply, by_cases hx_mem : x ∈ Union S, { simp only [hx_mem, if_true], obtain ⟨n, hxn⟩ := mem_Union.mp hx_mem, refine le_antisymm (trans _ (le_supr _ n)) (supr_le (λ i, _)), { simp only [hxn, le_refl, if_true], }, { by_cases hxi : x ∈ S i; simp [hxi], }, }, { simp only [hx_mem, if_false], rw mem_Union at hx_mem, push_neg at hx_mem, refine le_antisymm (zero_le _) (supr_le (λ n, _)), simp only [hx_mem n, if_false, nonpos_iff_eq_zero], }, }, { exact λ n, hf_meas.indicator (hm _ (hS_meas n)), }, { intros n₁ n₂ hn₁₂ a, simp_rw indicator_apply, split_ifs, { exact le_rfl, }, { exact absurd (mem_of_mem_of_subset h (hS_mono hn₁₂)) h_1, }, { exact zero_le _, }, { exact le_rfl, }, }, end /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral over the whole space is bounded by that same constant. -/ lemma lintegral_le_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0) [@sigma_finite _ m (μ.trim hm)] (C : ℝ≥0∞) {f : _ → ℝ≥0∞} (hf_meas : ae_measurable f μ) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := begin let f' := hf_meas.mk f, have hf' : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f' x ∂μ ≤ C, { refine λ s hs hμs, (le_of_eq _).trans (hf s hs hμs), refine lintegral_congr_ae (ae_restrict_of_ae (hf_meas.ae_eq_mk.mono (λ x hx, _))), rw hx, }, rw lintegral_congr_ae hf_meas.ae_eq_mk, exact lintegral_le_of_forall_fin_meas_le_of_measurable hm C hf_meas.measurable_mk hf', end omit m /-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite measure and the measure is σ-finite, then the integral over the whole space is bounded by that same constant. -/ lemma lintegral_le_of_forall_fin_meas_le [measurable_space α] {μ : measure α} [sigma_finite μ] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : ae_measurable f μ) (hf : ∀ s, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) : ∫⁻ x, f x ∂μ ≤ C := @lintegral_le_of_forall_fin_meas_le' _ _ _ _ _ (by rwa trim_eq_self) C _ hf_meas hf /-- A sigma-finite measure is absolutely continuous with respect to some finite measure. -/ lemma exists_absolutely_continuous_is_finite_measure {m : measurable_space α} (μ : measure α) [sigma_finite μ] : ∃ (ν : measure α), is_finite_measure ν ∧ μ ≪ ν := begin obtain ⟨g, gpos, gmeas, hg⟩ : ∃ (g : α → ℝ≥0), (∀ (x : α), 0 < g x) ∧ measurable g ∧ ∫⁻ (x : α), ↑(g x) ∂μ < 1 := exists_pos_lintegral_lt_of_sigma_finite μ (ennreal.zero_lt_one).ne', refine ⟨μ.with_density (λ x, g x), is_finite_measure_with_density hg.ne_top, _⟩, have : μ = (μ.with_density (λ x, g x)).with_density (λ x, (g x)⁻¹), { have A : (λ (x : α), (g x : ℝ≥0∞)) * (λ (x : α), (↑(g x))⁻¹) = 1, { ext1 x, exact ennreal.mul_inv_cancel (ennreal.coe_ne_zero.2 ((gpos x).ne')) ennreal.coe_ne_top }, rw [← with_density_mul _ gmeas.coe_nnreal_ennreal gmeas.coe_nnreal_ennreal.inv, A, with_density_one] }, conv_lhs { rw this }, exact with_density_absolutely_continuous _ _, end end sigma_finite end measure_theory
7263f24cc9ecc31349bcc66327d37ee771c4aea8
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Leanpkg/Build.lean
423f89023b255d28a735c1ccb920e60d733cdb8b
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
3,512
lean
/- Copyright (c) 2021 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Name import Lean.Elab.Import import Leanpkg.Proc open Lean open System namespace Leanpkg.Build def buildPath : FilePath := "build" def tempBuildPath := buildPath / "temp" structure Config where pkg : Name leanArgs : List String leanPath : String -- things like `leanpkg.toml` and olean roots of dependencies that should also trigger rebuilds moreDeps : List FilePath structure Context extends Config where parents : List Name := [] moreDepsMTime : IO.FS.SystemTime structure Result where maxMTime : IO.FS.SystemTime task : Task (Except IO.Error Unit) deriving Inhabited structure State where modTasks : NameMap Result := ∅ abbrev BuildM := ReaderT Context <| StateT State IO partial def buildModule (mod : Name) : BuildM Result := do let ctx ← read if ctx.parents.contains mod then -- cyclic import let cycle := ctx.parents.dropWhile (· != mod) ++ [mod] let cycle := cycle.reverse.map (s!" {·}") throw <| IO.userError s!"import cycle detected:\n{"\n".intercalate cycle}" if let some r := (← get).modTasks.find? mod then -- already visited return r let leanFile := modToFilePath "." mod "lean" let leanMData ← leanFile.metadata -- recursively build dependencies and calculate transitive `maxMTime` let (imports, _, _) ← Elab.parseImports (← IO.FS.readFile leanFile) leanFile.toString let localImports := imports.filter (·.module.getRoot == ctx.pkg) let deps ← localImports.mapM (buildModule ·.module) let depMTimes ← deps.mapM (·.maxMTime) let maxMTime := List.maximum? (leanMData.modified :: ctx.moreDepsMTime :: depMTimes) |>.get! -- check whether we have an up-to-date .olean let oleanFile := modToFilePath buildPath mod "olean" try if (← oleanFile.metadata).modified >= maxMTime then let r := { maxMTime, task := Task.pure (Except.ok ()) } modify fun st => { st with modTasks := st.modTasks.insert mod r } return r catch | IO.Error.noFileOrDirectory .. => pure () | e => throw e let task ← IO.mapTasks (tasks := deps.map (·.task)) fun rs => do if let some e := rs.findSome? (fun | Except.error e => some e | Except.ok _ => none) then -- propagate failure throw e try let cFile := modToFilePath tempBuildPath mod "c" IO.createDirAll oleanFile.parent.get! IO.createDirAll cFile.parent.get! execCmd { cmd := (← IO.appDir) / "lean" |>.withExtension FilePath.exeExtension |>.toString args := ctx.leanArgs.toArray ++ #["-o", oleanFile.toString, "-c", cFile.toString, leanFile.toString] env := #[("LEAN_PATH", ctx.leanPath)] } catch e => -- print errors early IO.eprintln e throw e let r := { maxMTime, task := task } modify fun st => { st with modTasks := st.modTasks.insert mod r } return r def buildModules (cfg : Config) (mods : List Name) : IO Unit := do let moreDepsMTime := (← cfg.moreDeps.mapM (·.metadata)).map (·.modified) |>.maximum? |>.getD ⟨0, 0⟩ let rs ← mods.mapM buildModule |>.run { toConfig := cfg, moreDepsMTime } |>.run' {} for r in rs do if let Except.error _ ← IO.wait r.task then -- actual error has already been printed above throw <| IO.userError "Build failed." end Leanpkg.Build
dbb90711a02a0c11ee1c811611cd699f9cfe7a40
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/homotopy/equiv.lean
a3796ad4907bdcd95a9b1bc1a446c4d7a3dff51e
[ "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
5,101
lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import topology.homotopy.basic /-! # Homotopy equivalences between topological spaces In this file, we define homotopy equivalences between topological spaces `X` and `Y` as a pair of functions `f : C(X, Y)` and `g : C(Y, X)` such that `f.comp g` and `g.comp f` are both homotopic to `id`. ## Main definitions - `continuous_map.homotopy_equiv` is the type of homotopy equivalences between topological spaces. ## Notation We introduce the notation `X ≃ₕ Y` for `continuous_map.homotopy_equiv X Y` in the `continuous_map` locale. -/ universes u v w variables {X : Type u} {Y : Type v} {Z : Type w} variables [topological_space X] [topological_space Y] [topological_space Z] namespace continuous_map /-- A homotopy equivalence between topological spaces `X` and `Y` are a pair of functions `to_fun : C(X, Y)` and `inv_fun : C(Y, X)` such that `to_fun.comp inv_fun` and `inv_fun.comp to_fun` are both homotopic to `id`. -/ @[ext] structure homotopy_equiv (X : Type u) (Y : Type v) [topological_space X] [topological_space Y] := (to_fun : C(X, Y)) (inv_fun : C(Y, X)) (left_inv : (inv_fun.comp to_fun).homotopic id) (right_inv : (to_fun.comp inv_fun).homotopic id) localized "infix ` ≃ₕ `:25 := continuous_map.homotopy_equiv" in continuous_map namespace homotopy_equiv instance : has_coe_to_fun (homotopy_equiv X Y) (λ _, X → Y) := ⟨λ h, h.to_fun⟩ @[simp] lemma to_fun_eq_coe (h : homotopy_equiv X Y) : (h.to_fun : X → Y) = h := rfl @[continuity] lemma continuous (h : homotopy_equiv X Y) : continuous h := h.to_fun.continuous end homotopy_equiv end continuous_map open_locale continuous_map namespace homeomorph /-- Any homeomorphism is a homotopy equivalence. -/ def to_homotopy_equiv (h : X ≃ₜ Y) : X ≃ₕ Y := { to_fun := ⟨h⟩, inv_fun := ⟨h.symm⟩, left_inv := by { convert continuous_map.homotopic.refl _, ext, simp }, right_inv := by { convert continuous_map.homotopic.refl _, ext, simp } } @[simp] lemma coe_to_homotopy_equiv (h : X ≃ₜ Y) : ⇑(h.to_homotopy_equiv) = h := rfl end homeomorph namespace continuous_map namespace homotopy_equiv /-- If `X` is homotopy equivalent to `Y`, then `Y` is homotopy equivalent to `X`. -/ def symm (h : X ≃ₕ Y) : Y ≃ₕ X := { to_fun := h.inv_fun, inv_fun := h.to_fun, left_inv := h.right_inv, right_inv := h.left_inv } @[simp] lemma coe_inv_fun (h : homotopy_equiv X Y) : (⇑h.inv_fun : Y → X) = ⇑h.symm := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : X ≃ₕ Y) : X → Y := h /-- 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.symm_apply (h : X ≃ₕ Y) : Y → X := h.symm initialize_simps_projections homotopy_equiv (to_fun_to_fun -> apply, inv_fun_to_fun -> symm_apply, -to_fun, -inv_fun) /-- Any topological space is homotopy equivalent to itself. -/ @[simps] def refl (X : Type u) [topological_space X] : X ≃ₕ X := (homeomorph.refl X).to_homotopy_equiv instance : inhabited (homotopy_equiv unit unit) := ⟨refl unit⟩ /-- If `X` is homotopy equivalent to `Y`, and `Y` is homotopy equivalent to `Z`, then `X` is homotopy equivalent to `Z`. -/ @[simps] def trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) : X ≃ₕ Z := { to_fun := h₂.to_fun.comp h₁.to_fun, inv_fun := h₁.inv_fun.comp h₂.inv_fun, left_inv := begin refine homotopic.trans _ h₁.left_inv, change ((h₁.inv_fun.comp h₂.inv_fun).comp (h₂.to_fun.comp h₁.to_fun)) with h₁.inv_fun.comp ((h₂.inv_fun.comp h₂.to_fun).comp h₁.to_fun), refine homotopic.hcomp _ (homotopic.refl _), refine homotopic.trans ((homotopic.refl _).hcomp h₂.left_inv) _, -- simp, rw continuous_map.id_comp, end, right_inv := begin refine homotopic.trans _ h₂.right_inv, change ((h₂.to_fun.comp h₁.to_fun).comp (h₁.inv_fun.comp h₂.inv_fun)) with h₂.to_fun.comp ((h₁.to_fun.comp h₁.inv_fun).comp h₂.inv_fun), refine homotopic.hcomp _ (homotopic.refl _), refine homotopic.trans ((homotopic.refl _).hcomp h₁.right_inv) _, rw id_comp, end } lemma symm_trans (h₁ : X ≃ₕ Y) (h₂ : Y ≃ₕ Z) : (h₁.trans h₂).symm = h₂.symm.trans h₁.symm := by ext; refl end homotopy_equiv end continuous_map open continuous_map namespace homeomorph @[simp] lemma refl_to_homotopy_equiv (X : Type u) [topological_space X] : (homeomorph.refl X).to_homotopy_equiv = homotopy_equiv.refl X := rfl @[simp] lemma symm_to_homotopy_equiv (h : X ≃ₜ Y) : h.symm.to_homotopy_equiv = h.to_homotopy_equiv.symm := rfl @[simp] lemma trans_to_homotopy_equiv (h₀ : X ≃ₜ Y) (h₁ : Y ≃ₜ Z) : (h₀.trans h₁).to_homotopy_equiv = h₀.to_homotopy_equiv.trans h₁.to_homotopy_equiv := rfl end homeomorph