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
80b756c90c892e976a1485af0f1d7e3b707c9cd1
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebraic_geometry/presheafed_space.lean
e02df88471a8616e31ae696627fe9ea632d8783e
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
8,351
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf /-! # Presheafed spaces Introduces the category of topological spaces equipped with a presheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.category category_theory.functor variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 local attribute [tidy] tactic.op_induction' namespace algebraic_geometry /-- A `PresheafedSpace C` is a topological space equipped with a presheaf of `C`s. -/ structure PresheafedSpace := (to_Top : Top) (𝒪 : to_Top.presheaf C) variables {C} namespace PresheafedSpace instance coe_to_Top : has_coe (PresheafedSpace C) Top := { coe := λ X, X.to_Top } @[simp] lemma as_coe (X : PresheafedSpace C) : X.to_Top = (X : Top.{v}) := rfl @[simp] lemma mk_coe (to_Top) (𝒪) : (({ to_Top := to_Top, 𝒪 := 𝒪 } : PresheafedSpace.{v} C) : Top.{v}) = to_Top := rfl instance (X : PresheafedSpace.{v} C) : topological_space X := X.to_Top.str /-- A morphism between presheafed spaces `X` and `Y` consists of a continuous map `f` between the underlying topological spaces, and a (notice contravariant!) map from the presheaf on `Y` to the pushforward of the presheaf on `X` via `f`. -/ structure hom (X Y : PresheafedSpace C) := (f : (X : Top.{v}) ⟶ (Y : Top.{v})) (c : Y.𝒪 ⟶ f _* X.𝒪) @[ext] lemma ext {X Y : PresheafedSpace C} (α β : hom X Y) (w : α.f = β.f) (h : α.c ≫ (whisker_right (nat_trans.op (opens.map_iso _ _ w).inv) X.𝒪) = β.c) : α = β := begin cases α, cases β, dsimp [presheaf.pushforward] at *, tidy, -- TODO including `injections` would make tidy work earlier. end . def id (X : PresheafedSpace C) : hom X X := { f := 𝟙 (X : Top.{v}), c := ((functor.left_unitor _).inv) ≫ (whisker_right (nat_trans.op (opens.map_id (X.to_Top)).hom) _) } def comp (X Y Z : PresheafedSpace C) (α : hom X Y) (β : hom Y Z) : hom X Z := { f := α.f ≫ β.f, c := β.c ≫ (whisker_left (opens.map β.f).op α.c) ≫ (Top.presheaf.pushforward.comp _ _ _).inv } variables (C) section local attribute [simp] id comp presheaf.pushforward /- The proofs below can be done by `tidy`, but it is too slow, and we don't have a tactic caching mechanism. -/ /-- The category of PresheafedSpaces. Morphisms are pairs, a continuous map and a presheaf map from the presheaf on the target to the pushforward of the presheaf on the source. -/ instance category_of_PresheafedSpaces : category (PresheafedSpace C) := { hom := hom, id := id, comp := comp, id_comp' := λ X Y f, begin ext1, swap, { dsimp, simp only [id_comp] }, { ext U, op_induction, cases U, dsimp, simp only [comp_id, id_comp, map_id, presheaf.pushforward, presheaf.pushforward.comp_inv_app], dsimp, simp only [comp_id], }, end, comp_id' := λ X Y f, begin ext1, swap, { dsimp, simp only [comp_id] }, { ext U, op_induction, cases U, dsimp, simp only [comp_id, id_comp, map_id, presheaf.pushforward, presheaf.pushforward.comp_inv_app], dsimp, simp only [comp_id], } end, assoc' := λ W X Y Z f g h, begin ext1, swap, refl, { ext U, op_induction, cases U, dsimp, simp only [assoc, map_id, comp_id, presheaf.pushforward, presheaf.pushforward.comp_inv_app], dsimp, simp only [comp_id, id_comp], } end } end variables {C} instance {X Y : PresheafedSpace C} : has_coe (X ⟶ Y) ((X : Top.{v}) ⟶ (Y : Top.{v})) := { coe := λ α, α.f } -- see Note [function coercion] instance {X Y : PresheafedSpace C} : has_coe_to_fun (X ⟶ Y) := ⟨λ _, (X : Top.{v}) → Y.to_Top, λ h, h⟩ @[simp] lemma hom_mk_coe {X Y : PresheafedSpace C} (f) (c) : (({ f := f, c := c } : X ⟶ Y) : (X : Top.{v}) ⟶ (Y : Top.{v})) = f := rfl @[simp] lemma f_as_coe {X Y : PresheafedSpace C} (α : X ⟶ Y) : α.f = (α : (X : Top.{v}) ⟶ (Y : Top.{v})) := rfl @[simp] lemma id_coe (X : PresheafedSpace C) : (((𝟙 X) : X ⟶ X) : (X : Top.{v}) ⟶ X) = 𝟙 (X : Top.{v}) := rfl @[simp] lemma id_coe_fn (X : PresheafedSpace C) : (((𝟙 X) : X ⟶ X) : (X : Top.{v}) → X) = 𝟙 (X : Top.{v}) := rfl @[simp] lemma comp_coe {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) : ((α ≫ β : X ⟶ Z) : (X : Top.{v}) ⟶ Z) = (α : (X : Top.{v}) ⟶ Y) ≫ (β : Y ⟶ Z) := rfl lemma id_c (X : PresheafedSpace C) : ((𝟙 X) : X ⟶ X).c = (((functor.left_unitor _).inv) ≫ (whisker_right (nat_trans.op (opens.map_id (X.to_Top)).hom) _)) := rfl -- Implementation note: this harmless looking lemma causes deterministic timeouts, -- but happily we can survive without it. -- lemma comp_c {X Y Z : PresheafedSpace.{v} C} (α : X ⟶ Y) (β : Y ⟶ Z) : -- (α ≫ β).c = (β.c ≫ (whisker_left (opens.map β.f).op α.c)) := rfl @[simp] lemma id_c_app (X : PresheafedSpace C) (U) : ((𝟙 X) : X ⟶ X).c.app U = eq_to_hom (by { op_induction U, cases U, refl }) := by { op_induction U, cases U, simp only [id_c], dsimp, simp, } @[simp] lemma comp_c_app {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) : (α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.f)).obj (unop U))) ≫ (Top.presheaf.pushforward.comp _ _ _).inv.app U := rfl /-- The forgetful functor from `PresheafedSpace` to `Top`. -/ def forget : PresheafedSpace C ⥤ Top := { obj := λ X, (X : Top.{v}), map := λ X Y f, f } end PresheafedSpace end algebraic_geometry open algebraic_geometry algebraic_geometry.PresheafedSpace variables {C} namespace category_theory variables {D : Type u} [category.{v} D] local attribute [simp] presheaf.pushforward namespace functor /-- We can apply a functor `F : C ⥤ D` to the values of the presheaf in any `PresheafedSpace C`, giving a functor `PresheafedSpace C ⥤ PresheafedSpace D` -/ /- The proofs below can be done by `tidy`, but it is too slow, and we don't have a tactic caching mechanism. -/ def map_presheaf (F : C ⥤ D) : PresheafedSpace C ⥤ PresheafedSpace D := { obj := λ X, { to_Top := X.to_Top, 𝒪 := X.𝒪 ⋙ F }, map := λ X Y f, { f := f.f, c := whisker_right f.c F }, map_id' := λ X, begin ext1, swap, { refl }, { ext, dsimp, simp only [presheaf.pushforward, eq_to_hom_map, map_id, comp_id, id_c_app], refl } end, map_comp' := λ X Y Z f g, begin ext1, swap, { refl, }, { ext, dsimp, simp only [comp_id, assoc, map_comp, map_id, comp_c_app, presheaf.pushforward, presheaf.pushforward.comp_inv_app], dsimp, simp only [comp_id, map_id] } end } @[simp] lemma map_presheaf_obj_X (F : C ⥤ D) (X : PresheafedSpace C) : ((F.map_presheaf.obj X) : Top.{v}) = (X : Top.{v}) := rfl @[simp] lemma map_presheaf_obj_𝒪 (F : C ⥤ D) (X : PresheafedSpace C) : (F.map_presheaf.obj X).𝒪 = X.𝒪 ⋙ F := rfl @[simp] lemma map_presheaf_map_f (F : C ⥤ D) {X Y : PresheafedSpace C} (f : X ⟶ Y) : ((F.map_presheaf.map f) : (X : Top.{v}) ⟶ (Y : Top.{v})) = f := rfl @[simp] lemma map_presheaf_map_c (F : C ⥤ D) {X Y : PresheafedSpace C} (f : X ⟶ Y) : (F.map_presheaf.map f).c = whisker_right f.c F := rfl end functor namespace nat_trans /- The proofs below can be done by `tidy`, but it is too slow, and we don't have a tactic caching mechanism. -/ def on_presheaf {F G : C ⥤ D} (α : F ⟶ G) : G.map_presheaf ⟶ F.map_presheaf := { app := λ X, { f := 𝟙 _, c := whisker_left X.𝒪 α ≫ ((functor.left_unitor _).inv) ≫ (whisker_right (nat_trans.op (opens.map_id X.to_Top).hom) _) }, naturality' := λ X Y f, begin ext1, swap, { refl }, { ext U, op_induction, cases U, dsimp, simp only [comp_id, assoc, map_id, presheaf.pushforward, presheaf.pushforward.comp_inv_app], dsimp, simp only [comp_id, nat_trans.naturality], } end } -- TODO Assemble the last two constructions into a functor -- `(C ⥤ D) ⥤ (PresheafedSpace C ⥤ PresheafedSpace D)` end nat_trans end category_theory
ff5bd37ef7dc9fff001e96bc8dd3916842ba522e
367134ba5a65885e863bdc4507601606690974c1
/src/data/nat/fib.lean
d3891e40615a728c16f17e9247413ec274cf54f8
[ "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
5,555
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import data.stream.basic import tactic import data.nat.gcd /-! # The Fibonacci Sequence ## Summary Definition of the Fibonacci sequence `F₀ = 0, F₁ = 1, Fₙ₊₂ = Fₙ + Fₙ₊₁`. ## Main Definitions - `fib` returns the stream of Fibonacci numbers. ## Main Statements - `fib_succ_succ` : shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.`. - `fib_gcd` : `fib n` is a strong divisibility sequence. ## Implementation Notes For efficiency purposes, the sequence is defined using `stream.iterate`. ## Tags fib, fibonacci -/ namespace nat /-- Auxiliary function used in the definition of `fib_aux_stream`. -/ private def fib_aux_step : (ℕ × ℕ) → (ℕ × ℕ) := λ p, ⟨p.snd, p.fst + p.snd⟩ /-- Auxiliary stream creating Fibonacci pairs `⟨Fₙ, Fₙ₊₁⟩`. -/ private def fib_aux_stream : stream (ℕ × ℕ) := stream.iterate fib_aux_step ⟨0, 1⟩ /-- Implementation of the fibonacci sequence satisfying `fib 0 = 0, fib 1 = 1, fib (n + 2) = fib n + fib (n + 1)`. *Note:* We use a stream iterator for better performance when compared to the naive recursive implementation. -/ @[pp_nodot] def fib (n : ℕ) : ℕ := (fib_aux_stream n).fst @[simp] lemma fib_zero : fib 0 = 0 := rfl @[simp] lemma fib_one : fib 1 = 1 := rfl @[simp] lemma fib_two : fib 2 = 1 := rfl private lemma fib_aux_stream_succ {n : ℕ} : fib_aux_stream (n + 1) = fib_aux_step (fib_aux_stream n) := begin change (stream.nth (n + 1) $ stream.iterate fib_aux_step ⟨0, 1⟩) = fib_aux_step (stream.nth n $ stream.iterate fib_aux_step ⟨0, 1⟩), rw [stream.nth_succ_iterate, stream.map_iterate, stream.nth_map] end /-- Shows that `fib` indeed satisfies the Fibonacci recurrence `Fₙ₊₂ = Fₙ + Fₙ₊₁.` -/ lemma fib_succ_succ {n : ℕ} : fib (n + 2) = fib n + fib (n + 1) := by simp only [fib, fib_aux_stream_succ, fib_aux_step] lemma fib_pos {n : ℕ} (n_pos : 0 < n) : 0 < fib n := begin induction n with n IH, case nat.zero { norm_num at n_pos }, case nat.succ { cases n, case nat.zero { simp [fib_succ_succ, zero_lt_one] }, case nat.succ { have : 0 ≤ fib n, by simp, exact (lt_add_of_nonneg_of_lt this $ IH n.succ_pos) }} end lemma fib_le_fib_succ {n : ℕ} : fib n ≤ fib (n + 1) := by { cases n; simp [fib_succ_succ] } @[mono] lemma fib_mono : monotone fib := monotone_of_monotone_nat $ λ _, fib_le_fib_succ lemma le_fib_self {n : ℕ} (five_le_n : 5 ≤ n) : n ≤ fib n := begin induction five_le_n with n five_le_n IH, { have : 5 = fib 5, by refl, -- 5 ≤ fib 5 exact le_of_eq this }, { -- n + 1 ≤ fib (n + 1) for 5 ≤ n cases n with n', -- rewrite n = succ n' to use fib.succ_succ { have : 5 = 0, from nat.le_zero_iff.elim_left five_le_n, contradiction }, rw fib_succ_succ, suffices : 1 + (n' + 1) ≤ fib n' + fib (n' + 1), by rwa [nat.succ_eq_add_one, add_comm], have : n' ≠ 0, by { intro h, have : 5 ≤ 1, by rwa h at five_le_n, norm_num at this }, have : 1 ≤ fib n', from nat.succ_le_of_lt (fib_pos $ pos_iff_ne_zero.mpr this), mono } end /-- Subsequent Fibonacci numbers are coprime, see https://proofwiki.org/wiki/Consecutive_Fibonacci_Numbers_are_Coprime -/ lemma fib_coprime_fib_succ (n : ℕ) : nat.coprime (fib n) (fib (n + 1)) := begin unfold coprime, induction n with n ih, { simp }, { convert ih using 1, rw [fib_succ_succ, succ_eq_add_one, gcd_rec, add_mod_right, gcd_comm (fib n), gcd_rec (fib (n + 1))], } end /-- See https://proofwiki.org/wiki/Fibonacci_Number_in_terms_of_Smaller_Fibonacci_Numbers -/ lemma fib_add (m n : ℕ) : fib m * fib n + fib (m + 1) * fib (n + 1) = fib (m + n + 1) := begin induction n with n ih generalizing m, { simp }, { intros, specialize ih (m + 1), rw [add_assoc m 1 n, add_comm 1 n] at ih, simp only [fib_succ_succ, ← ih], ring, } end lemma gcd_fib_add_self (m n : ℕ) : gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n) := begin cases eq_zero_or_pos n, { rw h, simp }, replace h := nat.succ_pred_eq_of_pos h, rw [← h, succ_eq_add_one], calc gcd (fib m) (fib (n.pred + 1 + m)) = gcd (fib m) (fib (n.pred) * (fib m) + fib (n.pred + 1) * fib (m + 1)) : by { rw fib_add n.pred _, ring } ... = gcd (fib m) (fib (n.pred + 1) * fib (m + 1)) : by rw [add_comm, gcd_add_mul_self (fib m) _ (fib (n.pred))] ... = gcd (fib m) (fib (n.pred + 1)) : coprime.gcd_mul_right_cancel_right (fib (n.pred + 1)) (coprime.symm (fib_coprime_fib_succ m)) end lemma gcd_fib_add_mul_self (m n : ℕ) : ∀ k, gcd (fib m) (fib (n + k * m)) = gcd (fib m) (fib n) | 0 := by simp | (k+1) := by rw [← gcd_fib_add_mul_self k, add_mul, ← add_assoc, one_mul, gcd_fib_add_self _ _] /-- `fib n` is a strong divisibility sequence, see https://proofwiki.org/wiki/GCD_of_Fibonacci_Numbers -/ lemma fib_gcd (m n : ℕ) : fib (gcd m n) = gcd (fib m) (fib n) := begin wlog h : m ≤ n using [n m, m n], exact le_total m n, { apply gcd.induction m n, { simp }, intros m n mpos h, rw ← gcd_rec m n at h, conv_rhs { rw ← mod_add_div' n m }, rwa [gcd_fib_add_mul_self m (n % m) (n / m), gcd_comm (fib m) _] }, rwa [gcd_comm, gcd_comm (fib m)] end lemma fib_dvd (m n : ℕ) (h : m ∣ n) : fib m ∣ fib n := by rwa [gcd_eq_left_iff_dvd, ← fib_gcd, gcd_eq_left_iff_dvd.mp] end nat
385c3f0d41178291108ab9ae9d7b8f406f78387d
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/untrusted_examples.lean
6f230473b5a1794dbb80bbdc2974bdbe62691d07
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
217
lean
open tactic set_option pp.all true example (m1 : tactic nat) (m2 : nat → tactic bool) : true := by do m1 ← get_local `m1, m2 ← get_local `m2, b ← mk_app `monad.bind [m1, m2], trace b, constructor
dc7fcac0188f78927cc0dbd1a74adf4a32857bee
63abd62053d479eae5abf4951554e1064a4c45b4
/archive/imo/imo1960_q1.lean
8266f10b39407889375a18df4d43b541d442d2c8
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,339
lean
/- Copyright (c) 2020 Kevin Lacker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker -/ import data.nat.digits /-! # IMO 1960 Q1 Determine all three-digit numbers $N$ having the property that $N$ is divisible by 11, and $\dfrac{N}{11}$ is equal to the sum of the squares of the digits of $N$. Since Lean doesn't have a way to directly express problem statements of the form "Determine all X satisfying Y", we express two predicates where proving that one implies the other is equivalent to solving the problem. A human solver also has to discover the second predicate. The strategy here is roughly brute force, checking the possible multiples of 11. -/ open nat def sum_of_squares (L : list ℕ) : ℕ := (L.map (λ x, x * x)).sum def problem_predicate (n : ℕ) : Prop := (nat.digits 10 n).length = 3 ∧ 11 ∣ n ∧ n / 11 = sum_of_squares (nat.digits 10 n) def solution_predicate (n : ℕ) : Prop := n = 550 ∨ n = 803 /- Proving that three digit numbers are the ones in [100, 1000). -/ lemma not_zero {n : ℕ} (h1 : problem_predicate n) : n ≠ 0 := have h2 : nat.digits 10 n ≠ list.nil, from list.ne_nil_of_length_eq_succ h1.left, digits_ne_nil_iff_ne_zero.mp h2 lemma ge_100 {n : ℕ} (h1 : problem_predicate n) : 100 ≤ n := have h2 : 10^3 ≤ 10 * n, begin rw ← h1.left, refine nat.base_pow_length_digits_le 10 n _ (not_zero h1), simp, end, by linarith lemma lt_1000 {n : ℕ} (h1 : problem_predicate n) : n < 1000 := have h2 : n < 10^3, begin rw ← h1.left, refine nat.lt_base_pow_length_digits _, simp, end, by linarith /- We do an exhaustive search to show that all results are covered by `solution_predicate`. -/ def search_up_to (c n : ℕ) : Prop := n = c * 11 ∧ ∀ m : ℕ, m < n → problem_predicate m → solution_predicate m lemma search_up_to_start : search_up_to 9 99 := ⟨rfl, λ n h p, by linarith [ge_100 p]⟩ lemma search_up_to_step {c n} (H : search_up_to c n) {c' n'} (ec : c + 1 = c') (en : n + 11 = n') {l} (el : nat.digits 10 n = l) (H' : c = sum_of_squares l → c = 50 ∨ c = 73) : search_up_to c' n' := begin subst ec, subst en, subst el, obtain ⟨rfl, H⟩ := H, refine ⟨by ring, λ m l p, _⟩, obtain ⟨h₁, ⟨m, rfl⟩, h₂⟩ := id p, by_cases h : 11 * m < c * 11, { exact H _ h p }, have : m = c, {linarith}, subst m, rw [nat.mul_div_cancel_left _ (by norm_num : 11 > 0), mul_comm] at h₂, refine (H' h₂).imp _ _; {rintro rfl, norm_num} end lemma search_up_to_end {c} (H : search_up_to c 1001) {n : ℕ} (ppn : problem_predicate n) : solution_predicate n := H.2 _ (by linarith [lt_1000 ppn]) ppn lemma right_direction {n : ℕ} : problem_predicate n → solution_predicate n := begin have := search_up_to_start, iterate 82 { replace := search_up_to_step this (by norm_num1; refl) (by norm_num1; refl) (by norm_digits; refl) dec_trivial }, exact search_up_to_end this end /- Now we just need to prove the equivalence, for the precise problem statement. -/ lemma left_direction (n : ℕ) (spn : solution_predicate n) : problem_predicate n := by rcases spn with (rfl | rfl); norm_num [problem_predicate, sum_of_squares] theorem imo1960_q1 (n : ℕ) : problem_predicate n ↔ solution_predicate n := ⟨right_direction, left_direction n⟩
08cd5eed63cce671e2b78d75247a644210dd975c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/multiset/interval.lean
af501ed5fd1bd056105b65a7566423c30d0fbaf1
[ "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,273
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.finset.locally_finite import data.dfinsupp.interval import data.dfinsupp.multiset import data.nat.interval /-! # Finite intervals of multisets This file provides the `locally_finite_order` instance for `multiset α` and calculates the cardinality of its finite intervals. ## Implementation notes We implement the intervals via the intervals on `dfinsupp`, rather than via filtering `multiset.powerset`; this is because `(multiset.repeat x n).powerset` has `2^n` entries not `n+1` entries as it contains duplicates. We do not go via `finsupp` as this would be noncomputable, and multisets are typically used computationally. -/ open finset dfinsupp function open_locale big_operators pointwise variables {α : Type*} {β : α → Type*} namespace multiset variables [decidable_eq α] (f g : multiset α) instance : locally_finite_order (multiset α) := locally_finite_order.of_Icc (multiset α) (λ f g, (finset.Icc f.to_dfinsupp g.to_dfinsupp).map (multiset.equiv_dfinsupp.to_equiv.symm.to_embedding)) (λ f g x, by simp) lemma Icc_eq : finset.Icc f g = (finset.Icc f.to_dfinsupp g.to_dfinsupp).map (multiset.equiv_dfinsupp.to_equiv.symm.to_embedding) := rfl lemma card_Icc : (finset.Icc f g).card = ∏ i in f.to_finset ∪ g.to_finset, (g.count i + 1 - f.count i) := by simp_rw [Icc_eq, finset.card_map, dfinsupp.card_Icc, nat.card_Icc, multiset.to_dfinsupp_apply, to_dfinsupp_support] lemma card_Ico : (finset.Ico f g).card = ∏ i in f.to_finset ∪ g.to_finset, (g.count i + 1 - f.count i) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc : (finset.Ioc f g).card = ∏ i in f.to_finset ∪ g.to_finset, (g.count i + 1 - f.count i) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo : (finset.Ioo f g).card = ∏ i in f.to_finset ∪ g.to_finset, (g.count i + 1 - f.count i) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] lemma card_Iic : (finset.Iic f).card = ∏ i in f.to_finset, (f.count i + 1) := by simp_rw [Iic_eq_Icc, card_Icc, bot_eq_zero, to_finset_zero, empty_union, count_zero, tsub_zero] end multiset
9715c609f40d3aa37b5bf049c4522eea16ecf817
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/topology/algebra/uniform_group.lean
a1419c83651dd306f207e59e984675827b4c9a8b
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,465
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 Uniform structure on topological groups: * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ import topology.uniform_space.uniform_embedding topology.uniform_space.separation topology.algebra.group noncomputable theory local attribute [instance, priority 0] classical.prop_decidable section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨(uniform_continuous_fst.prod_mk (uniform_continuous_snd.comp h₂)).comp h₁⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub' : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub α lemma uniform_continuous_sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := (hf.prod_mk hg).comp uniform_continuous_sub' lemma uniform_continuous_neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_sub uniform_continuous_const hf, by simp * at * lemma uniform_continuous_neg' : uniform_continuous (λx:α, - x) := uniform_continuous_neg uniform_continuous_id lemma uniform_continuous_add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from uniform_continuous_sub hf $ uniform_continuous_neg hg, by simp * at * lemma uniform_continuous_add' : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_add uniform_continuous_fst uniform_continuous_snd instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add'.continuous, continuous_neg := uniform_continuous_neg'.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨uniform_continuous.prod_mk (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_fst) (uniform_continuous_snd.comp uniform_continuous_fst)) (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_snd) (uniform_continuous_snd.comp uniform_continuous_snd)) ⟩ lemma uniformity_translate (a : α) : uniformity.map (λx:α×α, (x.1 + a, x.2 + a)) = uniformity := le_antisymm (uniform_continuous_add uniform_continuous_id uniform_continuous_const) (calc uniformity = (uniformity.map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ uniformity.map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_add uniform_continuous_id uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := begin refine ⟨assume x y, eq_of_add_eq_add_right, _⟩, rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end section variables (α) lemma uniformity_eq_comap_nhds_zero : uniformity = comap (λx:α×α, x.2 - x.1) (nhds (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_sub' hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_add' hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ uniformity.sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_eq_empty] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (nhds 0) (nhds 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp tendsto_comap h end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (nhds 0) (nhds (f 0)), by rwa [is_add_group_hom.zero f] at this, h.tendsto 0 end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (nhds 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (nhds 0)) (nhds (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp tendsto_comap (tendsto_neg tendsto_id) end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets, by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets, rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : uniformity = comap (λp:G×G, p.2 - p.1) (nhds (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((nhds 0).prod (nhds 0))) (nhds (0 - 0)) := tendsto_comap.comp (tendsto_sub tendsto_fst tendsto_snd), begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘)] end end lemma to_uniform_space_eq {α : Type*} [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = uniformity, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group namespace add_comm_group section Z_bilin variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] instance is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_group_hom.add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, dsimp [algebra.sub], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end Z_bilin end add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- α, β and G are abelian topological groups, G is complete Hausdorff variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] [uniform_add_group G] [complete_space G] [separated G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (nhds (x₁, 0)) (nhds 0) := begin have := continuous.tendsto hψ (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (nhds (0, y₁)) (nhds 0) := begin have := continuous.tendsto hψ (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ nhds (x₀, x₀)) (nhds 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (nhds (x₀, x₀)) (nhds (e 0)), { have := continuous.tendsto (continuous.comp continuous_swap continuous_sub') (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_embedding open filter variables {α : Type*} [topological_space α] variables {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_embedding e) (h : ∀ b : β, cauchy (map f (comap e $ nhds b))) : continuous (de.extend f) := continuous_extend de $ λ b, complete_space.complete (h b) end dense_embedding namespace dense_embedding variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_embedding f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ (nhds (0 : G)).sets) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ (comap e (nhds x₀)).sets, ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := nhds x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (nhds (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ nhds (x₀, x₀)) (nhds y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp lim1 (is_Z_bilin.tendsto_zero_right hφ y₁), rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ (comap e (nhds x₀)).sets, ∃ V ∈ (comap f (nhds y₀)).sets, ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := nhds x₀, let Ny := nhds y₀, let dp := dense_embedding.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (nhds (0, 0)) (nhds 0), { have := continuous.tendsto hφ (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ nhds (x₀, x₀)) (comap ff $ nhds (y₀, y₀))) (nhds 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (nhds (x₀, x₀))) (comap ff (nhds (y₀, y₀)))) (filter.prod (nhds 0) (nhds 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_sub_sub lim_φ }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ (comap e (nhds x₀)).sets, ∃ V₁ ∈ (comap f (nhds y₀)).sets, ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, have : ∃ x₁, x₁ ∈ U₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 de.comap_nhds_neq_bot U₁ U₁_nhd), rcases this with ⟨x₁, x₁_in⟩, have : ∃ y₁, y₁ ∈ V₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 df.comap_nhds_neq_bot V₁ V₁_nhd), rcases this with ⟨y₁, y₁_in⟩, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (continuous.comp continuous_swap hφ) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense sub-groups into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (dense_embedding.prod de df) φ) := begin let dp := dense_embedding.prod de df, refine dense_embedding.continuous_extend_of_cauchy (dense_embedding.prod de df) _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_neq_bot, intros U h, rcases exists_mem_of_ne_empty (mem_closure_iff_nhds.1 (dp.dense (x₀, y₀)) U h) with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (nhds (x₀, y₀)) (nhds (x₀, y₀)))) ≤ nhds 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage_eq, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_embedding
907f6f0999f9c0a3ddaf93b0c551f12036977f97
75bd9c50a345718d735a7533c007cf45f9da9a83
/src/measure_theory/set_integral.lean
e74b3f283925064d1ebb0294e4419ec1a00bc33f
[ "Apache-2.0" ]
permissive
jtbarker/mathlib
a1a3b1ddc16179826260578410746756ef18032c
392d3e376b44265ef2dedbd92231d3177acc1fd0
refs/heads/master
1,671,246,411,096
1,600,801,712,000
1,600,801,712,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,405
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.bochner_integration import analysis.normed_space.indicator_function /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation `∫ a in s, f a` is `measure_theory.integral (s.indicator f)` ## TODO The file ends with over a hundred lines of commented out code. This is the old contents of this file using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be migrated to the new definition. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter variables {α β E F : Type*} [measurable_space α] section piecewise variables {μ : measure α} {s : set α} {f g : α → β} lemma piecewise_ae_eq_restrict (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict s] f := begin rw [ae_restrict_eq hs], exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right end lemma piecewise_ae_eq_restrict_compl (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict sᶜ] g := begin rw [ae_restrict_eq hs.compl], exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right end end piecewise section indicator_function variables [has_zero β] {μ : measure α} {s : set α} {f : α → β} lemma indicator_ae_eq_restrict (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs lemma indicator_ae_eq_restrict_compl (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 := piecewise_ae_eq_restrict_compl hs end indicator_function namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ⊤) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty (hf : measurable f) : integrable_on f ∅ μ := by simp [integrable_on, measurable.integrable_zero hf] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ⊤ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_finite_union (hf : measurable f) {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp [hf] }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union (hf : measurable f) {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union hf s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma integrable_indicator_iff (hf : measurable f) (hs : is_measurable s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp only [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, hf, hf.indicator hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : is_measurable s) : integrable (indicator s f) μ := (integrable_indicator_iff h.measurable hs).2 h /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin rcases hμ with ⟨s, hsl, hsμ⟩, rcases hf with ⟨C, hC⟩, simp only [eventually_map] at hC, rcases hC.exists_measurable_mem with ⟨t, htl, htm, hC⟩, refine ⟨t ∩ s, inter_mem_sets htl hsl, _⟩, refine ⟨hfm, has_finite_integral_restrict_of_bounded (lt_of_le_of_lt (measure_mono $ inter_subset_right _ _) hsμ) _⟩, exact C, suffices : ∀ᵐ x ∂μ.restrict t, ∥f x∥ ≤ C, from ae_mono (measure.restrict_mono (inter_subset_left _ _) (le_refl _)) this, rw [ae_restrict_eq htm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter hfm hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto (hfm : measurable f) {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add [opens_measurable_space E] {f g : α → E} (h : univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0}) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, _, λ h, h.1.add h.2⟩, rw [← indicator_add_eq_left h], conv { congr, skip, rw [← indicator_add_eq_right h] }, rw [integrable_indicator_iff _ (hf (is_measurable_singleton 0)).compl], rw [integrable_indicator_iff _ (hg (is_measurable_singleton 0)).compl], exact ⟨hfg.integrable_on, hfg.integrable_on⟩, exact hf.add hg, exact hf.add hg end /-- To prove something for an arbitrary measurable + integrable function in a second countable Borel normed group, it suffices to show that * the property holds for (multiples of) characteristic functions; * is closed under addition; * the set of functions in the `L¹` space for which the property holds is closed. * the property is closed under the almost-everywhere equal relation. 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_sum` 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] lemma integrable.induction (P : (α → E) → Prop) (h_ind : ∀ (c : E) ⦃s⦄, is_measurable s → μ s < ⊤ → P (s.indicator (λ _, c))) (h_sum : ∀ ⦃f g : α → E⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → integrable f μ → integrable g μ → P f → P g → P (f + g)) (h_closed : is_closed {f : α →₁[μ] E | P f} ) (h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → integrable f μ → measurable g → P f → P g) : ∀ ⦃f : α → E⦄ (hf : integrable f μ), P f := begin have : ∀ (f : simple_func α E), integrable f μ → P f, { refine simple_func.induction _ _, { intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero, piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢, by_cases hc : c = 0, { subst hc, convert h_ind 0 is_measurable.empty (by simp) using 1, simp [const] }, apply h_ind c hs, have : (nnnorm c : ennreal) * μ s < ⊤, { have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ennreal)) (const α c) s, dsimp only at this, have h' := h.has_finite_integral, simpa [has_finite_integral, this, lintegral_indicator, hs] using h' }, exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) }, { intros f g hfg hf hg int_fg, rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg, refine h_sum hfg int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } }, have : ∀ (f : α →₁ₛ[μ] E), P f, { intro f, exact h_ae f.to_simple_func_eq_to_fun f.integrable (l1.measurable _) (this f.to_simple_func f.integrable) }, have : ∀ (f : α →₁[μ] E), P f := λ f, l1.simple_func.dense_range.induction_on f h_closed this, exact λ f hf, h_ae (l1.to_fun_of_fun f hf) (l1.integrable _) hf.measurable (this (l1.of_fun f hf)) end variables [complete_space E] [normed_space ℝ E] lemma integral_union (hst : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft] lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : is_measurable s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (disjoint_compl_right s) hs hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a measurable function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hfm : measurable f) (hs : is_measurable s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := have hfms : measurable (indicator s f) := hfm.indicator hs, if hfi : integrable_on f s μ then calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae hfms hfm (indicator_ae_eq_restrict hs)) (integral_congr_ae hfms measurable_const (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp else by { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hfm hs } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : is_measurable s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator measurable_const s_meas, ← set_integral_const] lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := by rw [measure.restrict_map hg hs, integral_map_measure hg hf] lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ (ae_restrict_iff $ hfm.norm is_measurable_Iic).2 hC lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ⊤) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC end normed_group end measure_theory open measure_theory asymptotics metric variables [measurable_space E] [normed_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s, f x ∂μ = μ s • b + o(μ s)` as `s` tends to `l.lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : measurable f) (hμ : μ.finite_at_filter l) : is_o (λ s : set α, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real) (l.lift' powerset) := begin simp only [is_o_iff], intros ε ε₀, have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), refine hμ.eventually.mp ((h.integrable_at_filter_ae hfm hμ).eventually.mp (this.mono _)), simp only [mem_closed_ball, dist_eq_norm], intros s h_norm h_integrable hμs, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub measurable_const) end /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hfm : measurable f) (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs (integrable_on_empty hfm) (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hfm : measurable f) (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within hfm $ λ x hx, by haveI := hs.is_measurable.nhds_within_is_measurably_generated; exact (hf x hx).integrable_at_filter hfm (μ.finite_at_nhds_within _ _) /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs hf.measurable /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure that and `f` is a measurable function that is continuous at a point `a`, then `∫ x in s, f x ∂μ = μ s • f a + o(μ s)` as `s` tends to `(𝓝 a).lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable f) : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • f a) (λ s, (μ s).to_real) ((𝓝 a).lift' powerset) := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. The first step is to prove that, given a function `φ : α → E` which is measurable and integrable, and a continuous linear map `L : E →L[ℝ] F`, the function `λ a, L(φ a)` is also measurable and integrable. Note we cannot write this as `L ∘ φ` since the type of `L` is not an actual function type. The next step is translate this to `l1`, replacing the function `φ` by a term with type `α →₁[μ] E` (an equivalence class of integrable functions). The corresponding "composition" is `L.comp_l1 φ : α →₁[μ] F`. This is then upgraded to a linear map `L.comp_l1ₗ : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F)` and a continuous linear map `L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F)`. Then we can prove the commutation result using continuity of all relevant operations and the result on simple functions. -/ variables {μ : measure α} [normed_space ℝ E] variables [normed_group F] [normed_space ℝ F] namespace continuous_linear_map lemma norm_comp_l1_apply_le [opens_measurable_space E] [second_countable_topology E] (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∀ᵐ a ∂μ, ∥L (φ a)∥ ≤ ∥L∥ * ∥φ a∥ := eventually_of_forall (λ a, L.le_op_norm (φ a)) variables [measurable_space F] [borel_space F] lemma integrable_comp [opens_measurable_space E] {φ : α → E} (L : E →L[ℝ] F) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp φ_int.measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a)) variables [borel_space E] [second_countable_topology E] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`. -/ def comp_l1 [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : α →₁[μ] F := l1.of_fun (λ a, L (φ a)) (L.integrable_comp φ.integrable) lemma comp_l1_apply [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∀ᵐ a ∂μ, (L.comp_l1 φ) a = L (φ a) := l1.to_fun_of_fun _ _ lemma integrable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : integrable (λ a, L (φ a)) μ := L.integrable_comp φ.integrable lemma measurable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : measurable (λ a, L (φ a)) := L.measurable.comp φ.measurable variables [second_countable_topology F] lemma integral_comp_l1 [complete_space F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, (L.comp_l1 φ) a ∂μ = ∫ a, L (φ a) ∂μ := by simp [comp_l1] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1ₗ (L : E →L[ℝ] F) : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F) := { to_fun := λ φ, L.comp_l1 φ, map_add' := begin intros f g, dsimp [comp_l1], rw [← l1.of_fun_add, l1.of_fun_eq_of_fun], apply (l1.add_to_fun f g).mono, intros a ha, simp only [ha, pi.add_apply, L.map_add] end, map_smul' := begin intros c f, dsimp [comp_l1], rw [← l1.of_fun_smul, l1.of_fun_eq_of_fun], apply (l1.smul_to_fun c f).mono, intros a ha, simp only [ha, pi.smul_apply, continuous_linear_map.map_smul] end } lemma norm_comp_l1_le (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∥L.comp_l1 φ∥ ≤ ∥L∥*∥φ∥ := begin erw l1.norm_of_fun_eq_integral_norm, calc ∫ a, ∥L (φ a)∥ ∂μ ≤ ∫ a, ∥L∥ *∥φ a∥ ∂μ : integral_mono (L.integrable_comp_l1 φ).norm (φ.integrable_norm.const_mul $ ∥L∥) (L.norm_comp_l1_apply_le φ) ... = ∥L∥ * ∥φ∥ : by rw [integral_mul_left, φ.norm_eq_integral_norm] end /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1L (L : E →L[ℝ] F) : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F) := linear_map.mk_continuous L.comp_l1ₗ (∥L∥) (λ φ, L.norm_comp_l1_le φ) lemma norm_compl1L_le (L : E →L[ℝ] F) : ∥(L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F))∥ ≤ ∥L∥ := op_norm_le_bound _ (norm_nonneg _) (λ φ, L.norm_comp_l1_le φ) variables [complete_space F] lemma continuous_integral_comp_l1 (L : E →L[ℝ] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := begin rw ← funext L.integral_comp_l1, exact continuous_integral.comp L.comp_l1L.continuous end variables [complete_space E] lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul, ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_l1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int g_meas hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (L.measurable.comp g_meas) (L.measurable.comp f_int.measurable) (hfg.fun_comp L).symm }, { rw integral_congr_ae g_meas f_int.measurable hfg.symm } }, all_goals { assumption } end lemma integral_comp_l1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm φ.integrable end continuous_linear_map end /- namespace integrable variables [measurable_space α] [measurable_space β] [normed_group E] protected lemma measure_mono end integrable end measure_theory section integral_on variables [measurable_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] {s t : set α} {f g : α → β} {μ : measure α} open set lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : is_measurable s) (h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ := integral_congr_ae hf hg $ _ lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ᵐ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ᵐ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact measurable.add hsm htm } end lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h } lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_on_nonneg_of_ae $ univ_mem_sets' hf lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h } lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_on_nonpos_of_ae $ univ_mem_sets' hf lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat ` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa has_sum.tsum_eq }, begin have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact is_countably_generated_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on -/
016770fdf119e028d3c4bdfcaba61dfaa20537b4
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/with_bot.lean
713a12e2cc1f8e3e36b6146698a6d901e17fff66
[ "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
2,275
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 data.nat.order.basic import algebra.order.monoid.with_top /-! # `with_bot ℕ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Lemmas about the type of natural numbers with a bottom element adjoined. -/ namespace nat namespace with_bot lemma add_eq_zero_iff {n m : with_bot ℕ} : n + m = 0 ↔ n = 0 ∧ m = 0 := begin rcases ⟨n, m⟩ with ⟨_ | _, _ | _⟩, any_goals { tautology }, repeat { erw [with_bot.coe_eq_coe] }, exact add_eq_zero_iff end lemma add_eq_one_iff {n m : with_bot ℕ} : n + m = 1 ↔ n = 0 ∧ m = 1 ∨ n = 1 ∧ m = 0 := begin rcases ⟨n, m⟩ with ⟨_ | _, _ | _⟩, any_goals { tautology }, repeat { erw [with_bot.coe_eq_coe] }, exact add_eq_one_iff end lemma add_eq_two_iff {n m : with_bot ℕ} : n + m = 2 ↔ n = 0 ∧ m = 2 ∨ n = 1 ∧ m = 1 ∨ n = 2 ∧ m = 0 := begin rcases ⟨n, m⟩ with ⟨_ | _, _ | _⟩, any_goals { tautology }, repeat { erw [with_bot.coe_eq_coe] }, exact add_eq_two_iff end lemma add_eq_three_iff {n m : with_bot ℕ} : n + m = 3 ↔ n = 0 ∧ m = 3 ∨ n = 1 ∧ m = 2 ∨ n = 2 ∧ m = 1 ∨ n = 3 ∧ m = 0 := begin rcases ⟨n, m⟩ with ⟨_ | _, _ | _⟩, any_goals { tautology }, repeat { erw [with_bot.coe_eq_coe] }, exact add_eq_three_iff end @[simp] lemma coe_nonneg {n : ℕ} : 0 ≤ (n : with_bot ℕ) := by { rw [← with_bot.coe_zero, with_bot.coe_le_coe], exact nat.zero_le _ } @[simp] lemma lt_zero_iff (n : with_bot ℕ) : n < 0 ↔ n = ⊥ := option.cases_on n dec_trivial $ λ n, iff_of_false (by simp [with_bot.some_eq_coe]) (λ h, option.no_confusion h) lemma one_le_iff_zero_lt {x : with_bot ℕ} : 1 ≤ x ↔ 0 < x := begin refine ⟨λ h, lt_of_lt_of_le (with_bot.coe_lt_coe.mpr zero_lt_one) h, λ h, _⟩, induction x using with_bot.rec_bot_coe, { exact (not_lt_bot h).elim }, { exact with_bot.coe_le_coe.mpr (nat.succ_le_iff.mpr (with_bot.coe_lt_coe.mp h)) } end lemma lt_one_iff_le_zero {x : with_bot ℕ} : x < 1 ↔ x ≤ 0 := not_iff_not.mp (by simpa using one_le_iff_zero_lt) end with_bot end nat
77c6df0d98d92e98374c8fade741c3cd2fb755bd
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/fiber.hlean
377c2ec179829de278ab12ff17f97a1dcecdba61
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
6,195
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about fibers -/ import .sigma .eq .pi .pointed open equiv sigma sigma.ops eq pi structure fiber {A B : Type} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) namespace fiber variables {A B : Type} {f : A → B} {b : B} protected definition sigma_char [constructor] (f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) := begin fapply equiv.MK, {intro x, exact ⟨point x, point_eq x⟩}, {intro x, exact (fiber.mk x.1 x.2)}, {intro x, exact abstract begin cases x, apply idp end end}, {intro x, exact abstract begin cases x, apply idp end end}, end definition fiber_eq_equiv (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := begin apply equiv.trans, apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char, apply equiv.trans, apply sigma_eq_equiv, apply sigma_equiv_sigma_right, intro p, apply pathover_eq_equiv_Fl, end definition fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : x = y := to_inv !fiber_eq_equiv ⟨p, q⟩ open is_trunc definition fiber_pr1 (B : A → Type) (a : A) : fiber (pr1 : (Σa, B a) → A) a ≃ B a := calc fiber pr1 a ≃ Σu, u.1 = a : fiber.sigma_char ... ≃ Σa' (b : B a'), a' = a : sigma_assoc_equiv ... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', !comm_equiv_nondep) ... ≃ Σu, B u.1 : sigma_assoc_equiv ... ≃ B a : !sigma_equiv_of_is_contr_left definition sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A := calc (Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, !fiber.sigma_char) ... ≃ Σa b, f a = b : sigma_comm_equiv ... ≃ A : sigma_equiv_of_is_contr_right definition is_pointed_fiber [instance] [constructor] (f : A → B) (a : A) : pointed (fiber f (f a)) := pointed.mk (fiber.mk a idp) definition pointed_fiber [constructor] (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) definition is_trunc_fun [reducible] (n : trunc_index) (f : A → B) := Π(b : B), is_trunc n (fiber f b) definition is_contr_fun [reducible] (f : A → B) := is_trunc_fun -2 f -- pre and post composition with equivalences open function protected definition equiv_postcompose {B' : Type} (g : B → B') [H : is_equiv g] : fiber (g ∘ f) (g b) ≃ fiber f b := calc fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma_right, intro a, apply equiv.symm, apply eq_equiv_fn_eq end ... ≃ fiber f b : fiber.sigma_char protected definition equiv_precompose {A' : Type} (g : A' → A) [H : is_equiv g] : fiber (f ∘ g) b ≃ fiber f b := calc fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma (equiv.mk g H), intro a', apply erfl end ... ≃ fiber f b : fiber.sigma_char end fiber open unit is_trunc pointed namespace fiber definition fiber_star_equiv (A : Type) : fiber (λx : A, star) star ≃ A := begin fapply equiv.MK, { intro f, cases f with a H, exact a }, { intro a, apply fiber.mk a, reflexivity }, { intro a, reflexivity }, { intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H, rewrite [is_set.elim H (refl star)] } end definition fiber_const_equiv (A : Type) (a₀ : A) (a : A) : fiber (λz : unit, a₀) a ≃ a₀ = a := calc fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char ... ≃ a₀ = a : sigma_unit_left -- the pointed fiber of a pointed map, which is the fiber over the basepoint definition pfiber [constructor] {X Y : Type*} (f : X →* Y) : Type* := pointed.MK (fiber f pt) (fiber.mk pt !respect_pt) definition ppoint [constructor] {X Y : Type*} (f : X →* Y) : pfiber f →* X := pmap.mk point idp end fiber open function is_equiv namespace fiber /- Theorem 4.7.6 -/ variables {A : Type} {P Q : A → Type} variable (f : Πa, P a → Q a) definition fiber_total_equiv {a : A} (q : Q a) : fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q := calc fiber (total f) ⟨a , q⟩ ≃ Σ(w : Σx, P x), ⟨w.1 , f w.1 w.2 ⟩ = ⟨a , q⟩ : fiber.sigma_char ... ≃ Σ(x : A), Σ(p : P x), ⟨x , f x p⟩ = ⟨a , q⟩ : sigma_assoc_equiv ... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_equiv_sigma_right, intro p, apply sigma_eq_equiv end ... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_comm_equiv end ... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q : sigma_assoc_equiv ... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q : sigma_equiv_of_is_contr_left ... ≃ Σ(p : P a), f a p =[idpath a] q : equiv_of_eq idp ... ≃ Σ(p : P a), f a p = q : begin apply sigma_equiv_sigma_right, intro p, apply pathover_idp end ... ≃ fiber (f a) q : fiber.sigma_char end fiber
6261530dbd53fcfe7242c9d8e4581f31f16bb43c
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/scan_test1.lean
360dca6d5379b9b4ebcf79e519956158706f4a9b
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
11
lean
print 10.0.
4ce00372370b36fa05fd54889574a9de2852f041
618003631150032a5676f229d13a079ac875ff77
/src/topology/algebra/monoid.lean
b3cfc0da5f4f35a25ffefc5e7d2e6f92b1e7c35f
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
5,669
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Theory of topological monoids. TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class `topological_operator α (*)`. -/ import topology.continuous_on import algebra.pi_instances open classical set filter topological_space open_locale classical topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_monoid /-- A topological monoid is a monoid in which the multiplication is continuous as a function `α × α → α`. -/ class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop := (continuous_mul : continuous (λp:α×α, p.1 * p.2)) /-- A topological (additive) monoid is a monoid in which the addition is continuous as a function `α × α → α`. -/ class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop := (continuous_add : continuous (λp:α×α, p.1 + p.2)) attribute [to_additive topological_add_monoid] topological_monoid section variables [topological_space α] [monoid α] [topological_monoid α] @[to_additive] lemma continuous_mul : continuous (λp:α×α, p.1 * p.2) := topological_monoid.continuous_mul @[to_additive] lemma continuous.mul [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg) @[to_additive] lemma continuous_mul_left (a : α) : continuous (λ b:α, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : α) : continuous (λ b:α, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) -- @[to_additive continuous_smul] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_id.mul (continuous_pow _) @[to_additive] lemma tendsto_mul {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp topological_monoid.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma continuous_at.mul [topological_space β] {f : β → α} {g : β → α} {x : β} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul [topological_space β] {f : β → α} {g : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} : ∀l:list γ, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive topological_add_monoid] instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ attribute [instance] prod.topological_add_monoid end section variables [topological_space α] [comm_monoid α] @[to_additive] lemma is_submonoid.mem_nhds_one (β : set α) [is_submonoid β] (oβ : is_open β) : β ∈ 𝓝 (1 : α) := mem_nhds_sets_iff.2 ⟨β, (by refl), oβ, is_submonoid.one_mem⟩ variable [topological_monoid α] @[to_additive] lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, s.prod (λc, f c b)) x (𝓝 (s.prod a)) := tendsto_multiset_prod _ @[to_additive] lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } @[to_additive] lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) : (∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) := continuous_multiset_prod _ end end topological_monoid
6b32e90dc7ca0fa6c6ecca811c0d611cc3596282
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/sheaf.lean
c8364bbfda47724648e8ccddc0f21bc36be10ed7
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,003
lean
/- Copyright (c) 2020 Kevin Buzzard, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Bhavik Mehta -/ import category_theory.sites.sheaf_of_types import category_theory.limits.yoneda import category_theory.limits.preserves.shapes.equalizers import category_theory.limits.preserves.shapes.products import category_theory.concrete_category /-! # Sheaves taking values in a category If C is a category with a Grothendieck topology, we define the notion of a sheaf taking values in an arbitrary category `A`. We follow the definition in https://stacks.math.columbia.edu/tag/00VR, noting that the presheaf of sets "defined above" can be seen in the comments between tags 00VQ and 00VR on the page https://stacks.math.columbia.edu/tag/00VL. The advantage of this definition is that we need no assumptions whatsoever on `A` other than the assumption that the morphisms in `C` and `A` live in the same universe. * An `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is defined to be a sheaf (for the topology `J`) iff for every `X : A`, the type-valued presheaves of sets given by sending `U : Cᵒᵖ` to `Hom_{A}(X, P U)` are all sheaves of sets, see `category_theory.presheaf.is_sheaf`. * When `A = Type`, this recovers the basic definition of sheaves of sets, see `category_theory.is_sheaf_iff_is_sheaf_of_type`. * An alternate definition when `C` is small, has pullbacks and `A` has products is given by an equalizer condition `category_theory.presheaf.is_sheaf'`. This is equivalent to the earlier definition, shown in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`. * When `A = Type`, this is *definitionally* equal to the equalizer condition for presieves in `category_theory.sites.sheaf_of_types`. * When `A` has limits and there is a functor `s : A ⥤ Type` which is faithful, reflects isomorphisms and preserves limits, then `P : C^op ⥤ A` is a sheaf iff the underlying presheaf of types `P ⋙ s : C^op ⥤ Type` is a sheaf (`category_theory.presheaf.is_sheaf_iff_is_sheaf_forget`). Cf https://stacks.math.columbia.edu/tag/0073, which is a weaker version of this statement (it's only over spaces, not sites) and https://stacks.math.columbia.edu/tag/00YR (a), which additionally assumes filtered colimits. -/ universes w v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open opposite category_theory category limits sieve classical namespace presheaf variables {C : Type u₁} [category.{v₁} C] variables {A : Type u₂} [category.{v₂} A] variables (J : grothendieck_topology C) -- We follow https://stacks.math.columbia.edu/tag/00VL definition 00VR /-- A sheaf of A is a presheaf P : C^op => A such that for every X : A, the presheaf of types given by sending U : C to Hom_{A}(X, P U) is a sheaf of types. https://stacks.math.columbia.edu/tag/00VR -/ def is_sheaf (P : Cᵒᵖ ⥤ A) : Prop := ∀ X : A, presieve.is_sheaf J (P ⋙ coyoneda.obj (op X)) end presheaf variables {C : Type u₁} [category.{v₁} C] variables (J : grothendieck_topology C) variables (A : Type u₂) [category.{v₂} A] /-- The category of sheaves taking values in `A` on a grothendieck topology. -/ @[derive category] def Sheaf : Type* := {P : Cᵒᵖ ⥤ A // presheaf.is_sheaf J P} /-- The inclusion functor from sheaves to presheaves. -/ @[simps {rhs_md := semireducible}, derive [full, faithful]] def Sheaf_to_presheaf : Sheaf J A ⥤ (Cᵒᵖ ⥤ A) := full_subcategory_inclusion (presheaf.is_sheaf J) /-- The sheaf of sections guaranteed by the sheaf condition. -/ @[simps] abbreviation sheaf_over {A : Type u₂} [category.{v₂} A] {J : grothendieck_topology C} (ℱ : Sheaf J A) (X : A) : SheafOfTypes J := ⟨ℱ.val ⋙ coyoneda.obj (op X), ℱ.property X⟩ lemma is_sheaf_iff_is_sheaf_of_type (P : Cᵒᵖ ⥤ Type w) : presheaf.is_sheaf J P ↔ presieve.is_sheaf J P := begin split, { intros hP, refine presieve.is_sheaf_iso J _ (hP punit), exact iso_whisker_left _ coyoneda.punit_iso ≪≫ P.right_unitor }, { intros hP X Y S hS z hz, refine ⟨λ x, (hP S hS).amalgamate (λ Z f hf, z f hf x) _, _, _⟩, { intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ h, exact congr_fun (hz g₁ g₂ hf₁ hf₂ h) x }, { intros Z f hf, ext x, apply presieve.is_sheaf_for.valid_glue }, { intros y hy, ext x, apply (hP S hS).is_separated_for.ext, intros Y' f hf, rw [presieve.is_sheaf_for.valid_glue _ _ _ hf, ← hy _ hf], refl } } end /-- The category of sheaves taking values in Type is the same as the category of set-valued sheaves. -/ @[simps] def Sheaf_equiv_SheafOfTypes : Sheaf J (Type w) ≌ SheafOfTypes J := { functor := { obj := λ S, ⟨S.1, (is_sheaf_iff_is_sheaf_of_type _ _).1 S.2⟩, map := λ S₁ S₂ f, f }, inverse := { obj := λ S, ⟨S.1, (is_sheaf_iff_is_sheaf_of_type _ _).2 S.2⟩, map := λ S₁ S₂ f, f }, unit_iso := nat_iso.of_components (λ X, ⟨𝟙 _, 𝟙 _, by tidy, by tidy⟩) (by tidy), counit_iso := nat_iso.of_components (λ X, ⟨𝟙 _, 𝟙 _, by tidy, by tidy⟩) (by tidy) } instance : inhabited (Sheaf (⊥ : grothendieck_topology C) (Type w)) := ⟨(Sheaf_equiv_SheafOfTypes _).inverse.obj (default _)⟩ end category_theory namespace category_theory open opposite category_theory category limits sieve classical namespace presheaf -- Under here is the equalizer story, which is equivalent if A has products (and doesn't -- make sense otherwise). It's described in https://stacks.math.columbia.edu/tag/00VL, -- between 00VQ and 00VR. variables {C : Type u₁} [category.{v₁} C] variables {A : Type u₂} [category.{max v₁ u₁} A] variables (J : grothendieck_topology C) variables {U : C} (R : presieve U) variables (P : Cᵒᵖ ⥤ A) section variables [has_products A] /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def first_obj : A := ∏ (λ (f : Σ V, {f : V ⟶ U // R f}), P.obj (op f.1)) /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def fork_map : P.obj (op U) ⟶ first_obj R P := pi.lift (λ f, P.map f.2.1.op) variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : A := ∏ (λ (fg : (Σ V, {f : V ⟶ U // R f}) × (Σ W, {g : W ⟶ U // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VM. -/ def first_map : first_obj R P ⟶ second_obj R P := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) /-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VM. -/ def second_map : first_obj R P ⟶ second_obj R P := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map R P ≫ first_map R P = fork_map R P ≫ second_map R P := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map, limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- An alternative definition of the sheaf condition in terms of equalizers. This is shown to be equivalent in `category_theory.presheaf.is_sheaf_iff_is_sheaf'`. -/ def is_sheaf' (P : Cᵒᵖ ⥤ A) : Prop := ∀ (U : C) (R : presieve U) (hR : generate R ∈ J U), nonempty (is_limit (fork.of_ι _ (w R P))) /-- (Implementation). An auxiliary lemma to convert between sheaf conditions. -/ def is_sheaf_for_is_sheaf_for' (P : Cᵒᵖ ⥤ A) (s : A ⥤ Type (max v₁ u₁)) [Π J, preserves_limits_of_shape (discrete J) s] (U : C) (R : presieve U) : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (equalizer.presieve.w (P ⋙ s) R)) := begin apply equiv.trans (is_limit_map_cone_fork_equiv _ _) _, apply (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _), { apply nat_iso.of_components _ _, { rintro (_ | _), { apply preserves_product.iso s }, { apply preserves_product.iso s } }, { rintro _ _ (_ | _), { ext : 1, dsimp [equalizer.presieve.first_map, first_map], simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp], erw pi_comparison_comp_π_assoc }, { ext : 1, dsimp [equalizer.presieve.second_map, second_map], simp only [limit.lift_π, map_lift_pi_comparison, assoc, fan.mk_π_app, functor.map_comp], erw pi_comparison_comp_π_assoc }, { dsimp, simp } } }, { refine fork.ext (iso.refl _) _, dsimp [equalizer.fork_map, fork_map], simp } end /-- The equalizer definition of a sheaf given by `is_sheaf'` is equivalent to `is_sheaf`. -/ theorem is_sheaf_iff_is_sheaf' : is_sheaf J P ↔ is_sheaf' J P := begin split, { intros h U R hR, refine ⟨_⟩, apply coyoneda_jointly_reflects_limits, intro X, have q : presieve.is_sheaf_for (P ⋙ coyoneda.obj X) _ := h X.unop _ hR, rw ←presieve.is_sheaf_for_iff_generate at q, rw equalizer.presieve.sheaf_condition at q, replace q := classical.choice q, apply (is_sheaf_for_is_sheaf_for' _ _ _ _).symm q }, { intros h U X S hS, rw equalizer.presieve.sheaf_condition, refine ⟨_⟩, refine is_sheaf_for_is_sheaf_for' _ _ _ _ _, apply is_limit_of_preserves, apply classical.choice (h _ S _), simpa } end end section concrete variables [has_pullbacks C] /-- For a concrete category `(A, s)` where the forgetful functor `s : A ⥤ Type v` preserves limits and reflects isomorphisms, and `A` has limits, an `A`-valued presheaf `P : Cᵒᵖ ⥤ A` is a sheaf iff its underlying `Type`-valued presheaf `P ⋙ s : Cᵒᵖ ⥤ Type` is a sheaf. Note this lemma applies for "algebraic" categories, eg groups, abelian groups and rings, but not for the category of topological spaces, topological rings, etc since reflecting isomorphisms doesn't hold. -/ lemma is_sheaf_iff_is_sheaf_forget (s : A ⥤ Type (max v₁ u₁)) [has_limits A] [preserves_limits s] [reflects_isomorphisms s] : is_sheaf J P ↔ is_sheaf J (P ⋙ s) := begin rw [is_sheaf_iff_is_sheaf', is_sheaf_iff_is_sheaf'], apply forall_congr (λ U, _), apply ball_congr (λ R hR, _), letI : reflects_limits s := reflects_limits_of_reflects_isomorphisms, have : is_limit (s.map_cone (fork.of_ι _ (w R P))) ≃ is_limit (fork.of_ι _ (w R (P ⋙ s))) := is_sheaf_for_is_sheaf_for' P s U R, rw ←equiv.nonempty_congr this, split, { exact nonempty.map (λ t, is_limit_of_preserves s t) }, { exact nonempty.map (λ t, is_limit_of_reflects s t) } end end concrete end presheaf end category_theory
a949f0e73e7c87ba061ade244f1fa4d3b8234b4a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/dedekind_domain/ideal.lean
78f6e62740ad2df0fd7bf1c40107f90fa95a4fc4
[ "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
58,182
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import algebra.algebra.subalgebra.pointwise import algebraic_geometry.prime_spectrum.noetherian import order.hom.basic import ring_theory.dedekind_domain.basic import ring_theory.fractional_ideal import ring_theory.principal_ideal_domain import ring_theory.chain_of_divisors /-! # Dedekind domains and ideals In this file, we show a ring is a Dedekind domain iff all fractional ideals are invertible. Then we prove some results on the unique factorization monoid structure of the ideals. ## Main definitions - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. - `is_dedekind_domain.height_one_spectrum` defines the type of nonzero prime ideals of `R`. ## Main results: - `is_dedekind_domain_iff_is_dedekind_domain_inv` - `ideal.unique_factorization_monoid` ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial variables [is_domain A] section inverse namespace fractional_ideal variables {R₁ : Type*} [comm_ring R₁] [is_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K] variables {I J : fractional_ideal R₁⁰ K} noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J := by { rwa inv_nonzero _, refl, assumption } variables {K} lemma mem_inv_iff (hI : I ≠ 0) {x : K} : x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) := fractional_ideal.mem_div_iff_of_nonzero hI lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) : J⁻¹ ≤ I⁻¹ := λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) } lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * I⁻¹ := fractional_ideal.le_self_mul_one_div hI variables (K) lemma coe_ideal_le_self_mul_inv (I : ideal R₁) : (I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ := le_self_mul_inv fractional_ideal.coe_ideal_le_one /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩ lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ is_unit I := (mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : K) : (fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv {R₁ : Type*} [comm_ring R₁] [algebra R₁ K] [is_localization R₁⁰ K] (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹, mul_generator_self_inv _ I h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ K))⁻¹, have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1, apply mul_generator_self_inv _ I h, exact (right_inverse_eq _ I (fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹)) hI).symm end @[simp] lemma inv_one : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 := fractional_ideal.div_one end fractional_ideal /-- A Dedekind domain is an integral domain such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. In particular we provide a `fractional_ideal.comm_group_with_zero` instance, assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals, `is_dedekind_domain`(`_inv`) implies only `ideal.cancel_comm_monoid_with_zero`. -/ def is_dedekind_domain_inv : Prop := ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1 open fractional_ideal variables {R A K} lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] : is_dedekind_domain_inv A ↔ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) := begin let h := fractional_ideal.map_equiv (fraction_ring.alg_equiv A K), refine h.to_equiv.forall_congr (λ I, _), rw ← h.to_equiv.apply_eq_iff_eq, simp [is_dedekind_domain_inv, show ⇑h.to_equiv = h, from rfl], end lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K] (x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) : adjoin_integral A⁰ x hx = 1 := begin set I := adjoin_integral A⁰ x hx, have mul_self : I * I = I, { apply fractional_ideal.coe_to_submodule_injective, simp }, convert congr_arg (* I⁻¹) mul_self; simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one], end namespace is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A) include h lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 := is_dedekind_domain_inv_iff.mp h I hI lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 := (mul_comm _ _).trans (h.mul_inv_eq_one hI) protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I := is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI) lemma is_noetherian_ring : is_noetherian_ring A := begin refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩, by_cases hI : I = ⊥, { rw hI, apply submodule.fg_bot }, have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI) end lemma integrally_closed : is_integrally_closed A := begin -- It suffices to show that for integral `x`, -- `A[x]` (which is a fractional ideal) is in fact equal to `A`. refine ⟨λ x hx, _⟩, rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot, ← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one, ← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)], { exact mem_adjoin_integral_self A⁰ x hx }, { exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) }, end open ring lemma dimension_le_one : dimension_le_one A := begin -- We're going to show that `P` is maximal because any (maximal) ideal `M` -- that is strictly larger would be `⊤`. rintros P P_ne hP, refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩, -- We may assume `P` and `M` (as fractional ideals) are nonzero. have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne, have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr (lt_of_le_of_lt bot_le hM).ne', -- In particular, we'll show `M⁻¹ * P ≤ P` suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P, { rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top], calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _ ... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this ... = M : _, { rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] }, { rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] }, { apply_instance } }, -- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`. intros x hx, have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1, { rw [← h.inv_mul_eq_one M'_ne], exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) }, obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx), -- Since `M` is strictly greater than `P`, let `z ∈ M \ P`. obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM, -- We have `z * y ∈ M * (M⁻¹ * P) = P`. have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx, rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem, obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem, rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy, -- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired. exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp) end /-- Showing one side of the equivalence between the definitions `is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/ theorem is_dedekind_domain : is_dedekind_domain A := ⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩ end is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] /-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains: Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field. Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime ideals that is contained within `I`. This lemma extends that result by making the product minimal: let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I` and the product excluding `M` is not contained within `I`. -/ lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A] (hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] : ∃ (Z : multiset (prime_spectrum A)), (M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧ ¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) := begin -- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`. obtain ⟨Z₀, hZ₀⟩ := prime_spectrum.exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0, obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min (λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥) ⟨Z₀, hZ₀⟩, have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM, have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM }, obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM, -- Then in fact there is a `P ∈ Z` with `P ≤ M`. obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ', letI := classical.dec_eq (ideal A), have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z, obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥, { rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot, not_or_distrib, ← this] at hprodZ }, -- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`. have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM, substI hPM', -- By minimality of `Z`, erasing `P` from `Z` is exactly what we need. refine ⟨Z.erase P, _, _⟩, { convert hZI, rw [this, multiset.cons_erase hPZ'] }, { refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ), exact hZP0 } end namespace fractional_ideal open ideal lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A] (hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : ∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) := begin -- WLOG, let `I` be maximal. suffices : ∀ {M : ideal A} (hM : M.is_maximal), ∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K), { obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1, resetI, have hM0 := (M.bot_lt_of_maximal hNF).ne', obtain ⟨x, hxM, hx1⟩ := this hM, refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩; apply fractional_ideal.coe_ideal_ne_zero; assumption }, -- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`. intros M hM, resetI, obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF), replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0, let J : ideal A := ideal.span {a}, have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0, have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM), have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF, -- Then we can find a product of prime (hence maximal) ideals contained in `J`, -- such that removing element `M` from the product is not contained in `J`. obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM, -- Choose an element `b` of the product that is not in `J`. obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle, have hnz_fa : algebra_map A K a ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (is_fraction_ring.injective A K) a) ha0, have hb0 : algebra_map A K b ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (is_fraction_ring.injective A K) b) (λ h, hbJ $ h.symm ▸ J.zero_mem), -- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`. refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩, { exact (fractional_ideal.coe_to_fractional_ideal_ne_zero le_rfl).mpr hM0.ne' }, { rintro y₀ hy₀, obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀, rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul], have h_yb : y * b ∈ J, { apply hle, rw multiset.prod_cons, exact submodule.smul_mem_smul h_Iy hbZ }, rw ideal.mem_span_singleton' at h_yb, rcases h_yb with ⟨c, hc⟩, rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one], apply fractional_ideal.coe_mem_one }, { refine mt (fractional_ideal.mem_one_iff _).mp _, rintros ⟨x', h₂_abs⟩, rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs, have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩, contradiction }, end lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) : (1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ := begin rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI), intros y hy, rw one_mul, exact coe_ideal_le_one hy, assumption end lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A] {I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- Handle a few trivial cases. by_cases hI1 : I = ⊤, { rw [hI1, coe_ideal_top, one_mul, fractional_ideal.inv_one] }, by_cases hNF : is_field A, { letI := hNF.to_field, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) }, -- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`: -- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`. obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ := le_one_iff_exists_coe_ideal.mp mul_one_div_le_one, by_cases hJ0 : J = ⊥, { subst hJ0, refine absurd _ hI0, rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ], exact coe_ideal_le_self_mul_inv K I, apply_instance }, by_cases hJ1 : J = ⊤, { rw [← hJ, hJ1, coe_ideal_top] }, obtain ⟨x, hx, hx1⟩ : ∃ (x : K), x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) := exists_not_mem_one_of_ne_bot hNF hJ0 hJ1, contrapose! hx1 with h_abs, rw hJ at hx, exact hI hx, end /-- Nonzero integral ideals in a Dedekind domain are invertible. We will use this to show that nonzero fractional ideals are invertible, and finally conclude that fractional ideals in a Dedekind domain form a group with zero. -/ lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`. apply mul_inv_cancel_of_le_one hI0, by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0, { rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ }, intros x hx, -- In particular, we'll show all `x ∈ J⁻¹` are integral. suffices : x ∈ integral_closure A K, { rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range, ← fractional_ideal.mem_one_iff] at this; assumption }, -- For that, we'll find a subalgebra that is f.g. as a module and contains `x`. -- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`. rw mem_integral_closure_iff_mem_fg, have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K), { intros b hb, rw mem_inv_iff at ⊢ hx, swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 }, swap, { exact hJ0 }, simp only [mul_assoc, mul_comm b] at ⊢ hx, intros y hy, exact hx _ (fractional_ideal.mul_mem_mul hy hb) }, -- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works. refine ⟨alg_hom.range (polynomial.aeval x : A[X] →ₐ[A] K), is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _), ⟨polynomial.X, polynomial.aeval_X x⟩⟩, obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy, rw polynomial.aeval_eq_sum_range, refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _), clear hi, induction i with i ih, { rw pow_zero, exact one_mem_inv_coe_ideal hI0 }, { show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K), rw pow_succ, exact x_mul_mem _ ih }, end /-- Nonzero fractional ideals in a Dedekind domain are units. This is also available as `_root_.mul_inv_cancel`, using the `comm_group_with_zero` instance defined below. -/ protected theorem mul_inv_cancel [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 := begin obtain ⟨a, J, ha, hJ⟩ : ∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI := exists_eq_span_singleton_mul I, suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1, { rw mul_inv_cancel_iff, exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ }, subst hJ, rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one, fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel, fractional_ideal.span_singleton_one], { exact mt ((injective_iff_map_eq_zero (algebra_map A K)).mp (is_fraction_ring.injective A K) _) ha }, { exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) } end lemma mul_right_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) : ∀ {I I'}, I * J ≤ I' * J ↔ I ≤ I' := begin intros I I', split, { intros h, convert mul_right_mono J⁻¹ h; rw [mul_assoc, fractional_ideal.mul_inv_cancel hJ, mul_one] }, { exact λ h, mul_right_mono J h } end lemma mul_left_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) {I I'} : J * I ≤ J * I' ↔ I ≤ I' := by convert fractional_ideal.mul_right_le_iff hJ using 1; simp only [mul_comm] lemma mul_right_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono (* I) := strict_mono_of_le_iff_le (λ _ _, (mul_right_le_iff hI).symm) lemma mul_left_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono ((*) I) := strict_mono_of_le_iff_le (λ _ _, (mul_left_le_iff hI).symm) /-- This is also available as `_root_.div_eq_mul_inv`, using the `comm_group_with_zero` instance defined below. -/ protected lemma div_eq_mul_inv [is_dedekind_domain A] (I J : fractional_ideal A⁰ K) : I / J = I * J⁻¹ := begin by_cases hJ : J = 0, { rw [hJ, div_zero, inv_zero', mul_zero] }, refine le_antisymm ((mul_right_le_iff hJ).mp _) ((le_div_iff_mul_le hJ).mpr _), { rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one, mul_le], intros x hx y hy, rw [mem_div_iff_of_nonzero hJ] at hx, exact hx y hy }, rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one], exact le_refl I end end fractional_ideal /-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways to express that an integral domain is a Dedekind domain. -/ theorem is_dedekind_domain_iff_is_dedekind_domain_inv : is_dedekind_domain A ↔ is_dedekind_domain_inv A := ⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩ end inverse section is_dedekind_domain variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K] open fractional_ideal open ideal noncomputable instance fractional_ideal.semifield : semifield (fractional_ideal A⁰ K) := { inv := λ I, I⁻¹, inv_zero := inv_zero' _, div := (/), div_eq_mul_inv := fractional_ideal.div_eq_mul_inv, exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective le_rfl).ne (by simpa using @zero_ne_one (ideal A) _ _)⟩, mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel, .. fractional_ideal.comm_semiring } /-- Fractional ideals have cancellative multiplication in a Dedekind domain. Although this instance is a direct consequence of the instance `fractional_ideal.comm_group_with_zero`, we define this instance to provide a computable alternative. -/ instance fractional_ideal.cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero (fractional_ideal A⁰ K) := { .. fractional_ideal.comm_semiring, -- Project out the computable fields first. .. (by apply_instance : cancel_comm_monoid_with_zero (fractional_ideal A⁰ K)) } instance ideal.cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero (ideal A) := { .. ideal.comm_semiring, .. function.injective.cancel_comm_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A)) coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _) (ring_hom.map_pow _) } /-- For ideals in a Dedekind domain, to divide is to contain. -/ lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I := ⟨ideal.le_of_dvd, λ h, begin by_cases hI : I = ⊥, { have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h }, rw [hI, hJ] }, have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans (fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h)) (le_of_eq (inv_mul_cancel hI')), obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this, use H, refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A)) (show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _), rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul] end⟩ lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} : dvd_not_unit I J ↔ J < I := ⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩) (mt (λ h, have H = 1, from mul_left_cancel₀ hI (by rw [← hmul, h, mul_one]), show is_unit H, from this.symm ▸ is_unit_one) hunit), λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h)) (mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩ instance : wf_dvd_monoid (ideal A) := { well_founded_dvd_not_unit := have well_founded ((>) : ideal A → ideal A → Prop) := is_noetherian_iff_well_founded.mp (is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring), by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } } instance ideal.unique_factorization_monoid : unique_factorization_monoid (ideal A) := { irreducible_iff_prime := λ P, ⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin have : P.is_maximal, { refine ⟨⟨mt ideal.is_unit_iff.mpr hirr.not_unit, _⟩⟩, intros J hJ, obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ, exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) }, rw [ideal.dvd_iff_le, ideal.dvd_iff_le, ideal.dvd_iff_le, set_like.le_def, set_like.le_def, set_like.le_def], contrapose!, rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩, exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem, mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩, end⟩, prime.irreducible⟩, .. ideal.wf_dvd_monoid } instance ideal.normalization_monoid : normalization_monoid (ideal A) := normalization_monoid_of_unique_units @[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} : I ∣ ideal.span {x} ↔ x ∈ I := ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff) lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P := begin refine ⟨_, λ x y hxy, _⟩, { unfreezingI { rintro rfl }, rw ← ideal.one_eq_top at h, exact h.not_unit is_unit_one }, { simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy, exact h.dvd_or_dvd hxy } end theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P := begin refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩, simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)), end /-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A` are exactly the prime ideals. -/ theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) : prime P ↔ is_prime P := ⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩ /-- In a Dedekind domain, the the prime ideals are the zero ideal together with the prime elements of the monoid with zero `ideal A`. -/ theorem ideal.is_prime_iff_bot_or_prime {P : ideal A} : is_prime P ↔ P = ⊥ ∨ prime P := ⟨λ hp, (eq_or_ne P ⊥).imp_right $ λ hp0, (ideal.prime_of_is_prime hp0 hp), λ hp, hp.elim (λ h, h.symm ▸ ideal.bot_prime) ideal.is_prime_of_prime⟩ lemma ideal.strict_anti_pow (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : strict_anti ((^) I : ℕ → ideal A) := strict_anti_nat_of_succ_lt $ λ e, ideal.dvd_not_unit_iff_lt.mp ⟨pow_ne_zero _ hI0, I, mt is_unit_iff.mp hI1, pow_succ' I e⟩ lemma ideal.pow_lt_self (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) (e : ℕ) (he : 2 ≤ e) : I^e < I := by convert I.strict_anti_pow hI0 hI1 he; rw pow_one lemma ideal.exists_mem_pow_not_mem_pow_succ (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) (e : ℕ) : ∃ x ∈ I^e, x ∉ I^(e+1) := set_like.exists_of_lt (I.strict_anti_pow hI0 hI1 e.lt_succ_self) lemma associates.le_singleton_iff (x : A) (n : ℕ) (I : ideal A) : associates.mk I^n ≤ associates.mk (ideal.span {x}) ↔ x ∈ I^n := begin rw [← associates.dvd_eq_le, ← associates.mk_pow, associates.mk_dvd_mk, ideal.dvd_span_singleton], end open fractional_ideal variables {A K} /-- Strengthening of `is_localization.exist_integer_multiples`: Let `J ≠ ⊤` be an ideal in a Dedekind domain `A`, and `f ≠ 0` a finite collection of elements of `K = Frac(A)`, then we can multiply the elements of `f` by some `a : K` to find a collection of elements of `A` that is not completely contained in `J`. -/ lemma ideal.exist_integer_multiples_not_mem {J : ideal A} (hJ : J ≠ ⊤) {ι : Type*} (s : finset ι) (f : ι → K) {j} (hjs : j ∈ s) (hjf : f j ≠ 0) : ∃ a : K, (∀ i ∈ s, is_localization.is_integer A (a * f i)) ∧ ∃ i ∈ s, (a * f i) ∉ (J : fractional_ideal A⁰ K) := begin -- Consider the fractional ideal `I` spanned by the `f`s. let I : fractional_ideal A⁰ K := fractional_ideal.span_finset A s f, have hI0 : I ≠ 0 := fractional_ideal.span_finset_ne_zero.mpr ⟨j, hjs, hjf⟩, -- We claim the multiplier `a` we're looking for is in `I⁻¹ \ (J / I)`. suffices : ↑J / I < I⁻¹, { obtain ⟨_, a, hI, hpI⟩ := set_like.lt_iff_le_and_exists.mp this, rw mem_inv_iff hI0 at hI, refine ⟨a, λ i hi, _, _⟩, -- By definition, `a ∈ I⁻¹` multiplies elements of `I` into elements of `1`, -- in other words, `a * f i` is an integer. { exact (mem_one_iff _).mp (hI (f i) (submodule.subset_span (set.mem_image_of_mem f hi))) }, { contrapose! hpI, -- And if all `a`-multiples of `I` are an element of `J`, -- then `a` is actually an element of `J / I`, contradiction. refine (mem_div_iff_of_nonzero hI0).mpr (λ y hy, submodule.span_induction hy _ _ _ _), { rintros _ ⟨i, hi, rfl⟩, exact hpI i hi }, { rw mul_zero, exact submodule.zero_mem _ }, { intros x y hx hy, rw mul_add, exact submodule.add_mem _ hx hy }, { intros b x hx, rw mul_smul_comm, exact submodule.smul_mem _ b hx } } }, -- To show the inclusion of `J / I` into `I⁻¹ = 1 / I`, note that `J < I`. calc ↑J / I = ↑J * I⁻¹ : div_eq_mul_inv ↑J I ... < 1 * I⁻¹ : mul_right_strict_mono (inv_ne_zero hI0) _ ... = I⁻¹ : one_mul _, { rw [← coe_ideal_top], -- And multiplying by `I⁻¹` is indeed strictly monotone. exact strict_mono_of_le_iff_le (λ _ _, (coe_ideal_le_coe_ideal K).symm) (lt_top_iff_ne_top.mpr hJ) }, end end is_dedekind_domain section is_dedekind_domain variables {T : Type*} [comm_ring T] [is_domain T] [is_dedekind_domain T] {I J : ideal T} open_locale classical open multiset unique_factorization_monoid ideal lemma prod_normalized_factors_eq_self (hI : I ≠ ⊥) : (normalized_factors I).prod = I := associated_iff_eq.1 (normalized_factors_prod hI) lemma count_le_of_ideal_ge {I J : ideal T} (h : I ≤ J) (hI : I ≠ ⊥) (K : ideal T) : count K (normalized_factors J) ≤ count K (normalized_factors I) := le_iff_count.1 ((dvd_iff_normalized_factors_le_normalized_factors (ne_bot_of_le_ne_bot hI h) hI).1 (dvd_iff_le.2 h)) _ lemma sup_eq_prod_inf_factors (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : I ⊔ J = (normalized_factors I ∩ normalized_factors J).prod := begin have H : normalized_factors (normalized_factors I ∩ normalized_factors J).prod = normalized_factors I ∩ normalized_factors J, { apply normalized_factors_prod_of_prime, intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, have := (multiset.prod_ne_zero_of_prime (normalized_factors I ∩ normalized_factors J) (λ _ h, prime_of_normalized_factor _ (multiset.mem_inter.1 h).1)), apply le_antisymm, { rw [sup_le_iff, ← dvd_iff_le, ← dvd_iff_le], split, { rw [dvd_iff_normalized_factors_le_normalized_factors this hI, H], exact inf_le_left }, { rw [dvd_iff_normalized_factors_le_normalized_factors this hJ, H], exact inf_le_right } }, { rw [← dvd_iff_le, dvd_iff_normalized_factors_le_normalized_factors, normalized_factors_prod_of_prime, le_iff_count], { intro a, rw multiset.count_inter, exact le_min (count_le_of_ideal_ge le_sup_left hI a) (count_le_of_ideal_ge le_sup_right hJ a) }, { intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, { exact ne_bot_of_le_ne_bot hI le_sup_left }, { exact this } }, end lemma irreducible_pow_sup (hI : I ≠ ⊥) (hJ : irreducible J) (n : ℕ) : J^n ⊔ I = J^(min ((normalized_factors I).count J) n) := by rw [sup_eq_prod_inf_factors (pow_ne_zero n hJ.ne_zero) hI, ← inf_eq_inter, normalized_factors_of_irreducible_pow hJ, normalize_eq J, repeat_inf, prod_repeat] lemma irreducible_pow_sup_of_le (hJ : irreducible J) (n : ℕ) (hn : ↑n ≤ multiplicity J I) : J^n ⊔ I = J^n := begin by_cases hI : I = ⊥, { simp [*] at *, }, rw [irreducible_pow_sup hI hJ, min_eq_right], rwa [multiplicity_eq_count_normalized_factors hJ hI, part_enat.coe_le_coe, normalize_eq J] at hn end lemma irreducible_pow_sup_of_ge (hI : I ≠ ⊥) (hJ : irreducible J) (n : ℕ) (hn : multiplicity J I ≤ n) : J^n ⊔ I = J ^ (multiplicity J I).get (part_enat.dom_of_le_coe hn) := begin rw [irreducible_pow_sup hI hJ, min_eq_left], congr, { rw [← part_enat.coe_inj, part_enat.coe_get, multiplicity_eq_count_normalized_factors hJ hI, normalize_eq J] }, { rwa [multiplicity_eq_count_normalized_factors hJ hI, part_enat.coe_le_coe, normalize_eq J] at hn } end end is_dedekind_domain section height_one_spectrum /-! ### Height one spectrum of a Dedekind domain If `R` is a Dedekind domain of Krull dimension 1, the maximal ideals of `R` are exactly its nonzero prime ideals. We define `height_one_spectrum` and provide lemmas to recover the facts that prime ideals of height one are prime and irreducible. -/ namespace is_dedekind_domain variables [is_domain R] [is_dedekind_domain R] /-- The height one prime spectrum of a Dedekind domain `R` is the type of nonzero prime ideals of `R`. Note that this equals the maximal spectrum if `R` has Krull dimension 1. -/ @[ext, nolint has_nonempty_instance unused_arguments] structure height_one_spectrum := (as_ideal : ideal R) (is_prime : as_ideal.is_prime) (ne_bot : as_ideal ≠ ⊥) variables (v : height_one_spectrum R) {R} lemma height_one_spectrum.prime (v : height_one_spectrum R) : prime v.as_ideal := ideal.prime_of_is_prime v.ne_bot v.is_prime lemma height_one_spectrum.irreducible (v : height_one_spectrum R) : irreducible v.as_ideal := begin rw [unique_factorization_monoid.irreducible_iff_prime], apply v.prime, end lemma height_one_spectrum.associates_irreducible (v : height_one_spectrum R) : irreducible (associates.mk v.as_ideal) := begin rw [associates.irreducible_mk _], apply v.irreducible, end end is_dedekind_domain end height_one_spectrum section open ideal variables {R} {A} [is_dedekind_domain A] {I : ideal R} {J : ideal A} /-- The map from ideals of `R` dividing `I` to the ideals of `A` dividing `J` induced by a homomorphism `f : R/I →+* A/J` -/ @[simps] def ideal_factors_fun_of_quot_hom {f : R ⧸ I →+* A ⧸ J} (hf : function.surjective f ) : {p : ideal R | p ∣ I} →o {p : ideal A | p ∣ J} := { to_fun := λ X, ⟨comap J^.quotient.mk (map f (map I^.quotient.mk X)), begin have : (J^.quotient.mk).ker ≤ comap J^.quotient.mk (map f (map I^.quotient.mk X)), { exact ker_le_comap J^.quotient.mk }, rw mk_ker at this, exact dvd_iff_le.mpr this, end ⟩, monotone' := begin rintros ⟨X, hX⟩ ⟨Y, hY⟩ h, rw [← subtype.coe_le_coe, subtype.coe_mk, subtype.coe_mk] at h ⊢, rw [subtype.coe_mk, comap_le_comap_iff_of_surjective J^.quotient.mk quotient.mk_surjective, map_le_iff_le_comap, subtype.coe_mk, comap_map_of_surjective _ hf (map I^.quotient.mk Y)], suffices : map I^.quotient.mk X ≤ map I^.quotient.mk Y, { exact le_sup_of_le_left this }, rwa [map_le_iff_le_comap, comap_map_of_surjective I^.quotient.mk quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, mk_ker, sup_eq_left.mpr $ le_of_dvd hY], end } @[simp] lemma ideal_factors_fun_of_quot_hom_id : ideal_factors_fun_of_quot_hom (ring_hom.id (A ⧸ J)).is_surjective = order_hom.id := order_hom.ext _ _ (funext $ λ X, by simp only [ideal_factors_fun_of_quot_hom, map_id, order_hom.coe_fun_mk, order_hom.id_coe, id.def, comap_map_of_surjective J^.quotient.mk quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot J^.quotient.mk, mk_ker, sup_eq_left.mpr (dvd_iff_le.mp X.prop), subtype.coe_eta] ) variables {B : Type*} [comm_ring B] [is_domain B] [is_dedekind_domain B] {L : ideal B} lemma ideal_factors_fun_of_quot_hom_comp {f : R ⧸ I →+* A ⧸ J} {g : A ⧸ J →+* B ⧸ L} (hf : function.surjective f) (hg : function.surjective g) : (ideal_factors_fun_of_quot_hom hg).comp (ideal_factors_fun_of_quot_hom hf) = ideal_factors_fun_of_quot_hom (show function.surjective (g.comp f), from hg.comp hf) := begin refine order_hom.ext _ _ (funext $ λ x, _), rw [ideal_factors_fun_of_quot_hom, ideal_factors_fun_of_quot_hom, order_hom.comp_coe, order_hom.coe_fun_mk, order_hom.coe_fun_mk, function.comp_app, ideal_factors_fun_of_quot_hom, order_hom.coe_fun_mk, subtype.mk_eq_mk, subtype.coe_mk, map_comap_of_surjective J^.quotient.mk quotient.mk_surjective, map_map], end variables [is_domain R] [is_dedekind_domain R] (f : R ⧸ I ≃+* A ⧸ J) /-- The bijection between ideals of `R` dividing `I` and the ideals of `A` dividing `J` induced by an isomorphism `f : R/I ≅ A/J`. -/ @[simps] def ideal_factors_equiv_of_quot_equiv : {p : ideal R | p ∣ I} ≃o {p : ideal A | p ∣ J} := order_iso.of_hom_inv (ideal_factors_fun_of_quot_hom (show function.surjective (f : R ⧸I →+* A ⧸ J), from f.surjective)) (ideal_factors_fun_of_quot_hom (show function.surjective (f.symm : A ⧸J →+* R ⧸ I), from f.symm.surjective)) (by simp only [← ideal_factors_fun_of_quot_hom_id, order_hom.coe_eq, order_hom.coe_eq, ideal_factors_fun_of_quot_hom_comp, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_trans, ring_equiv.symm_trans_self, ring_equiv.to_ring_hom_refl]) (by simp only [← ideal_factors_fun_of_quot_hom_id, order_hom.coe_eq, order_hom.coe_eq, ideal_factors_fun_of_quot_hom_comp, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_trans, ring_equiv.self_trans_symm, ring_equiv.to_ring_hom_refl]) lemma ideal_factors_equiv_of_quot_equiv_symm : (ideal_factors_equiv_of_quot_equiv f).symm = ideal_factors_equiv_of_quot_equiv f.symm := rfl lemma ideal_factors_equiv_of_quot_equiv_is_dvd_iso {L M : ideal R} (hL : L ∣ I) (hM : M ∣ I) : (ideal_factors_equiv_of_quot_equiv f ⟨L, hL⟩ : ideal A) ∣ ideal_factors_equiv_of_quot_equiv f ⟨M, hM⟩ ↔ L ∣ M := begin suffices : ideal_factors_equiv_of_quot_equiv f ⟨M, hM⟩ ≤ ideal_factors_equiv_of_quot_equiv f ⟨L, hL⟩ ↔ (⟨M, hM⟩ : {p : ideal R | p ∣ I}) ≤ ⟨L, hL⟩, { rw [dvd_iff_le, dvd_iff_le, subtype.coe_le_coe, this, subtype.mk_le_mk] }, exact (ideal_factors_equiv_of_quot_equiv f).le_iff_le, end open unique_factorization_monoid variables [decidable_eq (ideal R)] [decidable_eq (ideal A)] lemma ideal_factors_equiv_of_quot_equiv_mem_normalized_factors_of_mem_normalized_factors (hJ : J ≠ ⊥) {L : ideal R} (hL : L ∈ normalized_factors I) : ↑(ideal_factors_equiv_of_quot_equiv f ⟨L, dvd_of_mem_normalized_factors hL⟩) ∈ normalized_factors J := begin by_cases hI : I = ⊥, { exfalso, rw [hI, bot_eq_zero, normalized_factors_zero, ← multiset.empty_eq_zero] at hL, exact hL, }, { apply mem_normalized_factors_factor_dvd_iso_of_mem_normalized_factors hI hJ hL _, rintros ⟨l, hl⟩ ⟨l', hl'⟩, rw [subtype.coe_mk, subtype.coe_mk], apply ideal_factors_equiv_of_quot_equiv_is_dvd_iso f } end /-- The bijection between the sets of normalized factors of I and J induced by a ring isomorphism `f : R/I ≅ A/J`. -/ @[simps apply] def normalized_factors_equiv_of_quot_equiv (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : {L : ideal R | L ∈ normalized_factors I } ≃ {M : ideal A | M ∈ normalized_factors J } := { to_fun := λ j, ⟨ideal_factors_equiv_of_quot_equiv f ⟨↑j, dvd_of_mem_normalized_factors j.prop⟩, ideal_factors_equiv_of_quot_equiv_mem_normalized_factors_of_mem_normalized_factors f hJ j.prop⟩, inv_fun := λ j, ⟨(ideal_factors_equiv_of_quot_equiv f).symm ⟨↑j, dvd_of_mem_normalized_factors j.prop⟩, by { rw ideal_factors_equiv_of_quot_equiv_symm, exact ideal_factors_equiv_of_quot_equiv_mem_normalized_factors_of_mem_normalized_factors f.symm hI j.prop} ⟩, left_inv := λ ⟨j, hj⟩, by simp, right_inv := λ ⟨j, hj⟩, by simp } @[simp] lemma normalized_factors_equiv_of_quot_equiv_symm (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : (normalized_factors_equiv_of_quot_equiv f hI hJ).symm = normalized_factors_equiv_of_quot_equiv f.symm hJ hI := rfl variable [decidable_rel ((∣) : ideal R → ideal R → Prop)] variable [decidable_rel ((∣) : ideal A → ideal A → Prop)] /-- The map `normalized_factors_equiv_of_quot_equiv` preserves multiplicities. -/ lemma normalized_factors_equiv_of_quot_equiv_multiplicity_eq_multiplicity (hI : I ≠ ⊥) (hJ : J ≠ ⊥) (L : ideal R) (hL : L ∈ normalized_factors I) : multiplicity ↑(normalized_factors_equiv_of_quot_equiv f hI hJ ⟨L, hL⟩) J = multiplicity L I := begin rw [normalized_factors_equiv_of_quot_equiv, equiv.coe_fn_mk, subtype.coe_mk], exact multiplicity_factor_dvd_iso_eq_multiplicity_of_mem_normalized_factor hI hJ hL (λ ⟨l, hl⟩ ⟨l', hl'⟩, ideal_factors_equiv_of_quot_equiv_is_dvd_iso f hl hl'), end end section chinese_remainder open ideal unique_factorization_monoid open_locale big_operators variables {R} lemma ring.dimension_le_one.prime_le_prime_iff_eq (h : ring.dimension_le_one R) {P Q : ideal R} [hP : P.is_prime] [hQ : Q.is_prime] (hP0 : P ≠ ⊥) : P ≤ Q ↔ P = Q := ⟨(h P hP0 hP).eq_of_le hQ.ne_top, eq.le⟩ lemma ideal.coprime_of_no_prime_ge {I J : ideal R} (h : ∀ P, I ≤ P → J ≤ P → ¬ is_prime P) : I ⊔ J = ⊤ := begin by_contra hIJ, obtain ⟨P, hP, hIJ⟩ := ideal.exists_le_maximal _ hIJ, exact h P (le_trans le_sup_left hIJ) (le_trans le_sup_right hIJ) hP.is_prime end section dedekind_domain variables {R} [is_domain R] [is_dedekind_domain R] lemma ideal.is_prime.mul_mem_pow (I : ideal R) [hI : I.is_prime] {a b : R} {n : ℕ} (h : a * b ∈ I^n) : a ∈ I ∨ b ∈ I^n := begin cases n, { simp }, by_cases hI0 : I = ⊥, { simpa [pow_succ, hI0] using h }, simp only [← submodule.span_singleton_le_iff_mem, ideal.submodule_span_eq, ← ideal.dvd_iff_le, ← ideal.span_singleton_mul_span_singleton] at h ⊢, by_cases ha : I ∣ span {a}, { exact or.inl ha }, rw mul_comm at h, exact or.inr (prime.pow_dvd_of_dvd_mul_right ((ideal.prime_iff_is_prime hI0).mpr hI) _ ha h), end section open_locale classical lemma ideal.count_normalized_factors_eq {p x : ideal R} [hp : p.is_prime] {n : ℕ} (hle : x ≤ p^n) (hlt : ¬ (x ≤ p^(n+1))) : (normalized_factors x).count p = n := count_normalized_factors_eq' ((ideal.is_prime_iff_bot_or_prime.mp hp).imp_right prime.irreducible) (by { haveI : unique (ideal R)ˣ := ideal.unique_units, apply normalize_eq }) (by convert ideal.dvd_iff_le.mpr hle) (by convert mt ideal.le_of_dvd hlt) /- Warning: even though a pure term-mode proof typechecks (the `by convert` can simply be removed), it's slower to the point of a possible timeout. -/ end lemma ideal.le_mul_of_no_prime_factors {I J K : ideal R} (coprime : ∀ P, J ≤ P → K ≤ P → ¬ is_prime P) (hJ : I ≤ J) (hK : I ≤ K) : I ≤ J * K := begin simp only [← ideal.dvd_iff_le] at coprime hJ hK ⊢, by_cases hJ0 : J = 0, { simpa only [hJ0, zero_mul] using hJ }, obtain ⟨I', rfl⟩ := hK, rw mul_comm, exact mul_dvd_mul_left K (unique_factorization_monoid.dvd_of_dvd_mul_right_of_no_prime_factors hJ0 (λ P hPJ hPK, mt ideal.is_prime_of_prime (coprime P hPJ hPK)) hJ) end lemma ideal.le_of_pow_le_prime {I P : ideal R} [hP : P.is_prime] {n : ℕ} (h : I^n ≤ P) : I ≤ P := begin by_cases hP0 : P = ⊥, { simp only [hP0, le_bot_iff] at ⊢ h, exact pow_eq_zero h }, rw ← ideal.dvd_iff_le at ⊢ h, exact ((ideal.prime_iff_is_prime hP0).mpr hP).dvd_of_dvd_pow h end lemma ideal.pow_le_prime_iff {I P : ideal R} [hP : P.is_prime] {n : ℕ} (hn : n ≠ 0) : I^n ≤ P ↔ I ≤ P := ⟨ideal.le_of_pow_le_prime, λ h, trans (ideal.pow_le_self hn) h⟩ lemma ideal.prod_le_prime {ι : Type*} {s : finset ι} {f : ι → ideal R} {P : ideal R} [hP : P.is_prime] : ∏ i in s, f i ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin by_cases hP0 : P = ⊥, { simp only [hP0, le_bot_iff], rw [← ideal.zero_eq_bot, finset.prod_eq_zero_iff] }, simp only [← ideal.dvd_iff_le], exact ((ideal.prime_iff_is_prime hP0).mpr hP).dvd_finset_prod_iff _ end /-- The intersection of distinct prime powers in a Dedekind domain is the product of these prime powers. -/ lemma is_dedekind_domain.inf_prime_pow_eq_prod {ι : Type*} (s : finset ι) (f : ι → ideal R) (e : ι → ℕ) (prime : ∀ i ∈ s, prime (f i)) (coprime : ∀ i j ∈ s, i ≠ j → f i ≠ f j) : s.inf (λ i, f i ^ e i) = ∏ i in s, f i ^ e i := begin letI := classical.dec_eq ι, revert prime coprime, refine s.induction _ _, { simp }, intros a s ha ih prime coprime, specialize ih (λ i hi, prime i (finset.mem_insert_of_mem hi)) (λ i hi j hj, coprime i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj)), rw [finset.inf_insert, finset.prod_insert ha, ih], refine le_antisymm (ideal.le_mul_of_no_prime_factors _ inf_le_left inf_le_right) ideal.mul_le_inf, intros P hPa hPs hPp, haveI := hPp, obtain ⟨b, hb, hPb⟩ := ideal.prod_le_prime.mp hPs, haveI := ideal.is_prime_of_prime (prime a (finset.mem_insert_self a s)), haveI := ideal.is_prime_of_prime (prime b (finset.mem_insert_of_mem hb)), refine coprime a (finset.mem_insert_self a s) b (finset.mem_insert_of_mem hb) _ (((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq _).mp (ideal.le_of_pow_le_prime hPa)).trans ((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq _).mp (ideal.le_of_pow_le_prime hPb)).symm), { unfreezingI { rintro rfl }, contradiction }, { exact (prime a (finset.mem_insert_self a s)).ne_zero }, { exact (prime b (finset.mem_insert_of_mem hb)).ne_zero }, end /-- **Chinese remainder theorem** for a Dedekind domain: if the ideal `I` factors as `∏ i, P i ^ e i`, then `R ⧸ I` factors as `Π i, R ⧸ (P i ^ e i)`. -/ noncomputable def is_dedekind_domain.quotient_equiv_pi_of_prod_eq {ι : Type*} [fintype ι] (I : ideal R) (P : ι → ideal R) (e : ι → ℕ) (prime : ∀ i, prime (P i)) (coprime : ∀ i j, i ≠ j → P i ≠ P j) (prod_eq : (∏ i, P i ^ e i) = I) : R ⧸ I ≃+* Π i, R ⧸ (P i ^ e i) := (ideal.quot_equiv_of_eq (by { simp only [← prod_eq, finset.inf_eq_infi, finset.mem_univ, cinfi_pos, ← is_dedekind_domain.inf_prime_pow_eq_prod _ _ _ (λ i _, prime i) (λ i _ j _, coprime i j)] })) .trans $ ideal.quotient_inf_ring_equiv_pi_quotient _ (λ i j hij, ideal.coprime_of_no_prime_ge (begin intros P hPi hPj hPp, haveI := hPp, haveI := ideal.is_prime_of_prime (prime i), haveI := ideal.is_prime_of_prime (prime j), exact coprime i j hij (((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq (prime i).ne_zero).mp (ideal.le_of_pow_le_prime hPi)).trans ((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq (prime j).ne_zero).mp (ideal.le_of_pow_le_prime hPj)).symm) end)) open_locale classical /-- **Chinese remainder theorem** for a Dedekind domain: `R ⧸ I` factors as `Π i, R ⧸ (P i ^ e i)`, where `P i` ranges over the prime factors of `I` and `e i` over the multiplicities. -/ noncomputable def is_dedekind_domain.quotient_equiv_pi_factors {I : ideal R} (hI : I ≠ ⊥) : R ⧸ I ≃+* Π (P : (factors I).to_finset), R ⧸ ((P : ideal R) ^ (factors I).count P) := is_dedekind_domain.quotient_equiv_pi_of_prod_eq _ _ _ (λ (P : (factors I).to_finset), prime_of_factor _ (multiset.mem_to_finset.mp P.prop)) (λ i j hij, subtype.coe_injective.ne hij) (calc ∏ (P : (factors I).to_finset), (P : ideal R) ^ (factors I).count (P : ideal R) = ∏ P in (factors I).to_finset, P ^ (factors I).count P : (factors I).to_finset.prod_coe_sort (λ P, P ^ (factors I).count P) ... = ((factors I).map (λ P, P)).prod : (finset.prod_multiset_map_count (factors I) id).symm ... = (factors I).prod : by rw multiset.map_id' ... = I : (@associated_iff_eq (ideal R) _ ideal.unique_units _ _).mp (factors_prod hI)) @[simp] lemma is_dedekind_domain.quotient_equiv_pi_factors_mk {I : ideal R} (hI : I ≠ ⊥) (x : R) : is_dedekind_domain.quotient_equiv_pi_factors hI (ideal.quotient.mk I x) = λ P, ideal.quotient.mk _ x := rfl end dedekind_domain end chinese_remainder section PID open multiplicity unique_factorization_monoid ideal variables {R} [is_domain R] [is_principal_ideal_ring R] lemma span_singleton_dvd_span_singleton_iff_dvd {a b : R} : (ideal.span {a}) ∣ (ideal.span ({b} : set R)) ↔ a ∣ b := ⟨λ h, mem_span_singleton.mp (dvd_iff_le.mp h (mem_span_singleton.mpr (dvd_refl b))), λ h, dvd_iff_le.mpr (λ d hd, mem_span_singleton.mpr (dvd_trans h (mem_span_singleton.mp hd)))⟩ lemma singleton_span_mem_normalized_factors_of_mem_normalized_factors [normalization_monoid R] [decidable_eq R] [decidable_eq (ideal R)] {a b : R} (ha : a ∈ normalized_factors b) : ideal.span ({a} : set R) ∈ normalized_factors (ideal.span ({b} : set R)) := begin by_cases hb : b = 0, { rw [ideal.span_singleton_eq_bot.mpr hb, bot_eq_zero, normalized_factors_zero], rw [hb, normalized_factors_zero] at ha, simpa only [multiset.not_mem_zero] }, { suffices : prime (ideal.span ({a} : set R)), { obtain ⟨c, hc, hc'⟩ := exists_mem_normalized_factors_of_dvd _ this.irreducible (dvd_iff_le.mpr (span_singleton_le_span_singleton.mpr (dvd_of_mem_normalized_factors ha))), rwa associated_iff_eq.mp hc', { by_contra, exact hb (span_singleton_eq_bot.mp h) } }, rw prime_iff_is_prime, exact (span_singleton_prime (prime_of_normalized_factor a ha).ne_zero).mpr (prime_of_normalized_factor a ha), by_contra, exact (prime_of_normalized_factor a ha).ne_zero (span_singleton_eq_bot.mp h) }, end lemma multiplicity_eq_multiplicity_span [decidable_rel ((∣) : R → R → Prop)] [decidable_rel ((∣) : ideal R → ideal R → Prop)] {a b : R} : multiplicity (ideal.span {a}) (ideal.span ({b} : set R)) = multiplicity a b := begin by_cases h : finite a b, { rw ← part_enat.coe_get (finite_iff_dom.mp h), refine (multiplicity.unique (show (ideal.span {a})^(((multiplicity a b).get h)) ∣ (ideal.span {b}), from _) _).symm ; rw [ideal.span_singleton_pow, span_singleton_dvd_span_singleton_iff_dvd], exact pow_multiplicity_dvd h , { exact multiplicity.is_greatest ((part_enat.lt_coe_iff _ _).mpr (exists.intro (finite_iff_dom.mp h) (nat.lt_succ_self _))) } }, { suffices : ¬ (finite (ideal.span ({a} : set R)) (ideal.span ({b} : set R))), { rw [finite_iff_dom, part_enat.not_dom_iff_eq_top] at h this, rw [h, this] }, refine not_finite_iff_forall.mpr (λ n, by {rw [ideal.span_singleton_pow, span_singleton_dvd_span_singleton_iff_dvd], exact not_finite_iff_forall.mp h n }) } end variables [decidable_eq R] [decidable_eq (ideal R)] [normalization_monoid R] /-- The bijection between the (normalized) prime factors of `r` and the (normalized) prime factors of `span {r}` -/ @[simps] noncomputable def normalized_factors_equiv_span_normalized_factors {r : R} (hr : r ≠ 0) : {d : R | d ∈ normalized_factors r} ≃ {I : ideal R | I ∈ normalized_factors (ideal.span ({r} : set R))} := equiv.of_bijective (λ d, ⟨ideal.span {↑d}, singleton_span_mem_normalized_factors_of_mem_normalized_factors d.prop⟩) begin split, { rintros ⟨a, ha⟩ ⟨b, hb⟩ h, rw [subtype.mk_eq_mk, ideal.span_singleton_eq_span_singleton, subtype.coe_mk, subtype.coe_mk] at h, exact subtype.mk_eq_mk.mpr (mem_normalized_factors_eq_of_associated ha hb h) }, { rintros ⟨i, hi⟩, letI : i.is_principal := infer_instance, letI : i.is_prime := is_prime_of_prime (prime_of_normalized_factor i hi), obtain ⟨a, ha, ha'⟩ := exists_mem_normalized_factors_of_dvd hr (submodule.is_principal.prime_generator_of_is_prime i (prime_of_normalized_factor i hi).ne_zero).irreducible _, { use ⟨a, ha⟩, simp only [subtype.coe_mk, subtype.mk_eq_mk, ← span_singleton_eq_span_singleton.mpr ha', ideal.span_singleton_generator] }, {exact (submodule.is_principal.mem_iff_generator_dvd i).mp (((show ideal.span {r} ≤ i, from dvd_iff_le.mp (dvd_of_mem_normalized_factors hi))) (mem_span_singleton.mpr (dvd_refl r))) } } end variables [decidable_rel ((∣) : R → R → Prop)] [decidable_rel ((∣) : ideal R → ideal R → Prop)] /-- The bijection `normalized_factors_equiv_span_normalized_factors` between the set of prime factors of `r` and the set of prime factors of the ideal `⟨r⟩` preserves multiplicities. -/ lemma multiplicity_normalized_factors_equiv_span_normalized_factors_eq_multiplicity {r d: R} (hr : r ≠ 0) (hd : d ∈ normalized_factors r) : multiplicity d r = multiplicity (normalized_factors_equiv_span_normalized_factors hr ⟨d, hd⟩ : ideal R) (ideal.span {r}) := by simp only [normalized_factors_equiv_span_normalized_factors, multiplicity_eq_multiplicity_span, subtype.coe_mk, equiv.of_bijective_apply] /-- The bijection `normalized_factors_equiv_span_normalized_factors.symm` between the set of prime factors of the ideal `⟨r⟩` and the set of prime factors of `r` preserves multiplicities. -/ lemma multiplicity_normalized_factors_equiv_span_normalized_factors_symm_eq_multiplicity {r : R} (hr : r ≠ 0) (I : {I : ideal R | I ∈ normalized_factors (ideal.span ({r} : set R))}) : multiplicity ((normalized_factors_equiv_span_normalized_factors hr).symm I : R) r = multiplicity (I : ideal R) (ideal.span {r}) := begin obtain ⟨x, hx⟩ := (normalized_factors_equiv_span_normalized_factors hr).surjective I, obtain ⟨a, ha⟩ := x, rw [hx.symm, equiv.symm_apply_apply, subtype.coe_mk, multiplicity_normalized_factors_equiv_span_normalized_factors_eq_multiplicity hr ha, hx], end end PID
b71b22eeed197db05013044c73a3d2be8880b2a6
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Scopes.lean
ca2cda91a4cd76f5da16b95d876e8885af7cd8c3
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
3,715
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.Environment namespace Lean /- Scope management TODO: delete after we delete parser implemented in C++. We have decided to store scope information at ElabState -/ structure ScopeManagerState := (allNamespaces : NameSet := {}) /- Stack of namespaces for each each open namespace and section -/ (namespaces : List Name := []) /- Stack of namespace/section headers -/ (headers : List Name := []) (isNamespace : List Bool := []) namespace ScopeManagerState instance : Inhabited ScopeManagerState := ⟨{}⟩ def saveNamespace (s : ScopeManagerState) (n : Name) : ScopeManagerState := { allNamespaces := s.allNamespaces.insert n, .. s } end ScopeManagerState def regScopeManagerExtension : IO (SimplePersistentEnvExtension Name ScopeManagerState) := registerSimplePersistentEnvExtension { name := `scopes, addImportedFn := fun as => mkStateFromImportedEntries ScopeManagerState.saveNamespace {} as, addEntryFn := fun s n => { allNamespaces := s.allNamespaces.insert n, .. s }, } @[init regScopeManagerExtension] constant scopeManagerExt : SimplePersistentEnvExtension Name ScopeManagerState := arbitrary _ namespace Environment @[export lean_get_namespaces] def getNamespaces (env : Environment) : List Name := (scopeManagerExt.getState env).namespaces def getNamespaceSet (env : Environment) : NameSet := (scopeManagerExt.getState env).allNamespaces @[export lean_is_namespace] def isNamespace (env : Environment) (n : Name) : Bool := env.getNamespaceSet.contains n @[export lean_in_section] def inSection (env : Environment) : Bool := match (scopeManagerExt.getState env).isNamespace with | (b::_) => !b | _ => false @[export lean_has_open_scopes] def hasOpenScopes (env : Environment) : Bool := !env.getNamespaces.isEmpty @[export lean_get_namespace] def getNamespace (env : Environment) : Name := match env.getNamespaces with | (n::_) => n | _ => Name.anonymous @[export lean_get_scope_header] def getScopeHeader (env : Environment) : Name := match (scopeManagerExt.getState env).headers with | (n::_) => n | _ => Name.anonymous @[export lean_to_valid_namespace] def toValidNamespace (env : Environment) (n : Name) : Option Name := let s := scopeManagerExt.getState env; if s.allNamespaces.contains n then some n else s.namespaces.foldl (fun r ns => match r with | some _ => r | none => let c := ns ++ n; if s.allNamespaces.contains c then some c else none) none def registerNamespaceAux (env : Environment) (n : Name) : Environment := if env.getNamespaceSet.contains n then env else scopeManagerExt.addEntry env n @[export lean_register_namespace] def registerNamespace : Environment → Name → Environment | env, n@(Name.str p _ _) => registerNamespace (registerNamespaceAux env n) p | env, _ => env def pushScopeCore (env : Environment) (header : Name) (isNamespace : Bool) : Environment := let ns := env.getNamespace; let newNs := if isNamespace then ns ++ header else ns; let env := env.registerNamespaceAux newNs; let env := scopeManagerExt.modifyState env $ fun s => { headers := header :: s.headers, namespaces := newNs :: s.namespaces, isNamespace := isNamespace :: s.isNamespace, .. s }; env def popScopeCore (env : Environment) : Environment := if env.getNamespaces.isEmpty then env else scopeManagerExt.modifyState env $ fun s => { headers := s.headers.tail!, namespaces := s.namespaces.tail!, isNamespace := s.isNamespace.tail!, .. s } end Environment end Lean
a0778929bbc3bfad771c9a380ab3f4622ea4f551
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/sheaves/skyscraper.lean
c02f854b23030058b7e6a50d4914f14ff07c3e74
[ "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
17,736
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Junyan Xu -/ import topology.sheaves.punit import topology.sheaves.stalks import topology.sheaves.functors /-! # Skyscraper (pre)sheaves A skyscraper (pre)sheaf `𝓕 : (pre)sheaf C X` is the (pre)sheaf with value `A` at point `p₀` that is supported only at open sets contain `p₀`, i.e. `𝓕(U) = A` if `p₀ ∈ U` and `𝓕(U) = *` if `p₀ ∉ U` where `*` is a terminal object of `C`. In terms of stalks, `𝓕` is supported at all specializations of `p₀`, i.e. if `p₀ ⤳ x` then `𝓕ₓ ≅ A` and if `¬ p₀ ⤳ x` then `𝓕ₓ ≅ *`. ## Main definitions * `skyscraper_presheaf`: `skyscraper_presheaf p₀ A` is the skyscraper presheaf at point `p₀` with value `A`. * `skyscraper_sheaf`: the skyscraper presheaf satisfies the sheaf condition. ## Main statements * `skyscraper_presheaf_stalk_of_specializes`: if `y ∈ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. * `skyscraper_presheaf_stalk_of_not_specializes`: if `y ∉ closure {p₀}` then the stalk of `skyscraper_presheaf p₀ A` at `y` is `*` the terminal object. TODO: generalize universe level when calculating stalks, after generalizing universe level of stalk. -/ noncomputable theory open topological_space Top category_theory category_theory.limits opposite universes u v w variables {X : Top.{u}} (p₀ : X) [Π (U : opens X), decidable (p₀ ∈ U)] section variables {C : Type v} [category.{w} C] [has_terminal C] (A : C) /-- A skyscraper presheaf is a presheaf supported at a single point: if `p₀ ∈ X` is a specified point, then the skyscraper presheaf `𝓕` with value `A` is defined by `U ↦ A` if `p₀ ∈ U` and `U ↦ *` if `p₀ ∉ A` where `*` is some terminal object. -/ @[simps] def skyscraper_presheaf : presheaf C X := { obj := λ U, if p₀ ∈ unop U then A else terminal C, map := λ U V i, if h : p₀ ∈ unop V then eq_to_hom $ by erw [if_pos h, if_pos (le_of_hom i.unop h)] else ((if_neg h).symm.rec terminal_is_terminal).from _, map_id' := λ U, (em (p₀ ∈ U.unop)).elim (λ h, dif_pos h) (λ h, ((if_neg h).symm.rec terminal_is_terminal).hom_ext _ _), map_comp' := λ U V W iVU iWV, begin by_cases hW : p₀ ∈ unop W, { have hV : p₀ ∈ unop V := le_of_hom iWV.unop hW, simp only [dif_pos hW, dif_pos hV, eq_to_hom_trans] }, { rw [dif_neg hW], apply ((if_neg hW).symm.rec terminal_is_terminal).hom_ext } end } lemma skyscraper_presheaf_eq_pushforward [hd : Π (U : opens (Top.of punit.{u+1})), decidable (punit.star ∈ U)] : skyscraper_presheaf p₀ A = continuous_map.const (Top.of punit) p₀ _* skyscraper_presheaf punit.star A := by convert_to @skyscraper_presheaf X p₀ (λ U, hd $ (opens.map $ continuous_map.const _ p₀).obj U) C _ _ A = _; congr <|> refl /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraper_presheaf_functor.map' {a b : C} (f : a ⟶ b) : skyscraper_presheaf p₀ a ⟶ skyscraper_presheaf p₀ b := { app := λ U, if h : p₀ ∈ U.unop then eq_to_hom (if_pos h) ≫ f ≫ eq_to_hom (if_pos h).symm else ((if_neg h).symm.rec terminal_is_terminal).from _, naturality' := λ U V i, begin simp only [skyscraper_presheaf_map], by_cases hV : p₀ ∈ V.unop, { have hU : p₀ ∈ U.unop := le_of_hom i.unop hV, split_ifs, simpa only [eq_to_hom_trans_assoc, category.assoc, eq_to_hom_trans], }, { apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext, }, end } lemma skyscraper_presheaf_functor.map'_id {a : C} : skyscraper_presheaf_functor.map' p₀ (𝟙 a) = 𝟙 _ := begin ext1, ext1, simp only [skyscraper_presheaf_functor.map'_app, nat_trans.id_app], split_ifs, { simp only [category.id_comp, category.comp_id, eq_to_hom_trans, eq_to_hom_refl], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end lemma skyscraper_presheaf_functor.map'_comp {a b c : C} (f : a ⟶ b) (g : b ⟶ c) : skyscraper_presheaf_functor.map' p₀ (f ≫ g) = skyscraper_presheaf_functor.map' p₀ f ≫ skyscraper_presheaf_functor.map' p₀ g := begin ext1, ext1, simp only [skyscraper_presheaf_functor.map'_app, nat_trans.comp_app], split_ifs, { simp only [category.assoc, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end /-- Taking skyscraper presheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ @[simps] def skyscraper_presheaf_functor : C ⥤ presheaf C X := { obj := skyscraper_presheaf p₀, map := λ _ _, skyscraper_presheaf_functor.map' p₀, map_id' := λ _, skyscraper_presheaf_functor.map'_id p₀, map_comp' := λ _ _ _, skyscraper_presheaf_functor.map'_comp p₀ } end section -- In this section, we calculate the stalks for skyscraper presheaves. -- We need to restrict universe level. variables {C : Type v} [category.{u} C] (A : C) [has_terminal C] /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` -/ @[simps] def skyscraper_presheaf_cocone_of_specializes {y : X} (h : p₀ ⤳ y) : cocone ((open_nhds.inclusion y).op ⋙ skyscraper_presheaf p₀ A) := { X := A, ι := { app := λ U, eq_to_hom $ if_pos $ h.mem_open U.unop.1.2 U.unop.2, naturality' := λ U V inc, begin change dite _ _ _ ≫ _ = _, rw dif_pos, { erw [category.comp_id, eq_to_hom_trans], refl }, { exact h.mem_open V.unop.1.2 V.unop.2 }, end } } /-- The cocone at `A` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∈ closure {p₀}` is a colimit -/ noncomputable def skyscraper_presheaf_cocone_is_colimit_of_specializes {y : X} (h : p₀ ⤳ y) : is_colimit (skyscraper_presheaf_cocone_of_specializes p₀ A h) := { desc := λ c, eq_to_hom (if_pos trivial).symm ≫ c.ι.app (op ⊤), fac' := λ c U, begin rw ← c.w (hom_of_le $ (le_top : unop U ≤ _)).op, change _ ≫ _ ≫ dite _ _ _ ≫ _ = _, rw dif_pos, { simpa only [skyscraper_presheaf_cocone_of_specializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] }, { exact h.mem_open U.unop.1.2 U.unop.2 }, end, uniq' := λ c f h, by rw [← h, skyscraper_presheaf_cocone_of_specializes_ι_app, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] } /-- If `y ∈ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is `A`. -/ noncomputable def skyscraper_presheaf_stalk_of_specializes [has_colimits C] {y : X} (h : p₀ ⤳ y) : (skyscraper_presheaf p₀ A).stalk y ≅ A := colimit.iso_colimit_cocone ⟨_, skyscraper_presheaf_cocone_is_colimit_of_specializes p₀ A h⟩ /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` -/ @[simps] def skyscraper_presheaf_cocone (y : X) : cocone ((open_nhds.inclusion y).op ⋙ skyscraper_presheaf p₀ A) := { X := terminal C, ι := { app := λ U, terminal.from _, naturality' := λ U V inc, terminal_is_terminal.hom_ext _ _ } } /-- The cocone at `*` for the stalk functor of `skyscraper_presheaf p₀ A` when `y ∉ closure {p₀}` is a colimit -/ noncomputable def skyscraper_presheaf_cocone_is_colimit_of_not_specializes {y : X} (h : ¬p₀ ⤳ y) : is_colimit (skyscraper_presheaf_cocone p₀ A y) := let h1 : ∃ (U : open_nhds y), p₀ ∉ U.1 := let ⟨U, ho, h₀, hy⟩ := not_specializes_iff_exists_open.mp h in ⟨⟨⟨U, ho⟩, h₀⟩, hy⟩ in { desc := λ c, eq_to_hom (if_neg h1.some_spec).symm ≫ c.ι.app (op h1.some), fac' := λ c U, begin change _ = c.ι.app (op U.unop), simp only [← c.w (hom_of_le $ @inf_le_left _ _ h1.some U.unop).op, ← c.w (hom_of_le $ @inf_le_right _ _ h1.some U.unop).op, ← category.assoc], congr' 1, refine ((if_neg _).symm.rec terminal_is_terminal).hom_ext _ _, exact λ h, h1.some_spec h.1, end, uniq' := λ c f H, begin rw [← category.id_comp f, ← H, ← category.assoc], congr' 1, apply terminal_is_terminal.hom_ext, end } /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is isomorphic to a terminal object. -/ noncomputable def skyscraper_presheaf_stalk_of_not_specializes [has_colimits C] {y : X} (h : ¬p₀ ⤳ y) : (skyscraper_presheaf p₀ A).stalk y ≅ terminal C := colimit.iso_colimit_cocone ⟨_, skyscraper_presheaf_cocone_is_colimit_of_not_specializes _ A h⟩ /-- If `y ∉ closure {p₀}`, then the stalk of `skyscraper_presheaf p₀ A` at `y` is a terminal object -/ def skyscraper_presheaf_stalk_of_not_specializes_is_terminal [has_colimits C] {y : X} (h : ¬p₀ ⤳ y) : is_terminal ((skyscraper_presheaf p₀ A).stalk y) := is_terminal.of_iso terminal_is_terminal $ (skyscraper_presheaf_stalk_of_not_specializes _ _ h).symm lemma skyscraper_presheaf_is_sheaf : (skyscraper_presheaf p₀ A).is_sheaf := by classical; exact (presheaf.is_sheaf_iso_iff (eq_to_iso $ skyscraper_presheaf_eq_pushforward p₀ A)).mpr (sheaf.pushforward_sheaf_of_sheaf _ (presheaf.is_sheaf_on_punit_of_is_terminal _ (by { dsimp, rw if_neg, exact terminal_is_terminal, exact set.not_mem_empty punit.star }))) /-- The skyscraper presheaf supported at `p₀` with value `A` is the sheaf that assigns `A` to all opens `U` that contain `p₀` and assigns `*` otherwise. -/ def skyscraper_sheaf : sheaf C X := ⟨skyscraper_presheaf p₀ A, skyscraper_presheaf_is_sheaf _ _⟩ /-- Taking skyscraper sheaf at a point is functorial: `c ↦ skyscraper p₀ c` defines a functor by sending every `f : a ⟶ b` to the natural transformation `α` defined as: `α(U) = f : a ⟶ b` if `p₀ ∈ U` and the unique morphism to a terminal object in `C` if `p₀ ∉ U`. -/ def skyscraper_sheaf_functor : C ⥤ sheaf C X := { obj := λ c, skyscraper_sheaf p₀ c, map := λ a b f, Sheaf.hom.mk $ (skyscraper_presheaf_functor p₀).map f, map_id' := λ c, Sheaf.hom.ext _ _ $ (skyscraper_presheaf_functor p₀).map_id _, map_comp' := λ _ _ _ f g, Sheaf.hom.ext _ _ $ (skyscraper_presheaf_functor p₀).map_comp _ _ } namespace stalk_skyscraper_presheaf_adjunction_auxs variables [has_colimits C] /-- If `f : 𝓕.stalk p₀ ⟶ c`, then a natural transformation `𝓕 ⟶ skyscraper_presheaf p₀ c` can be defined by: `𝓕.germ p₀ ≫ f : 𝓕(U) ⟶ c` if `p₀ ∈ U` and the unique morphism to a terminal object if `p₀ ∉ U`. -/ @[simps] def to_skyscraper_presheaf {𝓕 : presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : 𝓕 ⟶ skyscraper_presheaf p₀ c := { app := λ U, if h : p₀ ∈ U.unop then 𝓕.germ ⟨p₀, h⟩ ≫ f ≫ eq_to_hom (if_pos h).symm else ((if_neg h).symm.rec terminal_is_terminal).from _, naturality' := λ U V inc, begin dsimp, by_cases hV : p₀ ∈ V.unop, { have hU : p₀ ∈ U.unop := le_of_hom inc.unop hV, split_ifs, erw [←category.assoc, 𝓕.germ_res inc.unop, category.assoc, category.assoc, eq_to_hom_trans], refl, }, { split_ifs, apply ((if_neg hV).symm.rec terminal_is_terminal).hom_ext }, end } /-- If `f : 𝓕 ⟶ skyscraper_presheaf p₀ c` is a natural transformation, then there is a morphism `𝓕.stalk p₀ ⟶ c` defined as the morphism from colimit to cocone at `c`. -/ def from_stalk {𝓕 : presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraper_presheaf p₀ c) : 𝓕.stalk p₀ ⟶ c := let χ : cocone ((open_nhds.inclusion p₀).op ⋙ 𝓕) := cocone.mk c $ { app := λ U, f.app (op U.unop.1) ≫ eq_to_hom (if_pos U.unop.2), naturality' := λ U V inc, begin dsimp, erw [category.comp_id, ←category.assoc, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, f.naturality, skyscraper_presheaf_map], have hV : p₀ ∈ (open_nhds.inclusion p₀).obj V.unop := V.unop.2, split_ifs, simpa only [comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], end } in colimit.desc _ χ lemma to_skyscraper_from_stalk {𝓕 : presheaf C X} {c : C} (f : 𝓕 ⟶ skyscraper_presheaf p₀ c) : to_skyscraper_presheaf p₀ (from_stalk _ f) = f := nat_trans.ext _ _ $ funext $ λ U, (em (p₀ ∈ U.unop)).elim (λ h, by { dsimp, split_ifs, erw [←category.assoc, colimit.ι_desc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], refl }) $ λ h, by { dsimp, split_ifs, apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext } lemma from_stalk_to_skyscraper {𝓕 : presheaf C X} {c : C} (f : 𝓕.stalk p₀ ⟶ c) : from_stalk p₀ (to_skyscraper_presheaf _ f) = f := colimit.hom_ext $ λ U, by { erw [colimit.ι_desc], dsimp, rw dif_pos U.unop.2, rw [category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, presheaf.germ], congr' 3, apply_fun opposite.unop using unop_injective, rw [unop_op], ext, refl } /-- The unit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def unit : 𝟭 (presheaf C X) ⟶ presheaf.stalk_functor C p₀ ⋙ skyscraper_presheaf_functor p₀ := { app := λ 𝓕, to_skyscraper_presheaf _ $ 𝟙 _, naturality' := λ 𝓕 𝓖 f, begin ext U, dsimp, split_ifs, { simp only [category.id_comp, ←category.assoc], rw [comp_eq_to_hom_iff], simp only [category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id], erw [colimit.ι_map], refl, }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext, }, end } /-- The counit in `presheaf.stalk ⊣ skyscraper_presheaf_functor` -/ @[simps] protected def counit : (skyscraper_presheaf_functor p₀ ⋙ (presheaf.stalk_functor C p₀ : presheaf C X ⥤ C)) ⟶ 𝟭 C := { app := λ c, (skyscraper_presheaf_stalk_of_specializes p₀ c specializes_rfl).hom, naturality' := λ x y f, colimit.hom_ext $ λ U, begin erw [←category.assoc, colimit.ι_map, colimit.iso_colimit_cocone_ι_hom_assoc, skyscraper_presheaf_cocone_of_specializes_ι_app, category.assoc, colimit.ι_desc, whiskering_left_obj_map, whisker_left_app, skyscraper_presheaf_functor.map'_app, dif_pos U.unop.2, skyscraper_presheaf_cocone_of_specializes_ι_app, comp_eq_to_hom_iff, category.assoc, eq_to_hom_comp_iff, ←category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.id_comp, comp_eq_to_hom_iff, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, category_theory.functor.id_map], end } end stalk_skyscraper_presheaf_adjunction_auxs section open stalk_skyscraper_presheaf_adjunction_auxs /-- `skyscraper_presheaf_functor` is the right adjoint of `presheaf.stalk_functor` -/ def skyscraper_presheaf_stalk_adjunction [has_colimits C] : (presheaf.stalk_functor C p₀ : presheaf C X ⥤ C) ⊣ skyscraper_presheaf_functor p₀ := { hom_equiv := λ c 𝓕, { to_fun := to_skyscraper_presheaf _, inv_fun := from_stalk _, left_inv := from_stalk_to_skyscraper _, right_inv := to_skyscraper_from_stalk _ }, unit := stalk_skyscraper_presheaf_adjunction_auxs.unit _, counit := stalk_skyscraper_presheaf_adjunction_auxs.counit _, hom_equiv_unit' := λ 𝓕 c α, begin ext U, simp only [equiv.coe_fn_mk, to_skyscraper_presheaf_app, nat_trans.comp_app, skyscraper_presheaf_functor.map'_app, skyscraper_presheaf_functor_map, unit_app], split_ifs, { erw [category.id_comp, ←category.assoc, comp_eq_to_hom_iff, category.assoc, category.assoc, category.assoc, category.assoc, eq_to_hom_trans, eq_to_hom_refl, category.comp_id, ←category.assoc _ _ α, eq_to_hom_trans, eq_to_hom_refl, category.id_comp], }, { apply ((if_neg h).symm.rec terminal_is_terminal).hom_ext } end, hom_equiv_counit' := λ 𝓕 c α, begin ext U, simp only [equiv.coe_fn_symm_mk, counit_app], erw [colimit.ι_desc, ←category.assoc, colimit.ι_map, whisker_left_app, category.assoc, colimit.ι_desc], refl, end } instance [has_colimits C] : is_right_adjoint (skyscraper_presheaf_functor p₀ : C ⥤ presheaf C X) := ⟨_, skyscraper_presheaf_stalk_adjunction _⟩ instance [has_colimits C] : is_left_adjoint (presheaf.stalk_functor C p₀) := ⟨_, skyscraper_presheaf_stalk_adjunction _⟩ /-- Taking stalks of a sheaf is the left adjoint functor to `skyscraper_sheaf_functor` -/ def stalk_skyscraper_sheaf_adjunction [has_colimits C] : sheaf.forget C X ⋙ presheaf.stalk_functor _ p₀ ⊣ skyscraper_sheaf_functor p₀ := { hom_equiv := λ 𝓕 c, ⟨λ f, ⟨to_skyscraper_presheaf p₀ f⟩, λ g, from_stalk p₀ g.1, from_stalk_to_skyscraper p₀, λ g, by { ext1, apply to_skyscraper_from_stalk }⟩, unit := { app := λ 𝓕, ⟨(stalk_skyscraper_presheaf_adjunction_auxs.unit p₀).app 𝓕.1⟩, naturality' := λ 𝓐 𝓑 ⟨f⟩, by { ext1, apply (stalk_skyscraper_presheaf_adjunction_auxs.unit p₀).naturality } }, counit := stalk_skyscraper_presheaf_adjunction_auxs.counit p₀, hom_equiv_unit' := λ 𝓐 c f, by { ext1, exact (skyscraper_presheaf_stalk_adjunction p₀).hom_equiv_unit }, hom_equiv_counit' := λ 𝓐 c f, (skyscraper_presheaf_stalk_adjunction p₀).hom_equiv_counit } instance [has_colimits C] : is_right_adjoint (skyscraper_sheaf_functor p₀ : C ⥤ sheaf C X) := ⟨_, stalk_skyscraper_sheaf_adjunction _⟩ end end
d6af4bb1ae59b981f35e94f5b2bf97aa5c9603c9
dc253be9829b840f15d96d986e0c13520b085033
/algebra/seq_colim.hlean
88d98b813da6f928a40994787178df85fbed730c
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
3,939
hlean
--Authors: Robert Rose, Liz Vidaurre import .direct_sum ..move_to_lib open eq algebra is_trunc set_quotient relation sigma prod sum list trunc function equiv sigma.ops nat namespace group section parameters (A : ℕ → AbGroup) (f : Πi , A i →g A (i + 1)) variables {A' : AbGroup} definition seq_colim_carrier : AbGroup := dirsum A inductive seq_colim_rel : seq_colim_carrier → Type := | rmk : Πi a, seq_colim_rel ((dirsum_incl A i a) * (dirsum_incl A (i + 1) (f i a))⁻¹) definition seq_colim : AbGroup := quotient_ab_group_gen seq_colim_carrier (λa, ∥seq_colim_rel a∥) parameters {A f} definition seq_colim_incl [constructor] (i : ℕ) : A i →g seq_colim := gqg_map _ _ ∘g dirsum_incl A i definition seq_colim_quotient (h : Πi, A i →g A') (k : Πi a, h i a = h (succ i) (f i a)) (v : seq_colim_carrier) (r : ∥seq_colim_rel v∥) : dirsum_elim h v = 1 := begin induction r with r, induction r, refine !to_respect_mul ⬝ _, refine ap (λγ, group_fun (dirsum_elim h) (group_fun (dirsum_incl A i) a) * group_fun (dirsum_elim h) γ) (!to_respect_inv)⁻¹ ⬝ _, refine ap (λγ, γ * group_fun (dirsum_elim h) (group_fun (dirsum_incl A (succ i)) (f i a)⁻¹)) !dirsum_elim_compute ⬝ _, refine ap (λγ, (h i a) * γ) !dirsum_elim_compute ⬝ _, refine ap (λγ, γ * group_fun (h (succ i)) (f i a)⁻¹) !k ⬝ _, refine ap (λγ, group_fun (h (succ i)) (f i a) * γ) (!to_respect_inv) ⬝ _, exact !mul.right_inv end definition seq_colim_elim [constructor] (h : Πi, A i →g A') (k : Πi a, h i a = h (succ i) (f i a)) : seq_colim →g A' := gqg_elim _ (dirsum_elim h) (seq_colim_quotient h k) definition seq_colim_compute (h : Πi, A i →g A') (k : Πi a, h i a = h (succ i) (f i a)) (i : ℕ) (a : A i) : (seq_colim_elim h k) (seq_colim_incl i a) = h i a := begin refine gqg_elim_compute (λa, ∥seq_colim_rel a∥) (dirsum_elim h) (seq_colim_quotient h k) (dirsum_incl A i a) ⬝ _, exact !dirsum_elim_compute end definition seq_colim_glue {i : @trunctype.mk 0 ℕ _} {a : A i} : seq_colim_incl i a = seq_colim_incl (succ i) (f i a) := begin refine gqg_eq_of_rel _ _, exact tr (seq_colim_rel.rmk _ _) end section local abbreviation h (m : seq_colim →g A') : Πi, A i →g A' := λi, m ∘g (seq_colim_incl i) local abbreviation k (m : seq_colim →g A') : Πi a, h m i a = h m (succ i) (f i a) := λ i a, ap m (@seq_colim_glue i a) definition seq_colim_unique (m : seq_colim →g A') : Πv, seq_colim_elim (h m) (k m) v = m v := begin intro v, refine (gqg_elim_unique _ (dirsum_elim (h m)) _ m _ _)⁻¹ ⬝ _, apply dirsum_elim_unique, rotate 1, reflexivity, intro i a, reflexivity end end end definition seq_colim_functor [constructor] {A A' : ℕ → AbGroup} {f : Πi , A i →g A (i + 1)} {f' : Πi , A' i →g A' (i + 1)} (h : Πi, A i →g A' i) (p : Πi, hsquare (f i) (f' i) (h i) (h (i+1))) : seq_colim A f →g seq_colim A' f' := seq_colim_elim (λi, seq_colim_incl i ∘g h i) begin intro i a, refine _ ⬝ ap (seq_colim_incl (succ i)) (p i a)⁻¹, apply seq_colim_glue end -- definition seq_colim_functor_compose [constructor] {A A' A'' : ℕ → AbGroup} -- {f : Πi , A i →g A (i + 1)} {f' : Πi , A' i →g A' (i + 1)} {f'' : Πi , A'' i →g A'' (i + 1)} -- (h : Πi, A i →g A' i) (p : Πi (a : A i), h (i+1) (f i a) = f' i (h i a)) -- (h : Πi, A i →g A' i) (p : Πi (a : A i), h (i+1) (f i a) = f' i (h i a)) : -- seq_colim A f →g seq_colim A' f' := -- sorry end group
ab7d33370a398923d6eb805839ede4d14f8337a8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/padics/ring_homs.lean
b07dfdc5ef4dff7c0f3447f6d9edc239938c39c3
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
24,377
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.zmod.basic import number_theory.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical open nat local_ring padic namespace padic_int variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.1.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.1.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.nat_cast_mod p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring_nf ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [mul_tsub, mul_one, ← pow_succ'], apply add_tsub_cancel_of_le (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_nat_of_le_succ, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, tsub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, obtain hc0 | hc0 := c.valuation.nat_abs.eq_zero_or_pos, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, zpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw zero_pow hc0, simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', exact (dvd_pow_self _ hc0.ne').mul_left _ } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat i j h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ i > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩, simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := ⟨pow_pos hp_prime.1.pos _⟩, have : fact (p ^ j > 0) := ⟨pow_pos hp_prime.1.pos _⟩, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.zpow_pos_of_pos hp_prime.1.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := ⟨pow_pos hp_prime.1.pos n⟩, rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← map_nat_cast $ to_zmod_pow n, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
bc0adb6841414b8fe3e673f97a01be4c7b8f4760
cfdac20f65ed6246e5fc7ce58637507f8945f419
/library/data/set/basic.lean
c0c4f75f3f7f19cd271d5f1b859621da79f68b6c
[ "Apache-2.0" ]
permissive
anandadalton/lean
8623b101ed898c8f4a7a161abd6f8e08d7db57c2
37b1e9163d069d12fb4a46b8d3ccfc3081aca645
refs/heads/master
1,647,253,997,156
1,461,883,971,000
1,461,883,971,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,195
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import logic.connectives logic.identities algebra.binary open eq.ops binary function definition set (X : Type) := X → Prop namespace set variable {X : Type} /- membership and subset -/ definition mem (x : X) (a : set X) := a x infix ∈ := mem notation a ∉ b := ¬ mem a b theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (H x)) definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b infix ⊆ := subset definition superset (s t : set X) : Prop := t ⊆ s infix ⊇ := superset theorem subset.refl (a : set X) : a ⊆ a := take x : X, show x ∈ a → x ∈ a, from (λ H : x ∈ a, H) theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x : X, show x ∈ a → x ∈ c, from (λ H : x ∈ a, subbc (subab H)) theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := show a = b, from have Hf : ∀ x : X, x ∈ a → x ∈ b, from h₁, have Hb : ∀ x : X, x ∈ b → x ∈ a, from h₂, have H : ∀ x : X, x ∈ a ↔ x ∈ b, from (λ x : X, iff.intro (Hf x) (Hb x)), ext H -- an alternative name theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ _ h₂ /- strict subset -/ definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b infix ` ⊂ `:50 := strict_subset theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a := assume h, absurd rfl (and.elim_right h) /- bounded quantification -/ abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x notation `forallb` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_forall a r notation `∀₀` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_forall a r abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x notation `existsb` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_exists a r notation `∃₀` binders ` ∈ ` a `, ` r:(scoped:1 P, P) := bounded_exists a r theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) : ∃₀ x ∈ s, P x := exists.intro x (and.intro xs Px) lemma bounded_forall_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x ∈ S, P x ↔ Q x) : (∀₀ x ∈ S, P x) = (∀₀ x ∈ S, Q x) := begin apply propext, apply forall_congr, intros x, apply imp_congr_right, apply H end lemma bounded_exists_congr {A : Type} {S : set A} {P Q : A → Prop} (H : ∀₀ x ∈ S, P x ↔ Q x) : (∃₀ x ∈ S, P x) = (∃₀ x ∈ S, Q x) := begin apply propext, apply exists_congr, intros x, apply and_congr_right, apply H end section open classical lemma not_bounded_exists {A : Type} {S : set A} {P : A → Prop} : (¬ (∃₀ x ∈ S, P x)) = (∀₀ x ∈ S, ¬ P x) := begin rewrite forall_iff_not_exists, apply propext, apply forall_congr, intro x, rewrite not_and_iff_not_or_not, symmetry, apply imp_iff_not_or end lemma not_bounded_forall {A : Type} {S : set A} {P : A → Prop} : (¬ (∀₀ x ∈ S, P x)) = (∃₀ x ∈ S, ¬ P x) := calc (¬ (∀₀ x ∈ S, P x)) = ¬ ¬ (∃₀ x ∈ S, ¬ P x) : begin rewrite not_bounded_exists, apply (congr_arg not), apply bounded_forall_congr, intros x H, rewrite not_not_iff end ... = (∃₀ x ∈ S, ¬ P x) : by (rewrite not_not_iff) end /- empty set -/ definition empty : set X := λx, false notation `∅` := empty theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (H x)) (assume xe, absurd xe !not_mem_empty)) theorem ne_empty_of_mem {s : set X} {x : X} (H : x ∈ s) : s ≠ ∅ := begin intro Hs, rewrite Hs at H, apply not_mem_empty _ H end section open classical theorem exists_mem_of_ne_empty {s : set X} (H : s ≠ ∅) : ∃ x, x ∈ s := by_contradiction (assume H', H (eq_empty_of_forall_not_mem (forall_not_of_not_exists H'))) end theorem empty_subset (s : set X) : ∅ ⊆ s := take x, assume H, false.elim H theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ := subset.antisymm H (empty_subset s) theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) lemma bounded_forall_empty_iff {P : X → Prop} : (∀₀x∈∅, P x) ↔ true := iff.intro (take H, true.intro) (take H, by contradiction) /- universal set -/ definition univ : set X := λx, true theorem mem_univ (x : X) : x ∈ univ := trivial theorem mem_univ_iff (x : X) : x ∈ univ ↔ true := !iff.refl theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ := assume H : empty = univ, absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _)) theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ := eq_of_subset_of_subset (subset_univ s) H theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ := ext (take x, iff.intro (assume H', trivial) (assume H', H x)) /- union -/ definition union (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b notation a ∪ b := union a b theorem mem_union_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_union_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_unionl {x : X} {a b : set X} : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_unionr {x : X} {a b : set X} : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_or_mem_of_mem_union {x : X} {a b : set X} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : X} {a b : set X} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union_iff (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl theorem union_self (a : set X) : a ∪ a = a := ext (take x, !or_self) theorem union_empty (a : set X) : a ∪ ∅ = a := ext (take x, !or_false) theorem empty_union (a : set X) : ∅ ∪ a = a := ext (take x, !false_or) theorem union_comm (a b : set X) : a ∪ b = b ∪ a := ext (take x, or.comm) theorem union_assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) theorem union_left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt) /- intersection -/ definition inter (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b theorem mem_inter_iff (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : X} {a b : set X} (Ha : x ∈ a) (Hb : x ∈ b) : x ∈ a ∩ b := and.intro Ha Hb theorem mem_of_mem_inter_left {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ a := and.left H theorem mem_of_mem_inter_right {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ b := and.right H theorem inter_self (a : set X) : a ∩ a = a := ext (take x, !and_self) theorem inter_empty (a : set X) : a ∩ ∅ = ∅ := ext (take x, !and_false) theorem empty_inter (a : set X) : ∅ ∩ a = ∅ := ext (take x, !false_and) theorem nonempty_of_inter_nonempty_right {T : Type} {s t : set T} (H : s ∩ t ≠ ∅) : t ≠ ∅ := suppose t = ∅, have s ∩ t = ∅, by rewrite this; apply inter_empty, H this theorem nonempty_of_inter_nonempty_left {T : Type} {s t : set T} (H : s ∩ t ≠ ∅) : s ≠ ∅ := suppose s = ∅, have s ∩ t = ∅, by rewrite this; apply empty_inter, H this theorem inter_comm (a b : set X) : a ∩ b = b ∩ a := ext (take x, !and.comm) theorem inter_assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, !and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_univ (a : set X) : a ∩ univ = a := ext (take x, !and_true) theorem univ_inter (a : set X) : univ ∩ a = a := ext (take x, !true_and) theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H theorem inter_subset_inter_right {s t : set X} (u : set X) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := take x, assume xsu, and.intro (H (and.left xsu)) (and.right xsu) theorem inter_subset_inter_left {s t : set X} (u : set X) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := take x, assume xus, and.intro (and.left xus) (H (and.right xus)) theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x xr, and.intro (rs xr) (rt xr) theorem not_mem_of_mem_of_not_mem_inter_left {s t : set X} {x : X} (Hxs : x ∈ s) (Hnm : x ∉ s ∩ t) : x ∉ t := suppose x ∈ t, have x ∈ s ∩ t, from and.intro Hxs this, show false, from Hnm this theorem not_mem_of_mem_of_not_mem_inter_right {s t : set X} {x : X} (Hxs : x ∈ t) (Hnm : x ∉ s ∩ t) : x ∉ s := suppose x ∈ s, have x ∈ s ∩ t, from and.intro this Hxs, show false, from Hnm this /- distributivity laws -/ theorem inter_distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, !and.left_distrib) theorem inter_distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, !and.right_distrib) theorem union_distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, !or.left_distrib) theorem union_distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, !or.right_distrib) /- set-builder notation -/ -- {x : X | P} definition set_of (P : X → Prop) : set X := P notation `{` binder ` | ` r:(scoped:1 P, set_of P) `}` := r -- {x ∈ s | P} definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x notation `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r /- insert -/ definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a} -- '{x, y, z} notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a := take y, assume ys, or.inr ys theorem mem_insert (x : X) (s : set X) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s := assume h, or.inr h theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s := assume h, h theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_eq_of_mem {a : X} {s : set X} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) -- useful in proofs by induction theorem forall_of_forall_insert {P : X → Prop} {a : X} {s : set X} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) lemma bounded_forall_insert_iff {P : X → Prop} {a : X} {s : set X} : (∀₀x ∈ insert a s, P x) ↔ P a ∧ (∀₀x ∈ s, P x) := begin apply iff.intro, all_goals (intro H), { apply and.intro, { apply H, apply mem_insert }, { intro x Hx, apply H, apply mem_insert_of_mem, assumption } }, { intro x Hx, cases Hx with eq Hx, { cases eq, apply (and.elim_left H) }, { apply (and.elim_right H), assumption } } end /- singleton -/ theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b := iff.intro (assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f)) (assume aeqb, or.inl aeqb) theorem mem_singleton (a : X) : a ∈ '{a} := !mem_insert theorem eq_of_mem_singleton {x y : X} (h : x ∈ '{y}) : x = y := or.elim (eq_or_mem_of_mem_insert h) (suppose x = y, this) (suppose x ∈ ∅, absurd this !not_mem_empty) theorem mem_singleton_of_eq {x y : X} (H : x = y) : x ∈ '{y} := eq.symm H ▸ mem_singleton y theorem insert_eq (x : X) (s : set X) : insert x s = '{x} ∪ s := ext (take y, iff.intro (suppose y ∈ insert x s, or.elim this (suppose y = x, or.inl (or.inl this)) (suppose y ∈ s, or.inr this)) (suppose y ∈ '{x} ∪ s, or.elim this (suppose y ∈ '{x}, or.inl (eq_of_mem_singleton this)) (suppose y ∈ s, or.inr this))) theorem pair_eq_singleton (a : X) : '{a, a} = '{a} := by rewrite [insert_eq_of_mem !mem_singleton] theorem singleton_ne_empty (a : X) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end /- separation -/ theorem mem_sep {s : set X} {P : X → Prop} {x : X} (xs : x ∈ s) (Px : P x) : x ∈ {x ∈ s | P x} := and.intro xs Px theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, and.intro (ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, and.right this)) theorem mem_sep_iff {s : set X} {P : X → Prop} {x : X} : x ∈ {x ∈ s | P x} ↔ x ∈ s ∧ P x := !iff.refl theorem sep_subset (s : set X) (P : X → Prop) : {x ∈ s | P x} ⊆ s := take x, assume H, and.left H theorem forall_not_of_sep_empty {s : set X} {P : X → Prop} (H : {x ∈ s | P x} = ∅) : ∀₀ x ∈ s, ¬ P x := take x, suppose x ∈ s, suppose P x, have x ∈ {x ∈ s | P x}, from and.intro `x ∈ s` this, show false, from ne_empty_of_mem this H /- complement -/ definition compl (s : set X) : set X := {x | x ∉ s} prefix `-` := compl theorem mem_compl {s : set X} {x : X} (H : x ∉ s) : x ∈ -s := H theorem not_mem_of_mem_compl {s : set X} {x : X} (H : x ∈ -s) : x ∉ s := H theorem mem_compl_iff (s : set X) (x : X) : x ∈ -s ↔ x ∉ s := !iff.refl theorem inter_compl_self (s : set X) : s ∩ -s = ∅ := ext (take x, !and_not_self_iff) theorem compl_inter_self (s : set X) : -s ∩ s = ∅ := ext (take x, !not_and_self_iff) /- some classical identities -/ section open classical theorem compl_empty : -(∅ : set X) = univ := ext (take x, iff.intro (assume H, trivial) (assume H, not_false)) theorem compl_union (s t : set X) : -(s ∪ t) = -s ∩ -t := ext (take x, !not_or_iff_not_and_not) theorem compl_compl (s : set X) : -(-s) = s := ext (take x, !not_not_iff) theorem compl_inter (s t : set X) : -(s ∩ t) = -s ∪ -t := ext (take x, !not_and_iff_not_or_not) theorem compl_univ : -(univ : set X) = ∅ := by rewrite [-compl_empty, compl_compl] theorem union_eq_compl_compl_inter_compl (s t : set X) : s ∪ t = -(-s ∩ -t) := ext (take x, !or_iff_not_and_not) theorem inter_eq_compl_compl_union_compl (s t : set X) : s ∩ t = -(-s ∪ -t) := ext (take x, !and_iff_not_or_not) theorem union_compl_self (s : set X) : s ∪ -s = univ := ext (take x, !or_not_self_iff) theorem compl_union_self (s : set X) : -s ∪ s = univ := ext (take x, !not_or_self_iff) theorem compl_comp_compl : #function compl ∘ compl = @id (set X) := funext (λ s, compl_compl s) end /- set difference -/ definition diff (s t : set X) : set X := {x ∈ s | x ∉ t} infix `\`:70 := diff theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := and.intro H1 H2 theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s := and.left H theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t := and.right H theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl theorem diff_eq (s t : set X) : s \ t = s ∩ -t := rfl theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2)) (assume H1 : x ∈ t, decidable.by_cases (suppose x ∈ s, or.inl this) (suppose x ∉ s, or.inr (and.intro H1 this)))) theorem diff_subset (s t : set X) : s \ t ⊆ s := inter_subset_left s _ theorem compl_eq_univ_diff (s : set X) : -s = univ \ s := ext (take x, iff.intro (assume H, and.intro trivial H) (assume H, and.right H)) /- powerset -/ definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set X} (H : x ⊆ s) : x ∈ 𝒫 s := H theorem subset_of_mem_powerset {x s : set X} (H : x ∈ 𝒫 s) : x ⊆ s := H theorem mem_powerset_iff (x s : set X) : x ∈ 𝒫 s ↔ x ⊆ s := !iff.refl /- function image -/ section image variables {Y Z : Type} abbreviation eq_on (f1 f2 : X → Y) (a : set X) : Prop := ∀₀ x ∈ a, f1 x = f2 x definition image (f : X → Y) (a : set X) : set Y := {y : Y | ∃x, x ∈ a ∧ f x = y} infix ` ' ` := image theorem image_eq_image_of_eq_on {f1 f2 : X → Y} {a : set X} (H1 : eq_on f1 f2 a) : f1 ' a = f2 ' a := ext (take y, iff.intro (assume H2, obtain x (H3 : x ∈ a ∧ f1 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f2 x = y, from (H1 H4)⁻¹ ⬝ and.right H3, exists.intro x (and.intro H4 H5)) (assume H2, obtain x (H3 : x ∈ a ∧ f2 x = y), from H2, have H4 : x ∈ a, from and.left H3, have H5 : f1 x = y, from (H1 H4) ⬝ and.right H3, exists.intro x (and.intro H4 H5))) theorem mem_image {f : X → Y} {a : set X} {x : X} {y : Y} (H1 : x ∈ a) (H2 : f x = y) : y ∈ f ' a := exists.intro x (and.intro H1 H2) theorem mem_image_of_mem (f : X → Y) {x : X} {a : set X} (H : x ∈ a) : f x ∈ image f a := mem_image H rfl lemma image_comp (f : Y → Z) (g : X → Y) (a : set X) : (f ∘ g) ' a = f ' (g ' a) := ext (take z, iff.intro (assume Hz : z ∈ (f ∘ g) ' a, obtain x (Hx₁ : x ∈ a) (Hx₂ : f (g x) = z), from Hz, have Hgx : g x ∈ g ' a, from mem_image Hx₁ rfl, show z ∈ f ' (g ' a), from mem_image Hgx Hx₂) (assume Hz : z ∈ f ' (g 'a), obtain y (Hy₁ : y ∈ g ' a) (Hy₂ : f y = z), from Hz, obtain x (Hz₁ : x ∈ a) (Hz₂ : g x = y), from Hy₁, show z ∈ (f ∘ g) ' a, from mem_image Hz₁ (Hz₂⁻¹ ▸ Hy₂))) lemma image_subset {a b : set X} (f : X → Y) (H : a ⊆ b) : f ' a ⊆ f ' b := take y, assume Hy : y ∈ f ' a, obtain x (Hx₁ : x ∈ a) (Hx₂ : f x = y), from Hy, mem_image (H Hx₁) Hx₂ theorem image_union (f : X → Y) (s t : set X) : image f (s ∪ t) = image f s ∪ image f t := ext (take y, iff.intro (assume H : y ∈ image f (s ∪ t), obtain x [(xst : x ∈ s ∪ t) (fxy : f x = y)], from H, or.elim xst (assume xs, or.inl (mem_image xs fxy)) (assume xt, or.inr (mem_image xt fxy))) (assume H : y ∈ image f s ∪ image f t, or.elim H (assume yifs : y ∈ image f s, obtain x [(xs : x ∈ s) (fxy : f x = y)], from yifs, mem_image (or.inl xs) fxy) (assume yift : y ∈ image f t, obtain x [(xt : x ∈ t) (fxy : f x = y)], from yift, mem_image (or.inr xt) fxy))) theorem image_empty (f : X → Y) : image f ∅ = ∅ := eq_empty_of_forall_not_mem (take y, suppose y ∈ image f ∅, obtain x [(H : x ∈ empty) H'], from this, H) theorem mem_image_compl (t : set X) (S : set (set X)) : t ∈ compl ' S ↔ -t ∈ S := iff.intro (suppose t ∈ compl ' S, obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, show -t ∈ S, by rewrite [-Ht, compl_compl]; exact Ht') (suppose -t ∈ S, have -(-t) ∈ compl 'S, from mem_image_of_mem compl this, show t ∈ compl 'S, from compl_compl t ▸ this) theorem image_id (s : set X) : id ' s = s := ext (take x, iff.intro (suppose x ∈ id ' s, obtain x' [(Hx' : x' ∈ s) (x'eq : x' = x)], from this, show x ∈ s, by rewrite [-x'eq]; apply Hx') (suppose x ∈ s, mem_image_of_mem id this)) theorem compl_compl_image (S : set (set X)) : compl ' (compl ' S) = S := by rewrite [-image_comp, compl_comp_compl, image_id] lemma bounded_forall_image_of_bounded_forall {f : X → Y} {S : set X} {P : Y → Prop} (H : ∀₀ x ∈ S, P (f x)) : ∀₀ y ∈ f ' S, P y := begin intro x' Hx; cases Hx with x Hx; cases Hx with Hx eq; rewrite (eq⁻¹); apply H; assumption end lemma bounded_forall_image_iff {f : X → Y} {S : set X} {P : Y → Prop} : (∀₀ y ∈ f ' S, P y) ↔ (∀₀ x ∈ S, P (f x)) := iff.intro (take H x Hx, H _ (!mem_image_of_mem `x ∈ S`)) bounded_forall_image_of_bounded_forall lemma image_insert_eq {f : X → Y} {a : X} {S : set X} : f ' insert a S = insert (f a) (f ' S) := begin apply set.ext, intro x, apply iff.intro, all_goals (intros H), { cases H with y Hy, cases Hy with Hy eq, rewrite (eq⁻¹), cases Hy with y_eq, { rewrite y_eq, apply mem_insert }, { apply mem_insert_of_mem, apply mem_image_of_mem, assumption } }, { cases H with eq Hx, { rewrite eq, apply mem_image_of_mem, apply mem_insert }, { cases Hx with y Hy, cases Hy with Hy eq, rewrite (eq⁻¹), apply mem_image_of_mem, apply mem_insert_of_mem, assumption } } end end image /- collections of disjoint sets -/ definition disjoint_sets (S : set (set X)) : Prop := ∀ a b, a ∈ S → b ∈ S → a ≠ b → a ∩ b = ∅ theorem disjoint_sets_empty : disjoint_sets (∅ : set (set X)) := take a b, assume H, !not.elim !not_mem_empty H theorem disjoint_sets_union {s t : set (set X)} (Hs : disjoint_sets s) (Ht : disjoint_sets t) (H : ∀ x y, x ∈ s ∧ y ∈ t → x ∩ y = ∅) : disjoint_sets (s ∪ t) := take a b, assume Ha Hb Hneq, or.elim Ha (assume H1, or.elim Hb (suppose b ∈ s, (Hs a b) H1 this Hneq) (suppose b ∈ t, (H a b) (and.intro H1 this))) (assume H2, or.elim Hb (suppose b ∈ s, !inter_comm ▸ ((H b a) (and.intro this H2))) (suppose b ∈ t, (Ht a b) H2 this Hneq)) theorem disjoint_sets_singleton (s : set (set X)) : disjoint_sets '{s} := take a b, assume Ha Hb Hneq, absurd (eq.trans ((iff.elim_left !mem_singleton_iff) Ha) ((iff.elim_left !mem_singleton_iff) Hb)⁻¹) Hneq /- large unions -/ section large_unions variables {I : Type} variable a : set I variable b : I → set X variable C : set (set X) definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c} definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c} prefix `⋃₀`:110 := sUnion prefix `⋂₀`:110 := sInter definition Union : set X := {x : X | ∃i, x ∈ b i} definition Inter : set X := {x : X | ∀i, x ∈ b i} notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i} definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i} notation `⋃` binders ` ∈ ` s `, ` r:(scoped f, bUnion s f) := r notation `⋂` binders ` ∈ ` s `, ` r:(scoped f, bInter s f) := r end large_unions -- sUnion and sInter: a collection (set) of sets theorem mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∈ t) (Ht : t ∈ S) : x ∈ ⋃₀ S := exists.intro t (and.intro Ht Hx) theorem not_mem_of_not_mem_sUnion {x : X} {t : set X} {S : set (set X)} (Hx : x ∉ ⋃₀ S) (Ht : t ∈ S) : x ∉ t := suppose x ∈ t, have x ∈ ⋃₀ S, from mem_sUnion this Ht, show false, from Hx this theorem mem_sInter {x : X} {t : set X} {S : set (set X)} (H : ∀₀ t ∈ S, x ∈ t) : x ∈ ⋂₀ S := H theorem sInter_subset_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) : (⋂₀ S) ⊆ t := take x, assume H, H t tS theorem subset_sUnion_of_mem {S : set (set X)} {t : set X} (tS : t ∈ S) : t ⊆ (⋃₀ S) := take x, assume H, exists.intro t (and.intro tS H) theorem sUnion_empty : ⋃₀ ∅ = (∅ : set X) := eq_empty_of_forall_not_mem (take x, suppose x ∈ sUnion ∅, obtain t [(Ht : t ∈ ∅) Ht'], from this, show false, from Ht) theorem sInter_empty : ⋂₀ ∅ = (univ : set X) := eq_univ_of_forall (λ x s H, false.elim H) theorem sUnion_singleton (s : set X) : ⋃₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ sUnion '{s}, obtain u [(Hu : u ∈ '{s}) (xu : x ∈ u)], from this, have u = s, from eq_of_mem_singleton Hu, show x ∈ s, by rewrite -this; apply xu) (suppose x ∈ s, mem_sUnion this (mem_singleton s))) theorem sInter_singleton (s : set X) : ⋂₀ '{s} = s := ext (take x, iff.intro (suppose x ∈ ⋂₀ '{s}, show x ∈ s, from this (mem_singleton s)) (suppose x ∈ s, take u, suppose u ∈ '{s}, show x ∈ u, by rewrite [eq_of_mem_singleton this]; assumption)) theorem sUnion_union (S T : set (set X)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := ext (take x, iff.intro (suppose x ∈ sUnion (S ∪ T), obtain u [(Hu : u ∈ S ∪ T) (xu : x ∈ u)], from this, or.elim Hu (assume uS, or.inl (mem_sUnion xu uS)) (assume uT, or.inr (mem_sUnion xu uT))) (suppose x ∈ sUnion S ∪ sUnion T, or.elim this (suppose x ∈ sUnion S, obtain u [(uS : u ∈ S) (xu : x ∈ u)], from this, mem_sUnion xu (or.inl uS)) (suppose x ∈ sUnion T, obtain u [(uT : u ∈ T) (xu : x ∈ u)], from this, mem_sUnion xu (or.inr uT)))) theorem sInter_union (S T : set (set X)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := ext (take x, iff.intro (assume H : x ∈ ⋂₀ (S ∪ T), and.intro (λ u uS, H (or.inl uS)) (λ u uT, H (or.inr uT))) (assume H : x ∈ ⋂₀ S ∩ ⋂₀ T, take u, suppose u ∈ S ∪ T, or.elim this (λ uS, and.left H u uS) (λ uT, and.right H u uT))) theorem sUnion_insert (s : set X) (T : set (set X)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := by rewrite [insert_eq, sUnion_union, sUnion_singleton] theorem sInter_insert (s : set X) (T : set (set X)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := by rewrite [insert_eq, sInter_union, sInter_singleton] theorem compl_sUnion (S : set (set X)) : - ⋃₀ S = ⋂₀ (compl ' S) := ext (take x, iff.intro (assume H : x ∈ -(⋃₀ S), take t, suppose t ∈ compl ' S, obtain t' [(Ht' : t' ∈ S) (Ht : -t' = t)], from this, have x ∈ -t', from suppose x ∈ t', H (mem_sUnion this Ht'), show x ∈ t, by rewrite -Ht; apply this) (assume H : x ∈ ⋂₀ (compl ' S), suppose x ∈ ⋃₀ S, obtain t [(tS : t ∈ S) (xt : x ∈ t)], from this, have -t ∈ compl ' S, from mem_image_of_mem compl tS, have x ∈ -t, from H this, show false, proof this xt qed)) theorem sUnion_eq_compl_sInter_compl (S : set (set X)) : ⋃₀ S = - ⋂₀ (compl ' S) := by rewrite [-compl_compl (⋃₀ S), compl_sUnion] theorem compl_sInter (S : set (set X)) : - ⋂₀ S = ⋃₀ (compl ' S) := by rewrite [sUnion_eq_compl_sInter_compl, compl_compl_image] theorem sInter_eq_comp_sUnion_compl (S : set (set X)) : ⋂₀ S = -(⋃₀ (compl ' S)) := by rewrite [-compl_compl (⋂₀ S), compl_sInter] theorem inter_sUnion_nonempty_of_inter_nonempty {s t : set X} {S : set (set X)} (Hs : t ∈ S) (Hne : s ∩ t ≠ ∅) : s ∩ ⋃₀ S ≠ ∅ := obtain x Hsx Htx, from exists_mem_of_ne_empty Hne, have x ∈ ⋃₀ S, from mem_sUnion Htx Hs, ne_empty_of_mem (mem_inter Hsx this) theorem sUnion_inter_nonempty_of_inter_nonempty {s t : set X} {S : set (set X)} (Hs : t ∈ S) (Hne : t ∩ s ≠ ∅) : (⋃₀ S) ∩ s ≠ ∅ := obtain x Htx Hsx, from exists_mem_of_ne_empty Hne, have x ∈ ⋃₀ S, from mem_sUnion Htx Hs, ne_empty_of_mem (mem_inter this Hsx) -- Union and Inter: a family of sets indexed by a type theorem Union_subset {I : Type} {b : I → set X} {c : set X} (H : ∀ i, b i ⊆ c) : (⋃ i, b i) ⊆ c := take x, suppose x ∈ Union b, obtain i (Hi : x ∈ b i), from this, show x ∈ c, from H i Hi theorem subset_Inter {I : Type} {b : I → set X} {c : set X} (H : ∀ i, c ⊆ b i) : c ⊆ ⋂ i, b i := λ x cx i, H i cx theorem Union_eq_sUnion_image {X I : Type} (s : I → set X) : (⋃ i, s i) = ⋃₀ (s ' univ) := ext (take x, iff.intro (suppose x ∈ Union s, obtain i (Hi : x ∈ s i), from this, mem_sUnion Hi (mem_image_of_mem s trivial)) (suppose x ∈ sUnion (s ' univ), obtain t [(Ht : t ∈ s ' univ) (Hx : x ∈ t)], from this, obtain i [univi (Hi : s i = t)], from Ht, exists.intro i (show x ∈ s i, by rewrite Hi; apply Hx))) theorem Inter_eq_sInter_image {X I : Type} (s : I → set X) : (⋂ i, s i) = ⋂₀ (s ' univ) := ext (take x, iff.intro (assume H : x ∈ Inter s, take t, suppose t ∈ s 'univ, obtain i [univi (Hi : s i = t)], from this, show x ∈ t, by rewrite -Hi; exact H i) (assume H : x ∈ ⋂₀ (s ' univ), take i, have s i ∈ s ' univ, from mem_image_of_mem s trivial, show x ∈ s i, from H this)) theorem compl_Union {X I : Type} (s : I → set X) : - (⋃ i, s i) = (⋂ i, - s i) := by rewrite [Union_eq_sUnion_image, compl_sUnion, -image_comp, -Inter_eq_sInter_image] theorem compl_Inter {X I : Type} (s : I → set X) : -(⋂ i, s i) = (⋃ i, - s i) := by rewrite [Inter_eq_sInter_image, compl_sInter, -image_comp, -Union_eq_sUnion_image] theorem Union_eq_comp_Inter_comp {X I : Type} (s : I → set X) : (⋃ i, s i) = - (⋂ i, - s i) := by rewrite [-compl_compl (⋃ i, s i), compl_Union] theorem Inter_eq_comp_Union_comp {X I : Type} (s : I → set X) : (⋂ i, s i) = - (⋃ i, -s i) := by rewrite [-compl_compl (⋂ i, s i), compl_Inter] lemma inter_distrib_Union_left {X I : Type} (s : I → set X) (a : set X) : a ∩ (⋃ i, s i) = ⋃ i, a ∩ s i := ext (take x, iff.intro (assume H, obtain i Hi, from and.elim_right H, have x ∈ a ∩ s i, from and.intro (and.elim_left H) Hi, show _, from exists.intro i this) (assume H, obtain i [xa xsi], from H, show _, from and.intro xa (exists.intro i xsi))) section open classical lemma union_distrib_Inter_left {X I : Type} (s : I → set X) (a : set X) : a ∪ (⋂ i, s i) = ⋂ i, a ∪ s i := ext (take x, iff.intro (assume H, or.elim H (assume H1, take i, or.inl H1) (assume H1, take i, or.inr (H1 i))) (assume H, by_cases (suppose x ∈ a, or.inl this) (suppose x ∉ a, or.inr (take i, or.resolve_left (H i) this)))) end -- these are useful for turning binary union / intersection into countable ones definition bin_ext (s t : set X) (n : ℕ) : set X := nat.cases_on n s (λ m, t) lemma Union_bin_ext (s t : set X) : (⋃ i, bin_ext s t i) = s ∪ t := ext (take x, iff.intro (assume H, obtain i (Hi : x ∈ (bin_ext s t) i), from H, by cases i; apply or.inl Hi; apply or.inr Hi) (assume H, or.elim H (suppose x ∈ s, exists.intro 0 this) (suppose x ∈ t, exists.intro 1 this))) lemma Inter_bin_ext (s t : set X) : (⋂ i, bin_ext s t i) = s ∩ t := ext (take x, iff.intro (assume H, and.intro (H 0) (H 1)) (assume H, by intro i; cases i; apply and.elim_left H; apply and.elim_right H)) -- bUnion and bInter: a family of sets indexed by a set ("b" is for bounded) variable {Y : Type} theorem mem_bUnion {s : set X} {f : X → set Y} {x : X} {y : Y} (xs : x ∈ s) (yfx : y ∈ f x) : y ∈ ⋃ x ∈ s, f x := exists.intro x (and.intro xs yfx) theorem mem_bInter {s : set X} {f : X → set Y} {y : Y} (H : ∀₀ x ∈ s, y ∈ f x) : y ∈ ⋂ x ∈ s, f x := H theorem bUnion_subset {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, f x ⊆ t) : (⋃ x ∈ s, f x) ⊆ t := take y, assume Hy, obtain x [xs yfx], from Hy, show y ∈ t, from H xs yfx theorem subset_bInter {s : set X} {t : set Y} {f : X → set Y} (H : ∀₀ x ∈ s, t ⊆ f x) : t ⊆ ⋂ x ∈ s, f x := take y, assume yt, take x, assume xs, H xs yt theorem subset_bUnion_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) : f x ⊆ ⋃ x ∈ s, f x := take y, assume Hy, mem_bUnion xs Hy theorem bInter_subset_of_mem {s : set X} {f : X → set Y} {x : X} (xs : x ∈ s) : (⋂ x ∈ s, f x) ⊆ f x := take y, assume Hy, Hy x xs theorem bInter_empty (f : X → set Y) : (⋂ x ∈ (∅ : set X), f x) = univ := eq_univ_of_forall (take y x xine, absurd xine !not_mem_empty) theorem bInter_singleton (a : X) (f : X → set Y) : (⋂ x ∈ '{a}, f x) = f a := ext (take y, iff.intro (assume H, H a !mem_singleton) (assume H, λ x xa, by rewrite [eq_of_mem_singleton xa]; apply H)) theorem bInter_union (s t : set X) (f : X → set Y) : (⋂ x ∈ s ∪ t, f x) = (⋂ x ∈ s, f x) ∩ (⋂ x ∈ t, f x) := ext (take y, iff.intro (assume H, and.intro (λ x xs, H x (or.inl xs)) (λ x xt, H x (or.inr xt))) (assume H, λ x xst, or.elim (xst) (λ xs, and.left H x xs) (λ xt, and.right H x xt))) theorem bInter_insert (a : X) (s : set X) (f : X → set Y) : (⋂ x ∈ insert a s, f x) = f a ∩ (⋂ x ∈ s, f x) := by rewrite [insert_eq, bInter_union, bInter_singleton] theorem bInter_pair (a b : X) (f : X → set Y) : (⋂ x ∈ '{a, b}, f x) = f a ∩ f b := by rewrite [*bInter_insert, bInter_empty, inter_univ] theorem bUnion_empty (f : X → set Y) : (⋃ x ∈ (∅ : set X), f x) = ∅ := eq_empty_of_forall_not_mem (λ y H, obtain x [xine yfx], from H, !not_mem_empty xine) theorem bUnion_singleton (a : X) (f : X → set Y) : (⋃ x ∈ '{a}, f x) = f a := ext (take y, iff.intro (assume H, obtain x [xina yfx], from H, show y ∈ f a, by rewrite [-eq_of_mem_singleton xina]; exact yfx) (assume H, exists.intro a (and.intro !mem_singleton H))) theorem bUnion_union (s t : set X) (f : X → set Y) : (⋃ x ∈ s ∪ t, f x) = (⋃ x ∈ s, f x) ∪ (⋃ x ∈ t, f x) := ext (take y, iff.intro (assume H, obtain x [xst yfx], from H, or.elim xst (λ xs, or.inl (exists.intro x (and.intro xs yfx))) (λ xt, or.inr (exists.intro x (and.intro xt yfx)))) (assume H, or.elim H (assume H1, obtain x [xs yfx], from H1, exists.intro x (and.intro (or.inl xs) yfx)) (assume H1, obtain x [xt yfx], from H1, exists.intro x (and.intro (or.inr xt) yfx)))) theorem bUnion_insert (a : X) (s : set X) (f : X → set Y) : (⋃ x ∈ insert a s, f x) = f a ∪ (⋃ x ∈ s, f x) := by rewrite [insert_eq, bUnion_union, bUnion_singleton] theorem bUnion_pair (a b : X) (f : X → set Y) : (⋃ x ∈ '{a, b}, f x) = f a ∪ f b := by rewrite [*bUnion_insert, bUnion_empty, union_empty] end set
0401f8d968bae741933b608eeb00f0a9864a70f6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/inlineIfReduceLCNF.lean
78b4343567fa764260209b877aaec082319daf80
[ "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
141
lean
import Lean def f (x y z : Nat) : Array Nat := #[x, y, z, y, x] set_option trace.Compiler.result true #eval Lean.Compiler.compile #[``f]
549602c4ab77d73b8513382446de732ac52918bd
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/cardinality/countable_inj.lean
53fe8bad40e38e0bb6ef196b397025d1f2b20e69
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
917
lean
import data.real.basic import topology.basic open function open set namespace xena -- hide /- # Chapter 7 : Cardinality ## Level 3 A classical result about countable sets. -/ /- Lemma If $f : X \to Y$ is an injective function and $Y$ is countable, then $X$ is also countable. -/ theorem countable_inj (X Y : set ℝ) (f : X → Y) (hY : countable Y) : injective f → countable X := begin intro hf, have H := countable_iff_exists_injective.1 hY, cases H with g hg, have G := countable_iff_exists_injective.2 ⟨g ∘ f, injective.comp hg hf⟩, exact G, done end end xena -- hide -- begin hide -- term mode proof due to Kenny Lau theorem countable_inj_2 (X Y : set ℝ) (f : X → Y) (hY : countable Y) : injective f → countable X := λ hf, let ⟨g, hg⟩ := countable_iff_exists_injective.1 hY in countable_iff_exists_injective.2 ⟨g ∘ f, injective.comp hg hf⟩ -- end hide
10884a64b22e707410a975b7d5cb6518343f87b7
b561a44b48979a98df50ade0789a21c79ee31288
/src/Init/Meta.lean
9f91448da8233e2c3cedab76859af2d3510454e5
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,981
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] constant getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s _ => s.contains '✝' || s == "_inaccessible" | Name.num p idx _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst s[0] && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s _ => maybeEscape s | num anonymous v _ => toString v | str n s _ => toStringWithSep n ++ sep ++ maybeEscape s | num n v _ => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let Name.str _ s _ := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i _ => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s _ => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec deriving instance Repr for Syntax def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s _ => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s _ => Name.mkStr p (pre ++ s) | num p n _ => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ args => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos trail endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node info _ _) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node SourceInfo.none k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node info k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node info k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val [] def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Syntax := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])] def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident SourceInfo.none (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => mkNode `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : Syntax := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : Syntax := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : Syntax := mkLit nameLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := OptionM.run do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := OptionM.run do let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev escapedPart.bsize) then [] else splitRest (ss.extract escapedPart.bsize ss.bsize) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract idPart.bsize ss.bsize) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → OptionM (List String) | Name.anonymous => acc | Name.str n s _ => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num n i _ => none private def quoteNameMk : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name where quote n := match getEscapedNameParts? [] n with | some ss => mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)] | none => quoteNameMk n instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "eval_prec " p:prec:max : term => return quote (← evalPrec p) /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "eval_prio " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz let sepStx := a.get ⟨i.pred, Nat.lt_trans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance (sep) : CoeTail (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := OptionM.run do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : OptionM String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true iota : Bool := true proj : Bool := true decide : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(rw (config := { transparency := Lean.Meta.TransparencyMode.default }) $s:rwRuleSeq $[$(loc.getOptional?):location]?) end Parser.Tactic end Lean
467ee8d0e156888c4002bafc002db539b57d9c91
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/order/complete_lattice.lean
2dcc1a58df0afb0d60cef2742eca32970a0ce92d
[ "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
43,625
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 order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded` supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj] class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' (by simp only [Sup_le_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans hy']) theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le (by simp only [le_Inf_iff]; introv h₀ h₁; rcases h _ h₁ with ⟨y,hy,hy'⟩; solve_by_elim [le_trans _ hy']) theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs -- TODO: it is weird that we have to add union_def theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := is_lub_empty.Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := is_glb_univ.Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_instert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) : a ≤ ⨆ i hi, f i hi := le_trans h (le_bsupr i hi) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b := ⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩ theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_sUnion {s : set (set α)} : Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have : f₁ ∘ pq.mpr = f₂ := funext f, rw [← this], refine (function.surjective.supr_comp (λ h, ⟨pq.1 h, _⟩) f₁).symm, refl end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) : (⨅ i hi, f i hi) ≤ a := le_trans (binfi_le i hi) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) β _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf (order_dual α) _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi (order_dual α) _ _ _ _ _ /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := @supr_range (order_dual α) _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', infi, range_comp, subtype.range_coe] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ /-! ### `supr` and `infi` under `Type` -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le (λ i, (le_refl _).trans (le_supr _ (i + k)))) (supr_le_supr (λ i, hf (nat.le_add_right i k))) @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i), from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. bounded_distrib_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _) end complete_lattice namespace complete_lattice variables [complete_lattice α] /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : independent s) @[simp] lemma independent_empty : independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem independent.mono {t : set α} (hst : t ⊆ s) : independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y := disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩) include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end end complete_lattice
3f9c6d593c516eca8e7542534c2e0c808ac2f8b9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/integral/vitali_caratheodory.lean
ee826838287605267bfceef48501bc12744ff749
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,686
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.measure.regular import topology.semicontinuous import measure_theory.integral.bochner import topology.instances.ereal /-! # Vitali-Carathéodory theorem Vitali-Carathéodory theorem asserts the following. Consider an integrable function `f : α → ℝ` on a space with a regular measure. Then there exists a function `g : α → ereal` such that `f x < g x` everywhere, `g` is lower semicontinuous, and the integral of `g` is arbitrarily close to that of `f`. This theorem is proved in this file, as `exists_lt_lower_semicontinuous_integral_lt`. Symmetrically, there exists `g < f` which is upper semicontinuous, with integral arbitrarily close to that of `f`. It follows from the previous statement applied to `-f`. It is formalized under the name `exists_upper_semicontinuous_lt_integral_gt`. The most classical version of Vitali-Carathéodory theorem only ensures a large inequality `f x ≤ g x`. For applications to the fundamental theorem of calculus, though, the strict inequality `f x < g x` is important. Therefore, we prove the stronger version with strict inequalities in this file. There is a price to pay: we require that the measure is `σ`-finite, which is not necessary for the classical Vitali-Carathéodory theorem. Since this is satisfied in all applications, this is not a real problem. ## Sketch of proof Decomposing `f` as the difference of its positive and negative parts, it suffices to show that a positive function can be bounded from above by a lower semicontinuous function, and from below by an upper semicontinuous function, with integrals close to that of `f`. For the bound from above, write `f` as a series `∑' n, cₙ * indicator (sₙ)` of simple functions. Then, approximate `sₙ` by a larger open set `uₙ` with measure very close to that of `sₙ` (this is possible by regularity of the measure), and set `g = ∑' n, cₙ * indicator (uₙ)`. It is lower semicontinuous as a series of lower semicontinuous functions, and its integral is arbitrarily close to that of `f`. For the bound from below, use finitely many terms in the series, and approximate `sₙ` from inside by a closed set `Fₙ`. Then `∑ n < N, cₙ * indicator (Fₙ)` is bounded from above by `f`, it is upper semicontinuous as a finite sum of upper semicontinuous functions, and its integral is arbitrarily close to that of `f`. The main pain point in the implementation is that one needs to jump between the spaces `ℝ`, `ℝ≥0`, `ℝ≥0∞` and `ereal` (and be careful that addition is not well behaved on `ereal`), and between `lintegral` and `integral`. We first show the bound from above for simple functions and the nonnegative integral (this is the main nontrivial mathematical point), then deduce it for general nonnegative functions, first for the nonnegative integral and then for the Bochner integral. Then we follow the same steps for the lower bound. Finally, we glue them together to obtain the main statement `exists_lt_lower_semicontinuous_integral_lt`. ## Related results Are you looking for a result on approximation by continuous functions (not just semicontinuous)? See result `measure_theory.Lp.continuous_map_dense`, in the file `measure_theory.continuous_map_dense`. ## References [Rudin, *Real and Complex Analysis* (Theorem 2.24)][rudin2006real] -/ open_locale ennreal nnreal open measure_theory measure_theory.measure variables {α : Type*} [topological_space α] [measurable_space α] [borel_space α] (μ : measure α) [weakly_regular μ] namespace measure_theory local infixr ` →ₛ `:25 := simple_func /-! ### Lower semicontinuous upper bound for nonnegative functions -/ /-- Given a simple function `f` with values in `ℝ≥0`, there exists a lower semicontinuous function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma simple_func.exists_le_lower_semicontinuous_lintegral_ge (f : α →ₛ ℝ≥0) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) := begin induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε, { let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0), by_cases h : ∫⁻ x, f x ∂μ = ⊤, { refine ⟨λ x, c, λ x, _, lower_semicontinuous_const, by simp only [ennreal.top_add, le_top, h]⟩, simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise], exact set.indicator_le_self _ _ _ }, by_cases hc : c = 0, { refine ⟨λ x, 0, _, lower_semicontinuous_const, _⟩, { simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff, eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, le_zero_iff] }, { simp only [lintegral_const, zero_mul, zero_le, ennreal.coe_zero] } }, have : μ s < μ s + ε / c, { have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩, simpa using ennreal.add_lt_add_left _ this, simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, function.const_apply, lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top, measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, or_false, lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and, restrict_apply] using h }, obtain ⟨u, su, u_open, μu⟩ : ∃ u ⊇ s, is_open u ∧ μ u < μ s + ε / c := s.exists_is_open_lt_of_lt _ this, refine ⟨set.indicator u (λ x, c), λ x, _, u_open.lower_semicontinuous_indicator (zero_le _), _⟩, { simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise], exact set.indicator_le_indicator_of_subset su (λ x, zero_le _) _ }, { suffices : (c : ℝ≥0∞) * μ u ≤ c * μ s + ε, by simpa only [hs, u_open.measurable_set, simple_func.coe_const, function.const_apply, lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ, simple_func.const_zero, lintegral_indicator, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply], calc (c : ℝ≥0∞) * μ u ≤ c * (μ s + ε / c) : ennreal.mul_le_mul (le_refl _) μu.le ... = c * μ s + ε : begin simp_rw [mul_add], rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top, simpa using hc, end } }, { rcases h₁ (ennreal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩, rcases h₂ (ennreal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩, refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩, simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply], rw [lintegral_add f₁.measurable.coe_nnreal_ennreal f₂.measurable.coe_nnreal_ennreal, lintegral_add g₁cont.measurable.coe_nnreal_ennreal g₂cont.measurable.coe_nnreal_ennreal], convert add_le_add g₁int g₂int using 1, conv_lhs { rw ← ennreal.add_halves ε }, abel } end open simple_func (eapprox_diff tsum_eapprox_diff) /-- Given a measurable function `f` with values in `ℝ≥0`, there exists a lower semicontinuous function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_le_lower_semicontinuous_lintegral_ge (f : α → ℝ≥0∞) (hf : measurable f) {ε : ℝ≥0∞} (εpos : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) := begin rcases ennreal.exists_pos_sum_of_encodable' εpos ℕ with ⟨δ, δpos, hδ⟩, have : ∀ n, ∃ g : α → ℝ≥0, (∀ x, simple_func.eapprox_diff f n x ≤ g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, simple_func.eapprox_diff f n x ∂μ + δ n) := λ n, simple_func.exists_le_lower_semicontinuous_lintegral_ge μ (simple_func.eapprox_diff f n) (δpos n).ne', choose g f_le_g gcont hg using this, refine ⟨λ x, (∑' n, g n x), λ x, _, _, _⟩, { rw ← tsum_eapprox_diff f hf, exact ennreal.tsum_le_tsum (λ n, ennreal.coe_le_coe.2 (f_le_g n x)) }, { apply lower_semicontinuous_tsum (λ n, _), exact ennreal.continuous_coe.comp_lower_semicontinuous (gcont n) (λ x y hxy, ennreal.coe_le_coe.2 hxy) }, { calc ∫⁻ x, ∑' (n : ℕ), g n x ∂μ = ∑' n, ∫⁻ x, g n x ∂μ : by rw lintegral_tsum (λ n, (gcont n).measurable.coe_nnreal_ennreal) ... ≤ ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ + δ n) : ennreal.tsum_le_tsum hg ... = ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ) + ∑' n, δ n : ennreal.tsum_add ... ≤ ∫⁻ (x : α), f x ∂μ + ε : begin refine add_le_add _ hδ.le, rw [← lintegral_tsum], { simp_rw [tsum_eapprox_diff f hf, le_refl] }, { assume n, exact (simple_func.measurable _).coe_nnreal_ennreal } end } end /-- Given a measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_lt_lower_semicontinuous_lintegral_ge [sigma_finite μ] (f : α → ℝ≥0) (fmeas : measurable f) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) := begin have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne', rcases exists_pos_lintegral_lt_of_sigma_finite μ this with ⟨w, wpos, wmeas, wint⟩, let f' := λ x, ((f x + w x : ℝ≥0) : ℝ≥0∞), rcases exists_le_lower_semicontinuous_lintegral_ge μ f' (fmeas.add wmeas).coe_nnreal_ennreal this with ⟨g, le_g, gcont, gint⟩, refine ⟨g, λ x, _, gcont, _⟩, { calc (f x : ℝ≥0∞) < f' x : by simpa [← ennreal.coe_lt_coe] using add_lt_add_left (wpos x) (f x) ... ≤ g x : le_g x }, { calc ∫⁻ (x : α), g x ∂μ ≤ ∫⁻ (x : α), f x + w x ∂μ + ε / 2 : gint ... = ∫⁻ (x : α), f x ∂ μ + ∫⁻ (x : α), w x ∂ μ + (ε / 2) : by rw lintegral_add fmeas.coe_nnreal_ennreal wmeas.coe_nnreal_ennreal ... ≤ ∫⁻ (x : α), f x ∂ μ + ε / 2 + ε / 2 : add_le_add_right (add_le_add_left wint.le _) _ ... = ∫⁻ (x : α), f x ∂μ + ε : by rw [add_assoc, ennreal.add_halves] }, end /-- Given an almost everywhere measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable [sigma_finite μ] (f : α → ℝ≥0) (fmeas : ae_measurable f μ) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) := begin have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne', rcases exists_lt_lower_semicontinuous_lintegral_ge μ (fmeas.mk f) fmeas.measurable_mk this with ⟨g0, f_lt_g0, g0_cont, g0_int⟩, rcases exists_measurable_superset_of_null fmeas.ae_eq_mk with ⟨s, hs, smeas, μs⟩, rcases exists_le_lower_semicontinuous_lintegral_ge μ (s.indicator (λ x, ∞)) (measurable_const.indicator smeas) this with ⟨g1, le_g1, g1_cont, g1_int⟩, refine ⟨λ x, g0 x + g1 x, λ x, _, g0_cont.add g1_cont, _⟩, { by_cases h : x ∈ s, { have := le_g1 x, simp only [h, set.indicator_of_mem, top_le_iff] at this, simp [this] }, { have : f x = fmeas.mk f x, by { rw set.compl_subset_comm at hs, exact hs h }, rw this, exact (f_lt_g0 x).trans_le le_self_add } }, { calc ∫⁻ x, g0 x + g1 x ∂μ = ∫⁻ x, g0 x ∂μ + ∫⁻ x, g1 x ∂μ : lintegral_add g0_cont.measurable g1_cont.measurable ... ≤ (∫⁻ x, f x ∂μ + ε / 2) + (0 + ε / 2) : begin refine add_le_add _ _, { convert g0_int using 2, exact lintegral_congr_ae (fmeas.ae_eq_mk.fun_comp _) }, { convert g1_int, simp only [smeas, μs, lintegral_const, set.univ_inter, measurable_set.univ, lintegral_indicator, mul_zero, restrict_apply] } end ... = ∫⁻ x, f x ∂μ + ε : by simp only [add_assoc, ennreal.add_halves, zero_add] } end variable {μ} /-- Given an integrable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`. Formulation in terms of `integral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_lt_lower_semicontinuous_integral_gt_nnreal [sigma_finite μ] (f : α → ℝ≥0) (fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧ (∀ᵐ x ∂ μ, g x < ⊤) ∧ (integrable (λ x, (g x).to_real) μ) ∧ (∫ x, (g x).to_real ∂μ < ∫ x, f x ∂μ + ε) := begin have fmeas : ae_measurable f μ, by { convert fint.ae_measurable.real_to_nnreal, ext1 x, simp only [real.to_nnreal_coe] }, lift ε to ℝ≥0 using εpos.le, obtain ⟨δ, δpos, hδε⟩ : ∃ δ : ℝ≥0, 0 < δ ∧ δ < ε, from exists_between εpos, have int_f_ne_top : ∫⁻ (a : α), (f a) ∂μ ≠ ∞ := (has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral).ne, rcases exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable μ f fmeas (ennreal.coe_ne_zero.2 δpos.ne') with ⟨g, f_lt_g, gcont, gint⟩, have gint_ne : ∫⁻ (x : α), g x ∂μ ≠ ∞ := ne_top_of_le_ne_top (by simpa) gint, have g_lt_top : ∀ᵐ (x : α) ∂μ, g x < ∞ := ae_lt_top gcont.measurable gint_ne, have Ig : ∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ = ∫⁻ (a : α), g a ∂μ, { apply lintegral_congr_ae, filter_upwards [g_lt_top], assume x hx, simp only [hx.ne, ennreal.of_real_to_real, ne.def, not_false_iff] }, refine ⟨g, f_lt_g, gcont, g_lt_top, _, _⟩, { refine ⟨gcont.measurable.ennreal_to_real.ae_measurable, _⟩, simp only [has_finite_integral_iff_norm, real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], convert gint_ne.lt_top using 1 }, { rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae], { calc ennreal.to_real (∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ) = ennreal.to_real (∫⁻ (a : α), g a ∂μ) : by congr' 1 ... ≤ ennreal.to_real (∫⁻ (a : α), f a ∂μ + δ) : begin apply ennreal.to_real_mono _ gint, simpa using int_f_ne_top, end ... = ennreal.to_real (∫⁻ (a : α), f a ∂μ) + δ : by rw [ennreal.to_real_add int_f_ne_top ennreal.coe_ne_top, ennreal.coe_to_real] ... < ennreal.to_real (∫⁻ (a : α), f a ∂μ) + ε : add_lt_add_left hδε _ ... = (∫⁻ (a : α), ennreal.of_real ↑(f a) ∂μ).to_real + ε : by simp }, { apply filter.eventually_of_forall (λ x, _), simp }, { exact fmeas.coe_nnreal_real, }, { apply filter.eventually_of_forall (λ x, _), simp }, { apply gcont.measurable.ennreal_to_real.ae_measurable } } end /-! ### Upper semicontinuous lower bound for nonnegative functions -/ /-- Given a simple function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma simple_func.exists_upper_semicontinuous_le_lintegral_le (f : α →ₛ ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) := begin induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε, { let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0), by_cases hc : c = 0, { refine ⟨λ x, 0, _, upper_semicontinuous_const, _⟩, { simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff, eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, le_zero_iff] }, { simp only [hc, set.indicator_zero', lintegral_const, zero_mul, pi.zero_apply, simple_func.const_zero, zero_add, zero_le', simple_func.coe_zero, set.piecewise_eq_indicator, ennreal.coe_zero, simple_func.coe_piecewise, zero_le] } }, have μs_lt_top : μ s < ∞, by simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, or_false, lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top, restrict_apply measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, function.const_apply, lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and] using int_f, have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩, obtain ⟨F, Fs, F_closed, μF⟩ : ∃ F ⊆ s, is_closed F ∧ μ s < μ F + ε / c := hs.exists_is_closed_lt_add μs_lt_top.ne this.ne', refine ⟨set.indicator F (λ x, c), λ x, _, F_closed.upper_semicontinuous_indicator (zero_le _), _⟩, { simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise], exact set.indicator_le_indicator_of_subset Fs (λ x, zero_le _) _ }, { suffices : (c : ℝ≥0∞) * μ s ≤ c * μ F + ε, by simpa only [hs, F_closed.measurable_set, simple_func.coe_const, function.const_apply, lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ, simple_func.const_zero, lintegral_indicator, simple_func.coe_zero, set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply], calc (c : ℝ≥0∞) * μ s ≤ c * (μ F + ε / c) : ennreal.mul_le_mul (le_refl _) μF.le ... = c * μ F + ε : begin simp_rw [mul_add], rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top, simpa using hc, end } }, { have A : ∫⁻ (x : α), f₁ x ∂μ + ∫⁻ (x : α), f₂ x ∂μ ≠ ⊤, by rwa ← lintegral_add f₁.measurable.coe_nnreal_ennreal f₂.measurable.coe_nnreal_ennreal , rcases h₁ (ennreal.add_ne_top.1 A).1 (ennreal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩, rcases h₂ (ennreal.add_ne_top.1 A).2 (ennreal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩, refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩, simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply], rw [lintegral_add f₁.measurable.coe_nnreal_ennreal f₂.measurable.coe_nnreal_ennreal, lintegral_add g₁cont.measurable.coe_nnreal_ennreal g₂cont.measurable.coe_nnreal_ennreal], convert add_le_add g₁int g₂int using 1, conv_lhs { rw ← ennreal.add_halves ε }, abel } end /-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `lintegral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_upper_semicontinuous_le_lintegral_le (f : α → ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) := begin obtain ⟨fs, fs_le_f, int_fs⟩ : ∃ (fs : α →ₛ ℝ≥0), (∀ x, fs x ≤ f x) ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε/2) := begin have := ennreal.lt_add_right int_f (ennreal.half_pos ε0).ne', conv_rhs at this { rw lintegral_eq_nnreal (λ x, (f x : ℝ≥0∞)) μ }, erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩], simp only [lt_supr_iff] at this, rcases this with ⟨fs, fs_le_f, int_fs⟩, refine ⟨fs, λ x, by simpa only [ennreal.coe_le_coe] using fs_le_f x, _⟩, convert int_fs.le, rw ← simple_func.lintegral_eq_lintegral, refl end, have int_fs_lt_top : ∫⁻ x, fs x ∂μ ≠ ∞, { apply ne_top_of_le_ne_top int_f (lintegral_mono (λ x, _)), simpa only [ennreal.coe_le_coe] using fs_le_f x }, obtain ⟨g, g_le_fs, gcont, gint⟩ : ∃ g : α → ℝ≥0, (∀ x, g x ≤ fs x) ∧ upper_semicontinuous g ∧ (∫⁻ x, fs x ∂μ ≤ ∫⁻ x, g x ∂μ + ε/2) := fs.exists_upper_semicontinuous_le_lintegral_le int_fs_lt_top (ennreal.half_pos ε0).ne', refine ⟨g, λ x, (g_le_fs x).trans (fs_le_f x), gcont, _⟩, calc ∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε / 2 : int_fs ... ≤ (∫⁻ x, g x ∂μ + ε / 2) + ε / 2 : add_le_add gint (le_refl _) ... = ∫⁻ x, g x ∂μ + ε : by rw [add_assoc, ennreal.add_halves] end /-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of `integral`. Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/ lemma exists_upper_semicontinuous_le_integral_le (f : α → ℝ≥0) (fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (integrable (λ x, (g x : ℝ)) μ) ∧ (∫ x, (f x : ℝ) ∂μ - ε ≤ ∫ x, g x ∂μ) := begin lift ε to ℝ≥0 using εpos.le, rw [nnreal.coe_pos, ← ennreal.coe_pos] at εpos, have If : ∫⁻ x, f x ∂ μ < ∞ := has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral, rcases exists_upper_semicontinuous_le_lintegral_le f If.ne εpos.ne' with ⟨g, gf, gcont, gint⟩, have Ig : ∫⁻ x, g x ∂ μ < ∞, { apply lt_of_le_of_lt (lintegral_mono (λ x, _)) If, simpa using gf x }, refine ⟨g, gf, gcont, _, _⟩, { refine integrable.mono fint gcont.measurable.coe_nnreal_real.ae_measurable _, exact filter.eventually_of_forall (λ x, by simp [gf x]) }, { rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae], { rw sub_le_iff_le_add, convert ennreal.to_real_mono _ gint, { simp, }, { rw ennreal.to_real_add Ig.ne ennreal.coe_ne_top, simp }, { simpa using Ig.ne } }, { apply filter.eventually_of_forall, simp }, { exact gcont.measurable.coe_nnreal_real.ae_measurable }, { apply filter.eventually_of_forall, simp }, { exact fint.ae_measurable } } end /-! ### Vitali-Carathéodory theorem -/ /-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an integrable function `g > f` which is lower semicontinuous, with integral arbitrarily close to that of `f`. This function has to be `ereal`-valued in general. -/ lemma exists_lt_lower_semicontinuous_integral_lt [sigma_finite μ] (f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ereal, (∀ x, (f x : ereal) < g x) ∧ lower_semicontinuous g ∧ (integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂ μ, g x < ⊤) ∧ (∫ x, ereal.to_real (g x) ∂μ < ∫ x, f x ∂μ + ε) := begin let δ : ℝ≥0 := ⟨ε/2, (half_pos εpos).le⟩, have δpos : 0 < δ := half_pos εpos, let fp : α → ℝ≥0 := λ x, real.to_nnreal (f x), have int_fp : integrable (λ x, (fp x : ℝ)) μ := hf.real_to_nnreal, rcases exists_lt_lower_semicontinuous_integral_gt_nnreal fp int_fp δpos with ⟨gp, fp_lt_gp, gpcont, gp_lt_top, gp_integrable, gpint⟩, let fm : α → ℝ≥0 := λ x, real.to_nnreal (-f x), have int_fm : integrable (λ x, (fm x : ℝ)) μ := hf.neg.real_to_nnreal, rcases exists_upper_semicontinuous_le_integral_le fm int_fm δpos with ⟨gm, gm_le_fm, gmcont, gm_integrable, gmint⟩, let g : α → ereal := λ x, (gp x : ereal) - (gm x), have ae_g : ∀ᵐ x ∂ μ, (g x).to_real = (gp x : ereal).to_real - (gm x : ereal).to_real, { filter_upwards [gp_lt_top], assume x hx, rw ereal.to_real_sub; simp [hx.ne] }, refine ⟨g, _, _, _, _, _⟩, show integrable (λ x, ereal.to_real (g x)) μ, { rw integrable_congr ae_g, convert gp_integrable.sub gm_integrable, ext x, simp }, show ∫ (x : α), (g x).to_real ∂μ < ∫ (x : α), f x ∂μ + ε, from calc ∫ (x : α), (g x).to_real ∂μ = ∫ (x : α), ereal.to_real (gp x) - ereal.to_real (gm x) ∂μ : integral_congr_ae ae_g ... = ∫ (x : α), ereal.to_real (gp x) ∂ μ - ∫ (x : α), gm x ∂μ : begin simp only [ereal.to_real_coe_ennreal, ennreal.coe_to_real, coe_coe], exact integral_sub gp_integrable gm_integrable, end ... < ∫ (x : α), ↑(fp x) ∂μ + ↑δ - ∫ (x : α), gm x ∂μ : begin apply sub_lt_sub_right, convert gpint, simp only [ereal.to_real_coe_ennreal], end ... ≤ ∫ (x : α), ↑(fp x) ∂μ + ↑δ - (∫ (x : α), fm x ∂μ - δ) : sub_le_sub_left gmint _ ... = ∫ (x : α), f x ∂μ + 2 * δ : by { simp_rw [integral_eq_integral_pos_part_sub_integral_neg_part hf, fp, fm], ring } ... = ∫ (x : α), f x ∂μ + ε : by { congr' 1, field_simp [δ, mul_comm] }, show ∀ᵐ (x : α) ∂μ, g x < ⊤, { filter_upwards [gp_lt_top], assume x hx, simp [g, ereal.sub_eq_add_neg, lt_top_iff_ne_top, lt_top_iff_ne_top.1 hx] }, show ∀ x, (f x : ereal) < g x, { assume x, rw ereal.coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (f x), refine ereal.sub_lt_sub_of_lt_of_le _ _ _ _, { simp only [ereal.coe_ennreal_lt_coe_ennreal_iff, coe_coe], exact (fp_lt_gp x) }, { simp only [ennreal.coe_le_coe, ereal.coe_ennreal_le_coe_ennreal_iff, coe_coe], exact (gm_le_fm x) }, { simp only [ereal.coe_ennreal_ne_bot, ne.def, not_false_iff, coe_coe] }, { simp only [ereal.coe_nnreal_ne_top, ne.def, not_false_iff, coe_coe] } }, show lower_semicontinuous g, { apply lower_semicontinuous.add', { exact continuous_coe_ennreal_ereal.comp_lower_semicontinuous gpcont (λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy) }, { apply ereal.continuous_neg.comp_upper_semicontinuous_antitone _ (λ x y hxy, ereal.neg_le_neg_iff.2 hxy), dsimp, apply continuous_coe_ennreal_ereal.comp_upper_semicontinuous _ (λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy), exact ennreal.continuous_coe.comp_upper_semicontinuous gmcont (λ x y hxy, ennreal.coe_le_coe.2 hxy) }, { assume x, exact ereal.continuous_at_add (by simp) (by simp) } } end /-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an integrable function `g < f` which is upper semicontinuous, with integral arbitrarily close to that of `f`. This function has to be `ereal`-valued in general. -/ lemma exists_upper_semicontinuous_lt_integral_gt [sigma_finite μ] (f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) : ∃ g : α → ereal, (∀ x, (g x : ereal) < f x) ∧ upper_semicontinuous g ∧ (integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂μ, ⊥ < g x) ∧ (∫ x, f x ∂μ < ∫ x, ereal.to_real (g x) ∂μ + ε) := begin rcases exists_lt_lower_semicontinuous_integral_lt (λ x, - f x) hf.neg εpos with ⟨g, g_lt_f, gcont, g_integrable, g_lt_top, gint⟩, refine ⟨λ x, - g x, _, _, _, _, _⟩, { exact λ x, ereal.neg_lt_iff_neg_lt.1 (by simpa only [ereal.coe_neg] using g_lt_f x) }, { exact ereal.continuous_neg.comp_lower_semicontinuous_antitone gcont (λ x y hxy, ereal.neg_le_neg_iff.2 hxy) }, { convert g_integrable.neg, ext x, simp }, { simpa [bot_lt_iff_ne_bot, lt_top_iff_ne_top] using g_lt_top }, { simp_rw [integral_neg, lt_neg_add_iff_add_lt] at gint, rw add_comm at gint, simpa [integral_neg] using gint } end end measure_theory
af80676e8bce34dba03f127ed947d1cffdd551ae
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/analysis/special_functions/trigonometric.lean
6178b4b64cbbc1f0423a53bf3e3d0845c1623a94
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,903
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 -/ import analysis.special_functions.exp_log /-! # 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. ## Tags log, sin, cos, tan, arcsin, arccos, arctan, angle, argument -/ noncomputable theory open_locale classical 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 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 /-- 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 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_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh 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 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 /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh 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 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 end complex section /-! Register lemmas for the derivatives of the composition of `complex.cos`, `complex.sin`, `complex.cosh` and `complex.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! `complex.cos`-/ 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 differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_deriv_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_deriv_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 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 namespace real variables {x y z : ℝ} lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) 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 has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) 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_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 has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) 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 has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) 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 end real section /-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`, `real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! `real.cos`-/ 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 differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_deriv_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_deriv_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 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 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 differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_deriv_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_deriv_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 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 namespace real lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨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_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_neg_pi_div_two_lt_of_lt_pi_div_two {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_neg_pi_div_two_le_of_le_pi_div_two {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_neg_pi_div_two_lt_of_lt_pi_div_two 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_neg_pi_div_two_lt_of_lt_pi_div_two (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_neg_pi_div_two_le_of_le_pi_div_two (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 (cos x), ← 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⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end 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 _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end 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]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (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₁ hx hy₁ 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_neg_pi_div_two_lt_of_lt_pi_div_two (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) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (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₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (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) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (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₁ hx₂ hy₁ 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₁ hx₂ hy₁ 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₁ hy₂ hx₁ 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_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.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 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 _ _ _).symm, -sub_eq_add_neg]; congr; 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 /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (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'⟩ instance angle.is_add_group_hom : @is_add_group_hom ℝ angle _ _ (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[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] lemma coe_smul (x : ℝ) (n : ℕ) : ↑(add_monoid.smul n x : ℝ) = add_monoid.smul n (↑x : angle) := add_monoid_hom.map_smul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; 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, gmultiples, set.mem_range, 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, ← gsmul_eq_mul, coe_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, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { 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_left_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, dsimp only 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 _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (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_neg_pi_div_two_le_of_le_pi_div_two (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 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_neg_pi_div_two_lt_of_lt_pi_div_two (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) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (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 hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (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 hy₁) (neg_nonneg.2 hx0) (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 hx₂ hy0 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₁ hx₂ hy₁ 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₁ hy₂ hx₁ 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_eq_inv, ← 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₁), ← domain.mul_left_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 tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, 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_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 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 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_pos.2 hx))) 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, euclidean_domain.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_neg_pi_div_two_le_of_le_pi_div_two 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 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 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] end complex
7edac558076d4406a097eafbabb6bc6baea9a7ca
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/ParserCompiler.lean
492bd24bc45d8382edc2f188b27c3a646ad6c15b
[ "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
7,749
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Meta.ReduceEval import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.Parser.Extension /-! Gadgets for compiling parser declarations into other programs, such as pretty printers. -/ namespace Lean namespace ParserCompiler structure Context (α : Type) where varName : Name categoryAttr : KeyedDeclsAttribute α combinatorAttr : CombinatorAttribute def Context.tyName {α} (ctx : Context α) : Name := ctx.categoryAttr.defn.valueTypeName /-- Replace all references of `Parser` with `tyName` -/ def replaceParserTy {α} (ctx : Context α) (e : Expr) : Expr := e.replace fun e => -- strip `optParam` let e := if e.isOptParam then e.appFn!.appArg! else e if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none open Meta Parser in /-- Takes an expression of type `Parser`, and determines the syntax kind of the root node it produces. -/ partial def parserNodeKind? (e : Expr) : MetaM (Option Name) := do let reduceEval? e : MetaM (Option Name) := do try pure <| some (← reduceEval e) catch _ => pure none let e ← whnfCore e if e matches Expr.lam .. then lambdaLetTelescope e fun _ e => parserNodeKind? e else if e.isAppOfArity ``leadingNode 3 || e.isAppOfArity ``trailingNode 4 || e.isAppOfArity ``node 2 then reduceEval? (e.getArg! 0) else if e.isAppOfArity ``withAntiquot 2 then parserNodeKind? (e.getArg! 1) else forallTelescope (← inferType e.getAppFn) fun params _ => do let lctx ← getLCtx -- if there is exactly one parameter of type `Parser`, search there if let [(i, _)] := params.toList.enum.filter (lctx.getFVar! ·.2 |>.type.isConstOf ``Parser) then parserNodeKind? (e.getArg! i) else return none section open Meta variable {α} (ctx : Context α) (builtin : Bool) (force : Bool) in /-- Translate an expression of type `Parser` into one of type `tyName`, tagging intermediary constants with `ctx.combinatorAttr`. If `force` is `false`, refuse to do so for imported constants. -/ partial def compileParserExpr (e : Expr) : MetaM Expr := do let e ← whnfCore e match e with | .lam .. => lambdaLetTelescope e fun xs b => compileParserExpr b >>= mkLambdaFVars xs | .fvar .. => return e | _ => do let fn := e.getAppFn let .const c .. := fn | throwError "call of unknown parser at '{e}'" -- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments -- of type `ty` (i.e. formerly `Parser`) let mkCall (p : Name) := do let ty ← inferType (mkConst p) forallTelescope ty fun params _ => do let mut p := mkConst p let args := e.getAppArgs for i in [:Nat.min params.size args.size] do let param := params[i]! let arg := args[i]! let paramTy ← inferType param let resultTy ← forallTelescope paramTy fun _ b => pure b let arg ← if resultTy.isConstOf ctx.tyName then compileParserExpr arg else pure arg p := mkApp p arg return p let env ← getEnv match ctx.combinatorAttr.getDeclFor? env c with | some p => mkCall p | none => let c' := c ++ ctx.varName let cinfo ← getConstInfo c let resultTy ← forallTelescope cinfo.type fun _ b => pure b if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do -- synthesize a new `[combinatorAttr c]` let some value ← pure cinfo.value? | throwError "don't know how to generate {ctx.varName} for non-definition '{e}'" unless (env.getModuleIdxFor? c).isNone || force do throwError "refusing to generate code for imported parser declaration '{c}'; use `@[run_parser_attribute_hooks]` on its definition instead." let value ← compileParserExpr <| replaceParserTy ctx value let ty ← forallTelescope cinfo.type fun params _ => params.foldrM (init := mkConst ctx.tyName) fun param ty => do let paramTy ← replaceParserTy ctx <$> inferType param return mkForall `_ BinderInfo.default paramTy ty let decl := Declaration.defnDecl { name := c', levelParams := [] type := ty, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } let env ← getEnv let env ← match env.addAndCompile {} decl with | Except.ok env => pure env | Except.error kex => do throwError (← (kex.toMessageData {}).toString) setEnv <| ctx.combinatorAttr.setDeclFor env c c' if cinfo.type.isConst then if let some kind ← parserNodeKind? cinfo.value! then -- If the parser is parameter-less and produces a node of kind `kind`, -- then tag the compiled definition as `[(builtin)Parenthesizer kind]` -- (or `[(builtin)Formatter kind]`, resp.) let attrName := if builtin then ctx.categoryAttr.defn.builtinName else ctx.categoryAttr.defn.name -- Create syntax node for a simple attribute of the form -- `def simple := leading_parser ident >> optional (ident <|> priorityParser)` let stx := mkNode `Lean.Parser.Attr.simple #[mkIdent attrName, mkNullNode #[mkIdent kind]] Attribute.add c' attrName stx mkCall c' else -- if this is a generic function, e.g. `AndThen.andthen`, it's easier to just unfold it until we are -- back to parser combinators let some e' ← unfoldDefinition? e | throwError "don't know how to generate {ctx.varName} for non-parser combinator '{e}'" compileParserExpr e' end variable {α} (ctx : Context α) (builtin : Bool) in def compileEmbeddedParsers : ParserDescr → MetaM Unit | ParserDescr.const _ => pure () | ParserDescr.unary _ d => compileEmbeddedParsers d | ParserDescr.binary _ d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂ | ParserDescr.parser constName => discard <| compileParserExpr ctx (mkConst constName) (builtin := builtin) (force := false) | ParserDescr.node _ _ d => compileEmbeddedParsers d | ParserDescr.nodeWithAntiquot _ _ d => compileEmbeddedParsers d | ParserDescr.sepBy p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.sepBy1 p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.trailingNode _ _ _ d => compileEmbeddedParsers d | ParserDescr.symbol _ => pure () | ParserDescr.nonReservedSymbol _ _ => pure () | ParserDescr.cat _ _ => pure () /-- Precondition: `α` must match `ctx.tyName`. -/ unsafe def registerParserCompiler {α} (ctx : Context α) : IO Unit := do Parser.registerParserAttributeHook { postAdd := fun catName constName builtin => do let info ← getConstInfo constName if info.type.isConstOf `Lean.ParserDescr || info.type.isConstOf `Lean.TrailingParserDescr then let d ← evalConstCheck ParserDescr `Lean.ParserDescr constName <|> evalConstCheck TrailingParserDescr `Lean.TrailingParserDescr constName compileEmbeddedParsers ctx d (builtin := builtin) |>.run' else -- `[run_builtin_parser_attribute_hooks]` => force compilation even if imported, do not apply `ctx.categoryAttr`. let force := catName.isAnonymous discard (compileParserExpr ctx (mkConst constName) (builtin := builtin) (force := force)).run' } end ParserCompiler end Lean
621a0f193db83b47163a8469866c34f9253f3842
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/subgroup/basic.lean
e8ca3cddd747b203d90b4294f4214ca35d8e37cd
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
98,211
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid.pointwise import group_theory.submonoid.membership import group_theory.submonoid.center import algebra.group.conj import order.atoms /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` * `is_simple_group G` : a class indicating that a group has exactly two normal subgroups ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators pointwise variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid namespace subgroup @[to_additive] instance : set_like (subgroup G) G := ⟨subgroup.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp, to_additive] lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma mem_mk {s : set G} {x : G} (h_one) (h_mul) (h_inv) : x ∈ mk s h_one h_mul h_inv ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_set_mk {s : set G} (h_one) (h_mul) (h_inv) : (mk s h_one h_mul h_inv : set G) = s := rfl @[simp, to_additive] lemma mk_le_mk {s t : set G} (h_one) (h_mul) (h_inv) (h_one') (h_mul') (h_inv') : mk s h_one h_mul h_inv ≤ mk t h_one' h_mul' h_inv' ↔ s ⊆ t := iff.rfl /-- See Note [custom simps projection] -/ @[to_additive "See Note [custom simps projection]"] def simps.coe (S : subgroup G) : set G := S initialize_simps_projections subgroup (carrier → coe) initialize_simps_projections add_subgroup (carrier → coe) @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[simp, to_additive] lemma mem_to_submonoid (K : subgroup G) (x : G) : x ∈ K.to_submonoid ↔ x ∈ K := iff.rfl @[to_additive] instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K := show fintype {g : G // g ∈ K}, from infer_instance @[to_additive] theorem to_submonoid_injective : function.injective (to_submonoid : subgroup G → submonoid G) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp, to_additive] theorem to_submonoid_eq {p q : subgroup G} : p.to_submonoid = q.to_submonoid ↔ p = q := to_submonoid_injective.eq_iff @[to_additive, mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subgroup G → submonoid G) := λ _ _, id attribute [mono] add_subgroup.to_add_submonoid_strict_mono @[to_additive, mono] lemma to_submonoid_mono : monotone (to_submonoid : subgroup G → submonoid G) := to_submonoid_strict_mono.monotone attribute [mono] add_subgroup.to_add_submonoid_mono @[simp, to_additive] lemma to_submonoid_le {p q : subgroup G} : p.to_submonoid ≤ q.to_submonoid ↔ p ≤ q := iff.rfl end subgroup /-! ### Conversion to/from `additive`/`multiplicative` -/ section mul_add /-- Supgroups of a group `G` are isomorphic to additive subgroups of `additive G`. -/ @[simps] def subgroup.to_add_subgroup : subgroup G ≃o add_subgroup (additive G) := { to_fun := λ S, { neg_mem' := S.inv_mem', ..S.to_submonoid.to_add_submonoid }, inv_fun := λ S, { inv_mem' := S.neg_mem', ..S.to_add_submonoid.to_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subgroup of an additive group `additive G` are isomorphic to subgroup of `G`. -/ abbreviation add_subgroup.to_subgroup' : add_subgroup (additive G) ≃o subgroup G := subgroup.to_add_subgroup.symm /-- Additive supgroups of an additive group `A` are isomorphic to subgroups of `multiplicative A`. -/ @[simps] def add_subgroup.to_subgroup : add_subgroup A ≃o subgroup (multiplicative A) := { to_fun := λ S, { inv_mem' := S.neg_mem', ..S.to_add_submonoid.to_submonoid }, inv_fun := λ S, { neg_mem' := S.inv_mem', ..S.to_submonoid.to_add_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subgroups of an additive group `multiplicative A` are isomorphic to additive subgroups of `A`. -/ abbreviation subgroup.to_add_subgroup' : subgroup (multiplicative A) ≃o add_subgroup A := add_subgroup.to_subgroup.symm end mul_add namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } @[simp, to_additive] lemma coe_copy (K : subgroup G) (s : set G) (hs : s = ↑K) : (K.copy s hs : set G) = s := rfl @[to_additive] lemma copy_eq (K : subgroup G) (s : set G) (hs : s = ↑K) : K.copy s hs = K := set_like.coe_injective hs /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := set_like.ext h /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H := by rw [← H.inv_mem_iff, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev, inv_inv] @[simp, to_additive] theorem inv_coe_set : (H : set G)⁻¹ = H := by { ext, simp, } @[simp, to_additive] lemma exists_inv_mem_iff_exists_mem (K : subgroup G) {P : G → Prop} : (∃ (x : G), x ∈ K ∧ P x⁻¹) ↔ ∃ x ∈ K, P x := by split; { rintros ⟨x, x_in, hx⟩, exact ⟨x⁻¹, inv_mem K x_in, by simp [hx]⟩ } @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h @[to_additive add_subgroup.nsmul_mem] lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx @[to_additive] lemma zpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (n : ℕ) := by { rw [zpow_coe_nat], exact pow_mem _ hx n } | -[1+ n] := by { rw [zpow_neg_succ_of_nat], exact K.inv_mem (K.pow_mem hx n.succ) } /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_div (x y : H) : (↑(x / y) : G) = ↑x / ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_ordered_comm_group` is an `add_ordered_comm_group`."] instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] (H : subgroup G) : ordered_comm_group H := subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`."] instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G] (H : subgroup G) : linear_ordered_comm_group H := subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast, to_additive coe_smul] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast, to_additive] lemma coe_zpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_zpow _ _ _ /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, coe_mk, monoid_hom.mk'_apply] } @[simp, to_additive] lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) : K.subtype.comp (inclusion hH) = H.subtype := by { ext, simp } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] instance : unique (⊥ : subgroup G) := ⟨⟨1⟩, λ g, subtype.ext g.2⟩ @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin rw set_like.ext'_iff, simp only [coe_bot, set.eq_singleton_iff_unique_mem, set_like.mem_coe, H.one_mem, true_and], end @[to_additive] lemma eq_bot_of_subsingleton [subsingleton H] : H = ⊥ := begin rw subgroup.eq_bot_iff_forall, intros y hy, rw [← subgroup.coe_mk H y hy, subsingleton.elim (⟨y, hy⟩ : H) 1, subgroup.coe_one], end @[to_additive] lemma coe_eq_univ {H : subgroup G} : (H : set G) = set.univ ↔ H = ⊤ := (set_like.ext'_iff.trans (by refl)).symm @[to_additive] lemma coe_eq_singleton {H : subgroup G} : (∃ g : G, (H : set G) = {g}) ↔ H = ⊥ := ⟨λ ⟨g, hg⟩, by { haveI : subsingleton (H : set G) := by { rw hg, apply_instance }, exact H.eq_bot_of_subsingleton }, λ h, ⟨1, set_like.ext'_iff.mp h⟩⟩ @[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1}, by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩ /- curly brackets `{}` are used here instead of instance brackets `[]` because the instance in a goal is often not the same as the one inferred by type class inference. -/ @[simp, to_additive] lemma card_bot {_ : fintype ↥(⊥ : subgroup G)} : fintype.card (⊥ : subgroup G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩ @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin haveI : fintype (H : set G) := ‹fintype H›, rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj, ← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card], congr end @[to_additive] lemma eq_top_of_le_card [fintype H] [fintype G] (h : fintype.card G ≤ fintype.card H) : H = ⊤ := eq_top_of_card_eq H (le_antisymm (fintype.card_le_of_injective coe subtype.coe_injective) h) @[to_additive] lemma eq_bot_of_card_le [fintype H] (h : fintype.card H ≤ 1) : H = ⊥ := let _ := fintype.card_le_one_iff_subsingleton.mp h in by exactI eq_bot_of_subsingleton H @[to_additive] lemma eq_bot_of_card_eq [fintype H] (h : fintype.card H = 1) : H = ⊥ := H.eq_bot_of_card_le (le_of_eq h) @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := subtype.nontrivial_iff_exists_ne (λ x, x ∈ H) (1 : H) /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, simp only [not_forall] at h, simpa only [nontrivial_iff_exists_ne_one] } end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end @[to_additive] lemma card_le_one_iff_eq_bot [fintype H] : fintype.card H ≤ 1 ↔ H = ⊥ := ⟨λ h, (eq_bot_iff_forall _).2 (λ x hx, by simpa [subtype.ext_iff] using fintype.card_le_one_iff.1 h ⟨x, hx⟩ 1), λ h, by simp [h]⟩ @[to_additive] lemma one_lt_card_iff_ne_bot [fintype H] : 1 < fintype.card H ↔ H ≠ ⊥ := lt_iff_not_ge'.trans (not_iff_not.mpr H.card_le_one_iff_eq_bot) /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, norm_cast, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, norm_cast, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from set_like.coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mul_mem_sup {S T : subgroup G} {x y : G} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := (S ⊔ T).mul_mem (mem_sup_left hx) (mem_sup_right hy) @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[simp, to_additive] lemma subsingleton_iff : subsingleton (subgroup G) ↔ subsingleton G := ⟨ λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩, λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩⟩ @[simp, to_additive] lemma nontrivial_iff : nontrivial (subgroup G) ↔ nontrivial G := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : unique (subgroup G) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mpr ‹_› @[to_additive] lemma eq_top_iff' : H = ⊤ ↔ ∀ x : G, x ∈ H := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx @[to_additive] lemma not_mem_of_not_mem_closure {P : G} (hP : P ∉ closure k) : P ∉ k := λ h, hP (subset_closure h) open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and inverses, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[elab_as_eliminator, to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ @[to_additive /-"The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element."-/] lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ zpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, zpow_one x⟩ }, { exact ⟨0, zpow_zero x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, zpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, zpow_neg x n⟩ end @[to_additive] lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[simp, to_additive] lemma inv_subset_closure (S : set G) : S⁻¹ ⊆ closure S := begin intros s hs, rw [set_like.mem_coe, ←subgroup.inv_mem_iff], exact subset_closure (mem_inv.mp hs), end @[simp, to_additive] lemma closure_inv (S : set G) : closure S⁻¹ = closure S := begin refine le_antisymm ((subgroup.closure_le _).2 _) ((subgroup.closure_le _).2 _), { exact inv_subset_closure S }, { simpa only [set.inv_inv] using inv_subset_closure S⁻¹ }, end @[to_additive] lemma closure_to_submonoid (S : set G) : (closure S).to_submonoid = submonoid.closure (S ∪ S⁻¹) := begin refine le_antisymm _ (submonoid.closure_le.2 _), { intros x hx, refine closure_induction hx (λ x hx, submonoid.closure_mono (subset_union_left S S⁻¹) (submonoid.subset_closure hx)) (submonoid.one_mem _) (λ x y hx hy, submonoid.mul_mem _ hx hy) (λ x hx, _), rwa [←submonoid.mem_closure_inv, set.union_inv, set.inv_inv, set.union_comm] }, { simp only [true_and, coe_to_submonoid, union_subset_iff, subset_closure, inv_subset_closure] } end /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k` and their inverse, and is preserved under multiplication, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k` and their negation, and is preserved under addition, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction'' {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (Hk_inv : ∀ x ∈ k, p x⁻¹) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := begin rw [← mem_to_submonoid, closure_to_submonoid k] at h, refine submonoid.closure_induction h (λ x hx, _) H1 (λ x y hx hy, Hmul x y hx hy), { rw [mem_union, mem_inv] at hx, cases hx with mem invmem, { exact Hk x mem }, { rw [← inv_inv x], exact Hk_inv _ invmem } }, end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_mono {f : G →* N} {K K' : subgroup N} : K ≤ K' → comap f K ≤ comap f K' := preimage_mono @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : G →* N) {K : subgroup G} {x : G} (hx : x ∈ K) : f x ∈ K.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : G →* N) (K : subgroup G) (x : K) : f x ∈ K.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_mono {f : G →* N} {K K' : subgroup G} : K ≤ K' → map f K ≤ map f K' := image_subset _ @[simp, to_additive] lemma map_id : K.map (monoid_hom.id G) = K := set_like.coe_injective $ image_id _ @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma mem_map_equiv {f : G ≃* N} {K : subgroup G} {x : N} : x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma mem_map_iff_mem {f : G →* N} (hf : function.injective f) {K : subgroup G} {x : G} : f x ∈ K.map f ↔ x ∈ K := hf.mem_set_image @[to_additive] lemma map_equiv_eq_comap_symm (f : G ≃* N) (K : subgroup G) : K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* G) (K : subgroup G) : K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom := (map_equiv_eq_comap_symm f.symm K).symm @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_sup_comap_le (H K : subgroup N) (f : G →* N) : comap f H ⊔ comap f K ≤ comap f (H ⊔ K) := monotone.le_map_sup (λ _ _, comap_mono) H K @[to_additive] lemma supr_comap_le {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (⨆ i, (s i).comap f) ≤ (supr s).comap f := monotone.le_map_supr (λ _ _, comap_mono) @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[to_additive] lemma map_inf_le (H K : subgroup G) (f : G →* N) : map f (H ⊓ K) ≤ map f H ⊓ map f K := le_inf (map_mono inf_le_left) (map_mono inf_le_right) @[to_additive] lemma map_inf_eq (H K : subgroup G) (f : G →* N) (hf : function.injective f) : map f (H ⊓ K) = map f H ⊓ map f K := begin rw ← set_like.coe_set_eq, simp [set.image_inter hf], end @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K := ext $ λ x, and_iff_right_of_imp (λ _, x.prop) @[simp, to_additive] lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H := ext $ λ x, and_iff_left_of_imp (λ _, x.prop) /-- If `H ≤ K`, then `H` as a subgroup of `K` is isomorphic to `H`. -/ @[to_additive "If `H ≤ K`, then `H` as a subgroup of `K` is isomorphic to `H`.", simps] def comap_subtype_equiv_of_le {G : Type*} [group G] {H K : subgroup G} (h : H ≤ K) : H.comap K.subtype ≃* H := { to_fun := λ g, ⟨g.1, g.2⟩, inv_fun := λ g, ⟨⟨g.1, h g.2⟩, g.2⟩, left_inv := λ g, subtype.ext (subtype.ext rfl), right_inv := λ g, subtype.ext rfl, map_mul' := λ g h, rfl } /-- For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`. -/ @[to_additive "For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`."] def subgroup_of (H K : subgroup G) : subgroup K := H.comap K.subtype @[to_additive] lemma coe_subgroup_of (H K : subgroup G) : (H.subgroup_of K : set K) = K.subtype ⁻¹' H := rfl @[to_additive] lemma mem_subgroup_of {H K : subgroup G} {h : K} : h ∈ H.subgroup_of K ↔ (h : G) ∈ H := iff.rfl @[to_additive] lemma subgroup_of_map_subtype (H K : subgroup G) : (H.subgroup_of K).map K.subtype = H ⊓ K := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp only [subtype.range_coe_subtype, coe_subtype, coe_inf], refl, end @[simp, to_additive] lemma bot_subgroup_of : (⊥ : subgroup G).subgroup_of H = ⊥ := eq.symm (subgroup.ext (λ g, subtype.ext_iff)) @[simp, to_additive] lemma top_subgroup_of : (⊤ : subgroup G).subgroup_of H = ⊤ := rfl @[to_additive] lemma subgroup_of_bot_eq_bot : H.subgroup_of ⊥ = ⊥ := subsingleton.elim _ _ @[to_additive] lemma subgroup_of_bot_eq_top : H.subgroup_of ⊥ = ⊤ := subsingleton.elim _ _ @[simp, to_additive] lemma subgroup_of_self : H.subgroup_of H = ⊤ := top_le_iff.mp (λ g hg, g.2) /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal variables (H) /-- A subgroup is characteristic if it is fixed by all automorphisms. Several equivalent conditions are provided by lemmas of the form `characteristic.iff...` -/ structure characteristic : Prop := (fixed : ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom = H) attribute [class] characteristic @[priority 100] instance normal_of_characteristic [h : H.characteristic] : H.normal := ⟨λ a ha b, (set_like.ext_iff.mp (h.fixed (mul_aut.conj b)) a).mpr ha⟩ end subgroup namespace add_subgroup variables (H : add_subgroup A) /-- A add_subgroup is characteristic if it is fixed by all automorphisms. Several equivalent conditions are provided by lemmas of the form `characteristic.iff...` -/ structure characteristic : Prop := (fixed : ∀ ϕ : A ≃+ A, H.comap ϕ.to_add_monoid_hom = H) attribute [to_additive add_subgroup.characteristic] subgroup.characteristic attribute [class] characteristic @[priority 100] instance normal_of_characteristic [h : H.characteristic] : H.normal := ⟨λ a ha b, (set_like.ext_iff.mp (h.fixed (add_aut.conj b)) a).mpr ha⟩ end add_subgroup namespace subgroup variables {H K : subgroup G} @[to_additive] lemma characteristic_iff_comap_eq : H.characteristic ↔ ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom = H := ⟨characteristic.fixed, characteristic.mk⟩ @[to_additive] lemma characteristic_iff_comap_le : H.characteristic ↔ ∀ ϕ : G ≃* G, H.comap ϕ.to_monoid_hom ≤ H := characteristic_iff_comap_eq.trans ⟨λ h ϕ, le_of_eq (h ϕ), λ h ϕ, le_antisymm (h ϕ) (λ g hg, h ϕ.symm ((congr_arg (∈ H) (ϕ.symm_apply_apply g)).mpr hg))⟩ @[to_additive] lemma characteristic_iff_le_comap : H.characteristic ↔ ∀ ϕ : G ≃* G, H ≤ H.comap ϕ.to_monoid_hom := characteristic_iff_comap_eq.trans ⟨λ h ϕ, ge_of_eq (h ϕ), λ h ϕ, le_antisymm (λ g hg, (congr_arg (∈ H) (ϕ.symm_apply_apply g)).mp (h ϕ.symm hg)) (h ϕ)⟩ @[to_additive] lemma characteristic_iff_map_eq : H.characteristic ↔ ∀ ϕ : G ≃* G, H.map ϕ.to_monoid_hom = H := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_comap_eq.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] lemma characteristic_iff_map_le : H.characteristic ↔ ∀ ϕ : G ≃* G, H.map ϕ.to_monoid_hom ≤ H := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_comap_le.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] lemma characteristic_iff_le_map : H.characteristic ↔ ∀ ϕ : G ≃* G, H ≤ H.map ϕ.to_monoid_hom := begin simp_rw map_equiv_eq_comap_symm, exact characteristic_iff_le_comap.trans ⟨λ h ϕ, h ϕ.symm, λ h ϕ, h ϕ.symm⟩, end @[to_additive] instance bot_characteristic : characteristic (⊥ : subgroup G) := characteristic_iff_le_map.mpr (λ ϕ, bot_le) @[to_additive] instance top_characteristic : characteristic (⊤ : subgroup G) := characteristic_iff_map_le.mpr (λ ϕ, le_top) variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of an additive group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := set.center G, inv_mem' := λ a, set.inv_mem_center, .. submonoid.center G } @[to_additive] lemma coe_center : ↑(center G) = set.center G := rfl @[simp, to_additive] lemma center_to_submonoid : (center G).to_submonoid = submonoid.center G := rfl variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center [decidable_eq G] [fintype G] : decidable_pred (∈ center G) := λ _, decidable_of_iff' _ mem_center_iff @[to_additive] instance center_characteristic : (center G).characteristic := begin refine characteristic_iff_comap_le.mpr (λ ϕ g hg h, _), rw [←ϕ.injective.eq_iff, ϕ.map_mul, ϕ.map_mul], exact hg (ϕ h), end variables {G} (H) /-- The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } lemma mem_normalizer_fintype {S : set G} [fintype S] {x : G} (h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S := by haveI := classical.prop_decidable; haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩ variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ @[to_additive] lemma normalizer_eq_top : H.normalizer = ⊤ ↔ H.normal := eq_top_iff.trans ⟨λ h, ⟨λ a ha b, (h (mem_top b) a).mp ha⟩, λ h a ha b, ⟨λ hb, h.conj_mem b hb a, λ hb, by rwa [h.mem_comm_iff, inv_mul_cancel_left] at hb⟩⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ variables {N : Type*} [group N] /-- The preimage of the normalizer is contained in the normalizer of the preimage. -/ @[to_additive "The preimage of the normalizer is contained in the normalizer of the preimage."] lemma le_normalizer_comap (f : N →* G) : H.normalizer.comap f ≤ (H.comap f).normalizer := λ x, begin simp only [mem_normalizer_iff, mem_comap], assume h n, simp [h (f n)] end /-- The image of the normalizer is contained in the normalizer of the image. -/ @[to_additive "The image of the normalizer is contained in the normalizer of the image."] lemma le_normalizer_map (f : G →* N) : H.normalizer.map f ≤ (H.map f).normalizer := λ _, begin simp only [and_imp, exists_prop, mem_map, exists_imp_distrib, mem_normalizer_iff], rintros x hx rfl n, split, { rintros ⟨y, hy, rfl⟩, use [x * y * x⁻¹, (hx y).1 hy], simp }, { rintros ⟨y, hyH, hy⟩, use [x⁻¹ * y * x], rw [hx], simp [hy, hyH, mul_assoc] } end variable (H) /-- Commutivity of a subgroup -/ structure is_commutative : Prop := (is_comm : _root_.is_commutative H (*)) attribute [class] is_commutative /-- Commutivity of an additive subgroup -/ structure _root_.add_subgroup.is_commutative (H : add_subgroup A) : Prop := (is_comm : _root_.is_commutative H (+)) attribute [to_additive add_subgroup.is_commutative] subgroup.is_commutative attribute [class] add_subgroup.is_commutative /-- A commutative subgroup is commutative -/ @[to_additive] instance is_commutative.comm_group [h : H.is_commutative] : comm_group H := { mul_comm := h.is_comm.comm, .. H.to_group } instance center.is_commutative : (center G).is_commutative := ⟨⟨λ a b, subtype.ext (b.2 a)⟩⟩ end subgroup namespace group variables {s : set G} /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates_of a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj.refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates_of a ⊆ N := by { rintros a hc, obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, h₂.trans (is_conj_iff.2 ⟨c,rfl⟩)⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) (_ : normal N) (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) /-- The normal core of a subgroup `H` is the largest normal subgroup of `G` contained in `H`, as shown by `subgroup.normal_core_eq_supr`. -/ def normal_core (H : subgroup G) : subgroup G := { carrier := {a : G | ∀ b : G, b * a * b⁻¹ ∈ H}, one_mem' := λ a, by rw [mul_one, mul_inv_self]; exact H.one_mem, inv_mem' := λ a h b, (congr_arg (∈ H) conj_inv).mp (H.inv_mem (h b)), mul_mem' := λ a b ha hb c, (congr_arg (∈ H) conj_mul).mp (H.mul_mem (ha c) (hb c)) } lemma normal_core_le (H : subgroup G) : H.normal_core ≤ H := λ a h, by { rw [←mul_one a, ←one_inv, ←one_mul a], exact h 1 } instance normal_core_normal (H : subgroup G) : H.normal_core.normal := ⟨λ a h b c, by rw [mul_assoc, mul_assoc, ←mul_inv_rev, ←mul_assoc, ←mul_assoc]; exact h (c * b)⟩ lemma normal_le_normal_core {H : subgroup G} {N : subgroup G} [hN : N.normal] : N ≤ H.normal_core ↔ N ≤ H := ⟨ge_trans H.normal_core_le, λ h_le n hn g, h_le (hN.conj_mem n hn g)⟩ lemma normal_core_mono {H K : subgroup G} (h : H ≤ K) : H.normal_core ≤ K.normal_core := normal_le_normal_core.mpr (H.normal_core_le.trans h) lemma normal_core_eq_supr (H : subgroup G) : H.normal_core = ⨆ (N : subgroup G) (_ : normal N) (hs : N ≤ H), N := le_antisymm (le_supr_of_le H.normal_core (le_supr_of_le H.normal_core_normal (le_supr_of_le H.normal_core_le le_rfl))) (supr_le (λ N, supr_le (λ hN, supr_le (by exactI normal_le_normal_core.mpr)))) @[simp] lemma normal_core_eq_self (H : subgroup G) [H.normal] : H.normal_core = H := le_antisymm H.normal_core_le (normal_le_normal_core.mpr le_rfl) @[simp] theorem normal_core_idempotent (H : subgroup G) : H.normal_core.normal_core = H.normal_core := H.normal_core.normal_core_eq_self end subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def range_restrict (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[simp, to_additive] lemma coe_range_restrict (f : G →* N) (g : G) : (f.range_restrict g : N) = f g := rfl @[to_additive] lemma range_restrict_surjective (f : G →* N) : function.surjective f.range_restrict := λ ⟨_, g, rfl⟩, ⟨g, rfl⟩ @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf @[simp, to_additive] lemma _root_.subgroup.subtype_range (H : subgroup G) : H.subtype.range = H := by { rw [range_eq_map, ← set_like.coe_set_eq, coe_map, subgroup.coe_subtype], ext, simp } @[simp, to_additive] lemma _root_.subgroup.inclusion_range {H K : subgroup G} (h_le : H ≤ K) : (inclusion h_le).range = H.subgroup_of K := subgroup.ext (λ g, set.ext_iff.mp (set.range_inclusion h_le) g) /-- Restriction of a group hom to a subgroup of the domain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the domain."] def restrict (f : G →* N) (H : subgroup G) : H →* N := f.comp H.subtype @[simp, to_additive] lemma restrict_apply {H : subgroup G} (f : G →* N) (x : H) : f.restrict H x = f (x : G) := rfl /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } @[simp, to_additive] lemma cod_restrict_apply {G : Type*} [group G] {N : Type*} [group N] (f : G →* N) (S : subgroup N) (h : ∀ (x : G), f x ∈ S) {x : G} : f.cod_restrict S h x = ⟨f x, h x⟩ := rfl @[to_additive] lemma subgroup_of_range_eq_of_le {G₁ G₂ : Type*} [group G₁] [group G₂] {K : subgroup G₂} (f : G₁ →* G₂) (h : f.range ≤ K) : f.range.subgroup_of K = (f.cod_restrict K (λ x, h ⟨x, rfl⟩)).range := begin ext k, refine exists_congr _, simp [subtype.ext_iff], end /-- Computable alternative to `monoid_hom.of_injective`. -/ @[to_additive /-"Computable alternative to `add_monoid_hom.of_injective`."-/] def of_left_inverse {f : G →* N} {g : N →* G} (h : function.left_inverse g f) : G ≃* f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := by { rintros ⟨x, y, rfl⟩, apply subtype.ext, rw [coe_range_restrict, function.comp_apply, subgroup.coe_subtype, subtype.coe_mk, h] }, .. f.range_restrict } @[simp, to_additive] lemma of_left_inverse_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : G) : ↑(of_left_inverse h x) = f x := rfl @[simp, to_additive] lemma of_left_inverse_symm_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- The range of an injective group homomorphism is isomorphic to its domain. -/ @[to_additive /-"The range of an injective additive group homomorphism is isomorphic to its domain."-/ ] noncomputable def of_injective {f : G →* N} (hf : function.injective f) : G ≃* f.range := (mul_equiv.of_bijective (f.cod_restrict f.range (λ x, ⟨x, rfl⟩)) ⟨λ x y h, hf (subtype.ext_iff.mp h), by { rintros ⟨x, y, rfl⟩, exact ⟨y, rfl⟩ }⟩) @[to_additive] lemma of_injective_apply {f : G →* N} (hf : function.injective f) {x : G} : ↑(of_injective hf x) = f x := rfl section ker variables {M : Type*} [mul_one_class M] /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* M) : subgroup G := { inv_mem' := λ x (hx : f x = 1), calc f x⁻¹ = f x * f x⁻¹ : by rw [hx, one_mul] ... = f (x * x⁻¹) : by rw [f.map_mul] ... = f 1 : by rw [mul_right_inv] ... = 1 : f.map_one, ..f.mker } @[to_additive] lemma mem_ker (f : G →* M) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_ker (f : G →* M) : (f.ker : set G) = (f : G → M) ⁻¹' {1} := rfl @[to_additive] lemma eq_iff (f : G →* N) {x y : G} : f x = f y ↔ y⁻¹ * x ∈ f.ker := by rw [f.mem_ker, f.map_mul, f.map_inv, inv_mul_eq_one, eq_comm] @[to_additive] instance decidable_mem_ker [decidable_eq M] (f : G →* M) : decidable_pred (∈ f.ker) := λ x, decidable_of_iff (f x = 1) f.mem_ker @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[simp, to_additive] lemma comap_bot (f : G →* N) : (⊥ : subgroup N).comap f = f.ker := rfl @[to_additive] lemma range_restrict_ker (f : G →* N) : ker (range_restrict f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[simp, to_additive] lemma ker_one : (1 : G →* M).ker = ⊤ := by { ext, simp [mem_ker] } @[to_additive] lemma ker_eq_bot_iff (f : G →* N) : f.ker = ⊥ ↔ function.injective f := begin split, { intros h x y hxy, rwa [←mul_inv_eq_one, ←map_inv, ←map_mul, ←mem_ker, h, mem_bot, mul_inv_eq_one] at hxy }, { exact λ h, le_bot_iff.mp (λ x hx, h (hx.trans f.map_one.symm)) }, end @[simp, to_additive] lemma _root_.subgroup.ker_subtype (H : subgroup G) : H.subtype.ker = ⊥ := H.subtype.ker_eq_bot_iff.mpr subtype.coe_injective @[simp, to_additive] lemma _root_.subgroup.ker_inclusion {H K : subgroup G} (h : H ≤ K) : (inclusion h).ker = ⊥ := (inclusion h).ker_eq_bot_iff.mpr (set.inclusion_injective h) @[to_additive] lemma prod_map_comap_prod {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') (S : subgroup N) (S' : subgroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ @[to_additive] lemma ker_prod_map {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') : (prod_map f g).ker = f.ker.prod g.ker := by rw [←comap_bot, ←comap_bot, ←comap_bot, ←prod_map_comap_prod, bot_prod_bot] end ker /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [set_like.mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) -- this instance can't go just after the definition of `mrange` because `fintype` is -- not imported at that stage /-- The range of a finite monoid under a monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive monoid under an additive monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_mrange {M N : Type*} [monoid M] [monoid N] [fintype M] [decidable_eq N] (f : M →* N) : fintype (mrange f) := set.fintype_range f /-- The range of a finite group under a group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive group under an additive group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_range [fintype G] [decidable_eq N] (f : G →* N) : fintype (range f) := set.fintype_range f end monoid_hom namespace subgroup variables {N : Type*} [group N] (H : subgroup G) @[to_additive] lemma map_eq_bot_iff {f : G →* N} : H.map f = ⊥ ↔ H ≤ f.ker := begin rw eq_bot_iff, split, { exact λ h x hx, h ⟨x, hx, rfl⟩ }, { intros h x hx, obtain ⟨y, hy, rfl⟩ := hx, exact h hy }, end @[to_additive] lemma map_eq_bot_iff_of_injective {f : G →* N} (hf : function.injective f) : H.map f = ⊥ ↔ H = ⊥ := by rw [map_eq_bot_iff, f.ker_eq_bot_iff.mpr hf, le_bot_iff] end subgroup namespace subgroup open monoid_hom variables {N : Type*} [group N] (f : G →* N) @[to_additive] lemma map_le_range (H : subgroup G) : map f H ≤ f.range := (range_eq_map f).symm ▸ map_mono le_top @[to_additive] lemma map_subtype_le {H : subgroup G} (K : subgroup H) : K.map H.subtype ≤ H := (K.map_le_range H.subtype).trans (le_of_eq H.subtype_range) @[to_additive] lemma ker_le_comap (H : subgroup N) : f.ker ≤ comap f H := (comap_bot f) ▸ comap_mono bot_le @[to_additive] lemma map_comap_le (H : subgroup N) : map f (comap f H) ≤ H := (gc_map_comap f).l_u_le _ @[to_additive] lemma le_comap_map (H : subgroup G) : H ≤ comap f (map f H) := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_eq (H : subgroup N) : map f (comap f H) = f.range ⊓ H := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp [set.inter_comm], end @[to_additive] lemma comap_map_eq (H : subgroup G) : comap f (map f H) = H ⊔ f.ker := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (ker_le_comap _ _)), intros x hx, simp only [exists_prop, mem_map, mem_comap] at hx, rcases hx with ⟨y, hy, hy'⟩, rw ← mul_inv_cancel_left y x, exact mul_mem_sup hy (by simp [mem_ker, hy']), end @[to_additive] lemma map_comap_eq_self {f : G →* N} {H : subgroup N} (h : H ≤ f.range) : map f (comap f H) = H := by rwa [map_comap_eq, inf_eq_right] @[to_additive] lemma map_comap_eq_self_of_surjective {f : G →* N} (h : function.surjective f) (H : subgroup N) : map f (comap f H) = H := map_comap_eq_self ((range_top_of_surjective _ h).symm ▸ le_top) @[to_additive] lemma comap_injective {f : G →* N} (h : function.surjective f) : function.injective (comap f) := λ K L hKL, by { apply_fun map f at hKL, simpa [map_comap_eq_self_of_surjective h] using hKL } @[to_additive] lemma comap_map_eq_self {f : G →* N} {H : subgroup G} (h : f.ker ≤ H) : comap f (map f H) = H := by rwa [comap_map_eq, sup_eq_left] @[to_additive] lemma comap_map_eq_self_of_injective {f : G →* N} (h : function.injective f) (H : subgroup G) : comap f (map f H) = H := comap_map_eq_self (((ker_eq_bot_iff _).mpr h).symm ▸ bot_le) @[to_additive] lemma map_injective {f : G →* N} (h : function.injective f) : function.injective (map f) := λ K L hKL, by { apply_fun comap f at hKL, simpa [comap_map_eq_self_of_injective h] using hKL } @[to_additive] lemma map_eq_comap_of_inverse {f : G →* N} {g : N →* G} (hl : function.left_inverse g f) (hr : function.right_inverse g f) (H : subgroup G) : map f H = comap g H := set_like.ext' $ by rw [coe_map, coe_comap, set.image_eq_preimage_of_inverse hl hr] /-- Given `f(A) = f(B)`, `ker f ≤ A`, and `ker f ≤ B`, deduce that `A = B` -/ @[to_additive] lemma map_injective_of_ker_le {H K : subgroup G} (hH : f.ker ≤ H) (hK : f.ker ≤ K) (hf : map f H = map f K) : H = K := begin apply_fun comap f at hf, rwa [comap_map_eq, comap_map_eq, sup_of_le_left hH, sup_of_le_left hK] at hf, end @[to_additive] lemma comap_sup_eq_of_le_range {H K : subgroup N} (hH : H ≤ f.range) (hK : K ≤ f.range) : comap f H ⊔ comap f K = comap f (H ⊔ K) := map_injective_of_ker_le f ((ker_le_comap f H).trans le_sup_left) (ker_le_comap f (H ⊔ K)) (by rw [map_comap_eq, map_sup, map_comap_eq, map_comap_eq, inf_eq_right.mpr hH, inf_eq_right.mpr hK, inf_eq_right.mpr (sup_le hH hK)]) @[to_additive] lemma comap_sup_eq (H K : subgroup N) (hf : function.surjective f) : comap f H ⊔ comap f K = comap f (H ⊔ K) := comap_sup_eq_of_le_range f (le_top.trans (ge_of_eq (f.range_top_of_surjective hf))) (le_top.trans (ge_of_eq (f.range_top_of_surjective hf))) @[to_additive] lemma sup_subgroup_of_eq {H K L : subgroup G} (hH : H ≤ L) (hK : K ≤ L) : H.subgroup_of L ⊔ K.subgroup_of L = (H ⊔ K).subgroup_of L := comap_sup_eq_of_le_range L.subtype (hH.trans (ge_of_eq L.subtype_range)) (hK.trans (ge_of_eq L.subtype_range)) /-- A subgroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subgroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (H : subgroup G) (f : G →* N) (hf : function.injective f) : H ≃* H.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f H hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (H : subgroup G) (f : G →* N) (hf : function.injective f) (h : H) : (equiv_map_of_injective H f hf h : N) = f h := rfl /-- The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function. -/ @[to_additive "The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function."] lemma comap_normalizer_eq_of_surjective (H : subgroup G) {f : N →* G} (hf : function.surjective f) : H.normalizer.comap f = (H.comap f).normalizer := le_antisymm (le_normalizer_comap f) begin assume x hx, simp only [mem_comap, mem_normalizer_iff] at *, assume n, rcases hf n with ⟨y, rfl⟩, simp [hx y] end /-- The image of the normalizer is equal to the normalizer of the image of an isomorphism. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of an isomorphism."] lemma map_equiv_normalizer_eq (H : subgroup G) (f : G ≃* N) : H.normalizer.map f.to_monoid_hom = (H.map f.to_monoid_hom).normalizer := begin ext x, simp only [mem_normalizer_iff, mem_map_equiv], rw [f.to_equiv.forall_congr], simp end /-- The image of the normalizer is equal to the normalizer of the image of a bijective function. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of a bijective function."] lemma map_normalizer_eq_of_bijective (H : subgroup G) {f : G →* N} (hf : function.bijective f) : H.normalizer.map f = (H.map f).normalizer := map_equiv_normalizer_eq H (mul_equiv.of_bijective f hf) end subgroup namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) (f_inv : G₂ → G₁) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ @[to_additive "Auxiliary definition used to define `lift_of_right_inverse`"] def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (f_inv b), map_one' := hg (hf 1), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [hf _], end } @[simp, to_additive] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f x) = g x := begin dsimp [lift_of_right_inverse_aux], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [hf _], end /-- `lift_of_right_inverse f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+* G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_right_inverse f f_inv hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`add_monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+ G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+ G₃` satisfies `hg : f.ker ≤ g.ker`. See `add_monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `monoid_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp, to_additive "A non-computable version of `add_monoid_hom.lift_of_right_inverse` for when no computable right inverse is available."] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) @[simp, to_additive] lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) (x : G₁) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x @[simp, to_additive] lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := monoid_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g @[to_additive] lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by { rw [←f.comap_bot], apply_instance } @[priority 100, to_additive] instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] : ((H ⊓ N).comap H.subtype).normal := ⟨λ x hx g, begin simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx, simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap], exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩, end⟩ namespace subgroup /-- The subgroup generated by an element. -/ def zpowers (g : G) : subgroup G := subgroup.copy (zpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_zpowers (g : G) : g ∈ zpowers g := ⟨1, zpow_one _⟩ lemma zpowers_eq_closure (g : G) : zpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_zpowers_hom (g : G) : (zpowers_hom G g).range = zpowers g := rfl lemma zpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : zpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.zpow_mem h i end lemma mem_zpowers_iff {g h : G} : h ∈ zpowers g ↔ ∃ (k : ℤ), g ^ k = h := iff.rfl @[simp] lemma forall_zpowers {x : G} {p : zpowers x → Prop} : (∀ g, p g) ↔ ∀ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.forall_subtype_range_iff @[simp] lemma exists_zpowers {x : G} {p : zpowers x → Prop} : (∃ g, p g) ↔ ∃ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.exists_subtype_range_iff lemma forall_mem_zpowers {x : G} {p : G → Prop} : (∀ g ∈ zpowers x, p g) ↔ ∀ m : ℤ, p (x ^ m) := set.forall_range_iff lemma exists_mem_zpowers {x : G} {p : G → Prop} : (∃ g ∈ zpowers x, p g) ↔ ∃ m : ℤ, p (x ^ m) := set.exists_range_iff end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def zmultiples (a : A) : add_subgroup A := add_subgroup.copy (zmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl @[simp] lemma range_zmultiples_hom (a : A) : (zmultiples_hom A a).range = zmultiples a := rfl attribute [to_additive add_subgroup.zmultiples] subgroup.zpowers attribute [to_additive add_subgroup.mem_zmultiples] subgroup.mem_zpowers attribute [to_additive add_subgroup.zmultiples_eq_closure] subgroup.zpowers_eq_closure attribute [to_additive add_subgroup.range_zmultiples_hom] subgroup.range_zpowers_hom attribute [to_additive add_subgroup.zmultiples_subset] subgroup.zpowers_subset attribute [to_additive add_subgroup.mem_zmultiples_iff] subgroup.mem_zpowers_iff attribute [to_additive add_subgroup.forall_zmultiples] subgroup.forall_zpowers attribute [to_additive add_subgroup.forall_mem_zmultiples] subgroup.forall_mem_zpowers attribute [to_additive add_subgroup.exists_zmultiples] subgroup.exists_zpowers attribute [to_additive add_subgroup.exists_mem_zmultiples] subgroup.exists_mem_zpowers end add_subgroup lemma int.mem_zmultiples_iff {a b : ℤ} : b ∈ add_subgroup.zmultiples a ↔ a ∣ b := exists_congr (λ k, by rw [mul_comm, eq_comm, ← smul_eq_mul]) lemma of_mul_image_zpowers_eq_zmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.zpowers x) : set G) = add_subgroup.zmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_zpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_zpow } end lemma of_add_image_zmultiples_eq_zpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.zmultiples x) : set A) = subgroup.zpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_zpowers_eq_zmultiples_of_mul, end namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- A `mul_equiv` `φ` between two groups `G` and `G'` induces a `mul_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. -/ @[to_additive "An `add_equiv` `φ` between two additive groups `G` and `G'` induces an `add_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. "] def subgroup_equiv_map {G'} [group G'] (e : G ≃* G') (H : subgroup G) : H ≃* H.map e.to_monoid_hom := e.submonoid_equiv_map H.to_submonoid end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem_sup hy hz⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup section variables (G) (A) /-- A `group` is simple when it has exactly two normal `subgroup`s. -/ class is_simple_group extends nontrivial G : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : subgroup G, H.normal → H = ⊥ ∨ H = ⊤) /-- An `add_group` is simple when it has exactly two normal `add_subgroup`s. -/ class is_simple_add_group extends nontrivial A : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : add_subgroup A, H.normal → H = ⊥ ∨ H = ⊤) attribute [to_additive] is_simple_group variables {G} {A} @[to_additive] lemma subgroup.normal.eq_bot_or_eq_top [is_simple_group G] {H : subgroup G} (Hn : H.normal) : H = ⊥ ∨ H = ⊤ := is_simple_group.eq_bot_or_eq_top_of_normal H Hn namespace is_simple_group @[to_additive] instance {C : Type*} [comm_group C] [is_simple_group C] : is_simple_lattice (subgroup C) := ⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩ open _root_.subgroup @[to_additive] lemma is_simple_group_of_surjective {H : Type*} [group H] [is_simple_group G] [nontrivial H] (f : G →* H) (hf : function.surjective f) : is_simple_group H := ⟨nontrivial.exists_pair_ne, λ H iH, begin refine ((iH.comap f).eq_bot_or_eq_top).imp (λ h, _) (λ h, _), { rw [←map_bot f, ←h, map_comap_eq_self_of_surjective hf] }, { rw [←comap_top f] at h, exact comap_injective hf h } end⟩ end is_simple_group end namespace subgroup section pointwise @[to_additive] lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) @[to_additive] private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G := { carrier := (H : set G) * N, one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩, ⟨h * h', h'⁻¹ * n * h' * n', H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨h, n, hh, hn, hx⟩, ⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h, by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ } /-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition) when `N` is normal."] lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N := set.subset.antisymm (show H ⊔ N ≤ mul_normal_aux H N, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure H N).symm ▸ subset_closure) @[to_additive] private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G := { carrier := (N : set G) * H, one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩, ⟨n * (h * n' * h⁻¹), h * h', N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨n, h, hn, hh, hx⟩, ⟨h⁻¹ * n⁻¹ * h, h⁻¹, by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh, by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ } /-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition) when `N` is normal."] lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H := set.subset.antisymm (show N ⊔ H ≤ normal_mul_aux N H, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure N H).symm ▸ subset_closure) @[to_additive] lemma mul_inf_assoc (A B C : subgroup G) (h : A ≤ C) : (A : set G) * ↑(B ⊓ C) = (A * B) ⊓ C := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, hy, ⟨hzB, hzC⟩, rfl⟩, refine ⟨_, mul_mem C (h hy) hzC⟩, exact ⟨y, z, hy, hzB, rfl⟩ }, rintros ⟨⟨y, z, hy, hz, rfl⟩, hyz⟩, refine ⟨y, z, hy, ⟨hz, _⟩, rfl⟩, suffices : y⁻¹ * (y * z) ∈ C, { simpa }, exact mul_mem C (inv_mem C (h hy)) hyz end @[to_additive] lemma inf_mul_assoc (A B C : subgroup G) (h : C ≤ A) : ((A ⊓ B : subgroup G) : set G) * C = A ⊓ (B * C) := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, ⟨hyA, hyB⟩, hz, rfl⟩, refine ⟨mul_mem A hyA (h hz), _⟩, exact ⟨y, z, hyB, hz, rfl⟩ }, rintros ⟨hyz, y, z, hy, hz, rfl⟩, refine ⟨y, z, ⟨_, hy⟩, hz, rfl⟩, suffices : (y * z) * z⁻¹ ∈ A, { simpa }, exact mul_mem A hyz (inv_mem A (h hz)) end end pointwise section subgroup_normal @[to_additive] lemma normal_subgroup_of_iff {H K : subgroup G} (hHK : H ≤ K) : (H.subgroup_of K).normal ↔ ∀ h k, h ∈ H → k ∈ K → k * h * k⁻¹ ∈ H := ⟨λ hN h k hH hK, hN.conj_mem ⟨h, hHK hH⟩ hH ⟨k, hK⟩, λ hN, { conj_mem := λ h hm k, (hN h.1 k.1 hm k.2) }⟩ @[to_additive] instance prod_subgroup_of_prod_normal {H₁ K₁ : subgroup G} {H₂ K₂ : subgroup N} [h₁ : (H₁.subgroup_of K₁).normal] [h₂ : (H₂.subgroup_of K₂).normal] : ((H₁.prod H₂).subgroup_of (K₁.prod K₂)).normal := { conj_mem := λ n hgHK g, ⟨h₁.conj_mem ⟨(n : G × N).fst, (mem_prod.mp n.2).1⟩ hgHK.1 ⟨(g : G × N).fst, (mem_prod.mp g.2).1⟩, h₂.conj_mem ⟨(n : G × N).snd, (mem_prod.mp n.2).2⟩ hgHK.2 ⟨(g : G × N).snd, (mem_prod.mp g.2).2⟩⟩ } @[to_additive] instance prod_normal (H : subgroup G) (K : subgroup N) [hH : H.normal] [hK : K.normal] : (H.prod K).normal := { conj_mem := λ n hg g, ⟨hH.conj_mem n.fst (subgroup.mem_prod.mp hg).1 g.fst, hK.conj_mem n.snd (subgroup.mem_prod.mp hg).2 g.snd⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_right (A B' B : subgroup G) (hB : B' ≤ B) [hN : (B'.subgroup_of B).normal] : ((A ⊓ B').subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨mul_mem A (mul_mem A (mem_inf.1 g.2).1 (mem_inf.1 n.2).1) (inv_mem A (mem_inf.1 g.2).1), (normal_subgroup_of_iff hB).mp hN n g hn.2 (mem_inf.mp g.2).2⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_left {A' A : subgroup G} (B : subgroup G) (hA : A' ≤ A) [hN : (A'.subgroup_of A).normal] : ((A' ⊓ B).subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨(normal_subgroup_of_iff hA).mp hN n g hn.1 (mem_inf.mp g.2).1, mul_mem B (mul_mem B (mem_inf.1 g.2).2 (mem_inf.1 n.2).2) (inv_mem B (mem_inf.1 g.2).2)⟩ } instance sup_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊔ K).normal := { conj_mem := λ n hmem g, begin change n ∈ ↑(H ⊔ K) at hmem, change g * n * g⁻¹ ∈ ↑(H ⊔ K), rw [normal_mul, set.mem_mul] at *, rcases hmem with ⟨h, k, hh, hk, rfl⟩, refine ⟨g * h * g⁻¹, g * k * g⁻¹, hH.conj_mem h hh g, hK.conj_mem k hk g, _⟩, simp end } @[to_additive] instance normal_inf_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊓ K).normal := { conj_mem := λ n hmem g, by { rw mem_inf at *, exact ⟨hH.conj_mem n hmem.1 g, hK.conj_mem n hmem.2 g⟩ } } @[to_additive] lemma subgroup_of_sup (A A' B : subgroup G) (hA : A ≤ B) (hA' : A' ≤ B) : (A ⊔ A').subgroup_of B = A.subgroup_of B ⊔ A'.subgroup_of B := begin refine map_injective_of_ker_le B.subtype (ker_le_comap _ _) (le_trans (ker_le_comap B.subtype _) le_sup_left) _, { simp only [subgroup_of, map_comap_eq, map_sup, subtype_range], rw [inf_of_le_right (sup_le hA hA'), inf_of_le_right hA', inf_of_le_right hA] }, end @[to_additive] lemma subgroup_normal.mem_comm {H K : subgroup G} (hK : H ≤ K) [hN : (H.subgroup_of K).normal] {a b : G} (hb : b ∈ K) (h : a * b ∈ H) : b * a ∈ H := begin have := (normal_subgroup_of_iff hK).mp hN (a * b) b h hb, rwa [mul_assoc, mul_assoc, mul_right_inv, mul_one] at this, end end subgroup_normal end subgroup namespace is_conj open subgroup lemma normal_closure_eq_top_of {N : subgroup G} [hn : N.normal] {g g' : G} {hg : g ∈ N} {hg' : g' ∈ N} (hc : is_conj g g') (ht : normal_closure ({⟨g, hg⟩} : set N) = ⊤) : normal_closure ({⟨g', hg'⟩} : set N) = ⊤ := begin obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, have h : ∀ x : N, (mul_aut.conj c) x ∈ N, { rintro ⟨x, hx⟩, exact hn.conj_mem _ hx c }, have hs : function.surjective (((mul_aut.conj c).to_monoid_hom.restrict N).cod_restrict _ h), { rintro ⟨x, hx⟩, refine ⟨⟨c⁻¹ * x * c, _⟩, _⟩, { have h := hn.conj_mem _ hx c⁻¹, rwa [inv_inv] at h }, simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, subtype.mk_eq_mk, ← mul_assoc, mul_inv_self, one_mul], rw [mul_assoc, mul_inv_self, mul_one] }, have ht' := map_mono (eq_top_iff.1 ht), rw [← monoid_hom.range_eq_map, monoid_hom.range_top_of_surjective _ hs] at ht', refine eq_top_iff.2 (le_trans ht' (map_le_iff_le_comap.2 (normal_closure_le_normal _))), rw [set.singleton_subset_iff, set_like.mem_coe], simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, mem_comap], exact subset_normal_closure (set.mem_singleton _), end end is_conj /-! ### Actions by `subgroup`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. -/ section actions namespace subgroup variables {α β : Type*} /-- The action by a subgroup is the action by the underlying group. -/ @[to_additive /-"The additive action by an add_subgroup is the action by the underlying add_group. "-/] instance [mul_action G α] (S : subgroup G) : mul_action S α := S.to_submonoid.mul_action @[to_additive] lemma smul_def [mul_action G α] {S : subgroup G} (g : S) (m : α) : g • m = (g : G) • m := rfl @[to_additive] instance smul_comm_class_left [mul_action G β] [has_scalar α β] [smul_comm_class G α β] (S : subgroup G) : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left @[to_additive] instance smul_comm_class_right [has_scalar α β] [mul_action G β] [smul_comm_class α G β] (S : subgroup G) : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S G G` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [mul_action G α] [mul_action G β] [is_scalar_tower G α β] (S : subgroup G) : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [mul_action G α] [has_faithful_scalar G α] (S : subgroup G) : has_faithful_scalar S α := S.to_submonoid.has_faithful_scalar /-- The action by a subgroup is the action by the underlying group. -/ instance [add_monoid α] [distrib_mul_action G α] (S : subgroup G) : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subgroup is the action by the underlying group. -/ instance [monoid α] [mul_distrib_mul_action G α] (S : subgroup G) : mul_distrib_mul_action S α := S.to_submonoid.mul_distrib_mul_action end subgroup end actions /-! ### Saturated subgroups -/ section saturated namespace subgroup /-- A subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `g^n ∈ H` we have `n = 0` or `g ∈ H`. -/ @[to_additive "An additive subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `n•g ∈ H` we have `n = 0` or `g ∈ H`."] def saturated (H : subgroup G) : Prop := ∀ ⦃n g⦄, g ^ n ∈ H → n = 0 ∨ g ∈ H @[to_additive] lemma saturated_iff_npow {H : subgroup G} : saturated H ↔ (∀ (n : ℕ) (g : G), g ^ n ∈ H → n = 0 ∨ g ∈ H) := iff.rfl @[to_additive] lemma saturated_iff_zpow {H : subgroup G} : saturated H ↔ (∀ (n : ℤ) (g : G), g ^ n ∈ H → n = 0 ∨ g ∈ H) := begin split, { rintros hH ⟨n⟩ g hgn, { simp only [int.coe_nat_eq_zero, int.of_nat_eq_coe, zpow_coe_nat] at hgn ⊢, exact hH hgn }, { suffices : g ^ (n+1) ∈ H, { refine (hH this).imp _ id, simp only [forall_false_left, nat.succ_ne_zero], }, simpa only [inv_mem_iff, zpow_neg_succ_of_nat] using hgn, } }, { intros h n g hgn, specialize h n g, simp only [int.coe_nat_eq_zero, zpow_coe_nat] at h, apply h hgn } end end subgroup namespace add_subgroup lemma ker_saturated {A₁ A₂ : Type*} [add_comm_group A₁] [add_comm_group A₂] [no_zero_smul_divisors ℕ A₂] (f : A₁ →+ A₂) : (f.ker).saturated := begin intros n g hg, simpa only [f.mem_ker, nsmul_eq_smul, f.map_nsmul, smul_eq_zero] using hg end end add_subgroup end saturated
b89954ff2889eeaf35c25acbc9c5fb4d0e1f7df1
217bb195841a8be2d1b4edd2084d6b69ccd62f50
/library/init/data/rbmap/basic.lean
cf0258d066c49ef3f26e9487be852ee0b4f166a2
[ "Apache-2.0" ]
permissive
frank-lesser/lean4
717f56c9bacd5bf3a67542d2f5cea721d4743a30
79e2abe33f73162f773ea731265e456dbfe822f9
refs/heads/master
1,589,741,267,933
1,556,424,200,000
1,556,424,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,306
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.repr init.data.option.basic universes u v w w' inductive Rbcolor | red | black inductive RBNode (α : Type u) (β : α → Type v) | leaf {} : RBNode | node (color : Rbcolor) (lchild : RBNode) (key : α) (val : β key) (rchild : RBNode) : RBNode namespace RBNode variables {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf := 0 | (node _ l _ _ r) := succ (f (depth l) (depth r)) protected def min : RBNode α β → Option (Σ k : α, β k) | leaf := none | (node _ leaf k v _) := some ⟨k, v⟩ | (node _ l k v _) := min l protected def max : RBNode α β → Option (Σ k : α, β k) | leaf := none | (node _ _ k v leaf) := some ⟨k, v⟩ | (node _ _ k v r) := max r @[specialize] def fold (f : σ → Π (k : α), β k → σ) : σ → RBNode α β → σ | b leaf := b | b (node _ l k v r) := fold (f (fold b l) k v) r @[specialize] def mfold {m : Type w → Type w'} [Monad m] (f : σ → Π (k : α), β k → m σ) : σ → RBNode α β → m σ | b leaf := pure b | b (node _ l k v r) := do b ← mfold b l, b ← f b k v, mfold b r @[specialize] def revFold (f : σ → Π (k : α), β k → σ) : σ → RBNode α β → σ | b leaf := b | b (node _ l k v r) := revFold (f (revFold b r) k v) l @[specialize] def all (p : Π k : α, β k → Bool) : RBNode α β → Bool | leaf := true | (node _ l k v r) := p k v && all l && all r @[specialize] def any (p : Π k : α, β k → Bool) : RBNode α β → Bool | leaf := false | (node _ l k v r) := p k v || any l || any r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf @[inline] def balance1 : Π a, β a → RBNode α β → RBNode α β → RBNode α β | kv vv t (node _ (node red l kx vx r₁) ky vy r₂) := node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t) | kv vv t (node _ l₁ ky vy (node red l₂ kx vx r)) := node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t) | kv vv t (node _ l ky vy r) := node black (node red l ky vy r) kv vv t | _ _ _ _ := leaf -- unreachable @[inline] def balance2 : RBNode α β → Π a, β a → RBNode α β → RBNode α β | t kv vv (node _ (node red l kx₁ vx₁ r₁) ky vy r₂) := node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂) | t kv vv (node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂)) := node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂) | t kv vv (node _ l ky vy r) := node black t kv vv (node red l ky vy r) | _ _ _ _ := leaf -- unreachable def isRed : RBNode α β → Bool | (node red _ _ _ _) := true | _ := false section insert variables (lt : α → α → Bool) @[specialize] def ins : RBNode α β → Π k : α, β k → RBNode α β | leaf kx vx := node red leaf kx vx leaf | (node red a ky vy b) kx vx := if lt kx ky then node red (ins a kx vx) ky vy b else if lt ky kx then node red a ky vy (ins b kx vx) else node red a kx vx b | (node black a ky vy b) kx vx := if lt kx ky then if isRed a then balance1 ky vy b (ins a kx vx) else node black (ins a kx vx) ky vy b else if lt ky kx then if isRed b then balance2 a ky vy (ins b kx vx) else node black a ky vy (ins b kx vx) else node black a kx vx b def setBlack : RBNode α β → RBNode α β | (node _ l k v r) := node black l k v r | e := e @[inline] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins lt t k v) else ins lt t k v end insert section membership variable (lt : α → α → Bool) @[specialize] def findCore : RBNode α β → Π k : α, Option (Σ k : α, β k) | leaf x := none | (node _ a ky vy b) x := if lt x ky then findCore a x else if lt ky x then findCore b x else some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (λ _, β) → α → Option β | leaf x := none | (node _ a ky vy b) x := if lt x ky then find a x else if lt ky x then find b x else some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf x lb := lb | (node _ a ky vy b) x lb := if lt x ky then lowerBound a x lb else if lt ky x then lowerBound b x (some ⟨ky, vy⟩) else some ⟨ky, vy⟩ end membership inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop | leafWff : WellFormed leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed n → n' = insert lt n k v → WellFormed n' end RBNode open RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) := {t : RBNode α (λ _, β) // t.WellFormed lt } @[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt := ⟨leaf, WellFormed.leafWff lt⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt := mkRBMap _ _ _ instance (α : Type u) (β : Type v) (lt : α → α → Bool) : HasEmptyc (RBMap α β lt) := ⟨RBMap.empty⟩ namespace RBMap variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool} def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : σ → RBMap α β lt → σ | b ⟨t, _⟩ := t.fold f b @[inline] def revFold (f : σ → α → β → σ) : σ → RBMap α β lt → σ | b ⟨t, _⟩ := t.revFold f b @[inline] def mfold {m : Type w → Type w'} [Monad m] (f : σ → α → β → m σ) : σ → RBMap α β lt → m σ | b ⟨t, _⟩ := t.mfold f b @[inline] def mfor {m : Type w → Type w'} [Monad m] (f : α → β → m σ) (t : RBMap α β lt) : m PUnit := t.mfold (λ _ k v, f k v *> pure ⟨⟩) ⟨⟩ @[inline] def isEmpty : RBMap α β lt → Bool | ⟨leaf, _⟩ := true | _ := false @[specialize] def toList : RBMap α β lt → List (α × β) | ⟨t, _⟩ := t.revFold (λ ps k v, (k, v)::ps) [] @[inline] protected def min : RBMap α β lt → Option (α × β) | ⟨t, _⟩ := match t.min with | some ⟨k, v⟩ := some (k, v) | none := none @[inline] protected def max : RBMap α β lt → Option (α × β) | ⟨t, _⟩ := match t.max with | some ⟨k, v⟩ := some (k, v) | none := none instance [HasRepr α] [HasRepr β] : HasRepr (RBMap α β lt) := ⟨λ t, "rbmapOf " ++ repr t.toList⟩ @[inline] def insert : RBMap α β lt → α → β → RBMap α β lt | ⟨t, w⟩ k v := ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β lt | [] := mkRBMap _ _ _ | (⟨k,v⟩::xs) := (ofList xs).insert k v @[inline] def findCore : RBMap α β lt → α → Option (Σ k : α, β) | ⟨t, _⟩ x := t.findCore lt x @[inline] def find : RBMap α β lt → α → Option β | ⟨t, _⟩ x := t.find lt x /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β lt → α → Option (Σ k : α, β) | ⟨t, _⟩ x := t.lowerBound lt x none @[inline] def contains (t : RBMap α β lt) (a : α) : Bool := (t.find a).isSome @[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := l.foldl (λ r p, r.insert p.1 p.2) (mkRBMap α β lt) @[inline] def all : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩ p := t.all p @[inline] def any : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩ p := t.any p end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := RBMap.fromList l lt
9df76360c0c8347a01b55e0b9613db2d5fac0c20
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/instances/monoids.lean
4158f7fe1da02e25dedef50129a074c2c96579af
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
1,741
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison Introduce Mon -- the category of monoids. Currently only the basic setup. -/ import category_theory.concrete_category import category_theory.fully_faithful import category_theory.adjunction import data.finsupp universes u v open category_theory namespace category_theory.instances /-- The category of monoids and monoid morphisms. -/ @[reducible] def Mon : Type (u+1) := bundled monoid instance (x : Mon) : monoid x := x.str instance concrete_is_monoid_hom : concrete_category @is_monoid_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance Mon_hom_is_monoid_hom {R S : Mon} (f : R ⟶ S) : is_monoid_hom (f : R → S) := f.2 /-- The category of commutative monoids and monoid morphisms. -/ @[reducible] def CommMon : Type (u+1) := bundled comm_monoid instance (x : CommMon) : comm_monoid x := x.str @[reducible] def is_comm_monoid_hom {α β} [comm_monoid α] [comm_monoid β] (f : α → β) : Prop := is_monoid_hom f instance concrete_is_comm_monoid_hom : concrete_category @is_comm_monoid_hom := ⟨by introsI α ia; apply_instance, by introsI α β γ ia ib ic f g hf hg; apply_instance⟩ instance CommMon_hom_is_comm_monoid_hom {R S : CommMon} (f : R ⟶ S) : is_comm_monoid_hom (f : R → S) := f.2 namespace CommMon /-- The forgetful functor from commutative monoids to monoids. -/ def forget_to_Mon : CommMon ⥤ Mon := concrete_functor (by intros _ c; exact { ..c }) (by introsI _ _ _ _ f i; exact { ..i }) instance : faithful (forget_to_Mon) := {} end CommMon end category_theory.instances
5a5bcefa56e5fdab6f23ecfe550a17fb01482421
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/relations/equiv_partition.lean
20ecb746667e41dfe0207cb62aa37e533523b8d8
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
4,894
lean
import tactic import data.setoid.partition --#check setoid.partition.rel_iso open setoid variable (α : Type) -- mathlib has this function already. /- def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} -/ -- set_option pp.notation false example : {p : set (set α) // is_partition p} ≃ setoid α := { to_fun := λ pa, { r := λ (a b : α), ∀ X ∈ pa.1, a ∈ X → b ∈ X, iseqv := begin cases pa with p hp, dsimp only at *, -- Need to check that the binary relation on α coming from -- a partition p is reflexive, symmetric and transitive -- note that p is just the set of sets; hp is the proof -- that it's a partition. split, { -- reflexive unfold reflexive, cc, }, split, { -- symmetric -- this needs thought -- rintros a b hab X (hX : X ∈ p) hbX, -- obtain ⟨Y, ⟨hYp, haY, -⟩, hY2⟩ := hp.2 a, simp at hY2, -- have hY3 : ∀ (Z : set α), Z ∈ p → a ∈ Z → Z = Y, rintros b c hbc X (hX : X ∈ p) hcX, obtain ⟨Y, ⟨hYp, hcY, -⟩, hY2⟩ := hp.2 c, simp at hY2, have hpcY : ∀ (Z : set α), Z ∈ p → c ∈ Z → Z = Y, simpa using hY2, clear hY2, --specialize hab {x | r.rel x y} have hXY := hpcY X hX hcX, obtain ⟨Z, ⟨hZp, hbZ, -⟩, hZ2⟩ := hp.2 b, simp at hZ2, have hcZ := hbc Z hZp hbZ, have hZY := hpcY Z hZp hcZ, rw [hXY, ← hZY], exact hbZ }, { -- transitive intros b c d hbc hcd X hXp hbX, apply hcd, exact hXp, apply hbc; assumption, } end }, inv_fun := λ r, ⟨classes r, begin haveI : has_equiv α := ⟨r.rel⟩, split, { -- empty set isn't an equiv class -- proof by contradiction intro h, cases h with a ha, suffices : a ∈ (∅ : set α), cases this, rw ha, simp only [set.mem_set_of_eq], }, { intro a, use {x : α | r.rel x a}, dsimp only, split, { suffices : {x : α | r.rel x a} ∈ r.classes ∧ r.rel a a, simpa, split, use a, refl }, { intro X, rintro ⟨⟨c, rfl⟩, haX, -⟩, ext b, resetI, -- TODO must fix this notation change setoid.r b c ↔ r.rel b a, change r.rel a c at haX, split, intro hbc, apply r.iseqv.2.2, -- these suck exact hbc, apply r.iseqv.2.1, exact haX, -- need a ~ b <-> b ~ a intro hba, apply r.iseqv.2.2,exact hba, exact haX, } } end⟩, left_inv := begin rintro ⟨p, hp⟩, simp only, ext X, split, { rintro ⟨b, rfl⟩, obtain ⟨Y, ⟨hYp, hbY, -⟩, hY2⟩ := hp.2 b, have hpb : ∀ (y : set α), y ∈ p → b ∈ y → y = Y, simpa using hY2, clear hY2, convert hYp, ext c, obtain ⟨Z, ⟨hZp, hcZ, -⟩, hY2⟩ := hp.2 c, have hpc : ∀ (y : set α), y ∈ p → c ∈ y → y = Z, simpa using hY2, clear hY2, show (∀ X : set α, X ∈ p → c ∈ X → b ∈ X) ↔ _, split, { intro hpcb, specialize hpcb Z hZp hcZ, specialize hpb Z hZp hpcb, rw ← hpb, exact hcZ, }, { intro hcY, intros X hXp hcX, have hXZ := hpc X hXp hcX, have hYZ := hpc Y hYp hcY, convert hbY, cc } }, { intro hXp, have hX : X.nonempty, have h := hp.1, rw ← set.ne_empty_iff_nonempty, rintro rfl, contradiction, cases hX with b hbX, use b, ext c, simp, show c ∈ X ↔ (∀ X : set α, X ∈ p → c ∈ X → b ∈ X), split, { intros hcX Y hYp hcY, convert hbX, obtain ⟨Z, ⟨hZp, hcZ, -⟩, hY2⟩ := hp.2 c, have hpc : ∀ (y : set α), y ∈ p → c ∈ y → y = Z, simpa using hY2, clear hY2, have hYZ := hpc Y hYp hcY, have hXZ := hpc X hXp hcX, cc }, { intros hcb, obtain ⟨Z, ⟨hZp, hcZ, -⟩, hY2⟩ := hp.2 c, have hpc : ∀ (y : set α), y ∈ p → c ∈ y → y = Z, simpa using hY2, clear hY2, obtain ⟨Y, ⟨hYp, hbY, -⟩, hY2⟩ := hp.2 b, have hpb : ∀ (y : set α), y ∈ p → b ∈ y → y = Y, simpa using hY2, clear hY2, have hZY := hpb Z hZp (hcb Z hZp hcZ), have hXY := hpb X hXp hbX, cc } } end, right_inv := begin rintro ⟨r, hrr, hrs, hrt⟩, ext s, simp only [setoid.rel], split, { intro h, specialize h {x : α | r x s} (by use s; refl) (by apply hrr), apply hrs, exact h }, { intros hrsb X, rintros ⟨c, rfl⟩ h, simp [setoid.rel] at h ⊢, apply hrt, apply hrs, exact hrsb, exact h, } end }
7172f03dce98a9d457964ff2f841239cada1f878
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/algebra/lattice/complete_boolean_algebra.lean
8de16a86a1434afef0458fde81cbab54f5cf0cf6
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
2,132
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of complete Boolean algebras. -/ import .complete_lattice .boolean_algebra data.set.basic set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} namespace lattice class complete_distrib_lattice α extends complete_lattice α := (infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s) (inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b)) section complete_distrib_lattice variables [complete_distrib_lattice α] {a : α} {s : set α} lemma sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) := le_antisymm (le_infi $ assume i, le_infi $ assume h, sup_le_sup (le_refl _) (Inf_le h)) (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) lemma inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) := le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf _ _) (supr_le $ assume i, supr_le $ assume h, inf_le_inf (le_refl _) (le_Sup h)) end complete_distrib_lattice instance [d : complete_distrib_lattice α] : bounded_distrib_lattice α := { d with le_sup_inf := assume x y z, calc (x ⊔ y) ⊓ (x ⊔ z) ≤ (⨅ b ∈ ({z, y} : set α), x ⊔ b) : by rw insert_of_has_insert; simp ... = x ⊔ Inf {z, y} : sup_Inf_eq^.symm ... = x ⊔ y ⊓ z : by rw insert_of_has_insert; simp } class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α section complete_boolean_algebra variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α} lemma neg_infi : - infi f = (⨆i, - f i) := le_antisymm (neg_le_of_neg_le $ le_infi $ assume i, neg_le_of_neg_le $ le_supr (λi, - f i) i) (supr_le $ assume i, neg_le_neg $ infi_le _ _) lemma neg_supr : - supr f = (⨅i, - f i) := neg_eq_neg_of_eq (by simp [neg_infi]) lemma neg_Inf : - Inf s = (⨆i∈s, - i) := by simp [Inf_eq_infi, neg_infi] lemma neg_Sup : - Sup s = (⨅i∈s, - i) := by simp [Sup_eq_supr, neg_supr] end complete_boolean_algebra end lattice
7254e96b99721fbb57b1c4e9458019e8b53157ce
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Match.lean
a2eb3c86f71168939962a5f520091c7f91c86522
[ "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,370
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Elab.Match import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.Induction namespace Lean.Elab.Tactic open Meta open TSyntax.Compat in open Parser.Tactic in private def mkAuxiliaryMatchTerm (parentTag : Name) (matchTac : Syntax) : MacroM (Term × Array Syntax) := do let matchAlts := matchTac[5] let alts := matchAlts[0].getArgs let mut newAlts := #[] let mut nextIdx := 1 let mut newCases := #[] for alt in alts do let alt := alt.setKind ``Parser.Term.matchAlt let holeOrTacticSeq := alt[3] -- must generate a separate mvar for each `| $patGroup | ... => ...` as they can have different local contexts for patGroup in alt[1].getSepArgs do let mut alt := alt.setArg 1 (mkNullNode #[patGroup]) if holeOrTacticSeq.isOfKind ``Parser.Term.syntheticHole then pure () else if holeOrTacticSeq.isOfKind ``Parser.Term.hole then let tag := if alts.size > 1 then parentTag ++ (`match).appendIndexAfter nextIdx else parentTag let holeName := mkIdentFrom holeOrTacticSeq tag let newHole ← `(?$holeName:ident) nextIdx := nextIdx + 1 alt := alt.setArg 3 newHole else let newHole ← withFreshMacroScope `(?rhs) let newHoleId := newHole.raw[1] let newCase ← `(tactic| case $newHoleId:ident =>%$(alt[2]) -- annotate `| ... =>` with state after `case` with_annotate_state $(mkNullNode #[alt[0], alt[2]]) skip $holeOrTacticSeq) newCases := newCases.push newCase alt := alt.setArg 3 newHole newAlts := newAlts.push alt let result := matchTac.setKind ``Parser.Term.«match» let result := result.setArg 5 (mkNode ``Parser.Term.matchAlts #[mkNullNode newAlts]) return (result, newCases) @[builtin_tactic Lean.Parser.Tactic.match] def evalMatch : Tactic := fun stx => do let tag ← getMainTag let (matchTerm, casesStx) ← liftMacroM <| mkAuxiliaryMatchTerm tag stx let refineMatchTerm ← `(tactic| refine no_implicit_lambda% $matchTerm) let stxNew := mkNullNode (#[refineMatchTerm] ++ casesStx) withMacroExpansion stx stxNew <| evalTactic stxNew end Lean.Elab.Tactic
fe2d717c113ee2d51588d570d783547d98ebcb5f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/partition.lean
840ae22c4ee4c64abb548a280b3a8f9630b4364a
[ "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,216
lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import combinatorics.simple_graph.coloring /-! # Graph partitions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module provides an interface for dealing with partitions on simple graphs. A partition of a graph `G`, with vertices `V`, is a set `P` of disjoint nonempty subsets of `V` such that: * The union of the subsets in `P` is `V`. * Each element of `P` is an independent set. (Each subset contains no pair of adjacent vertices.) Graph partitions are graph colorings that do not name their colors. They are adjoint in the following sense. Given a graph coloring, there is an associated partition from the set of color classes, and given a partition, there is an associated graph coloring from using the partition's subsets as colors. Going from graph colorings to partitions and back makes a coloring "canonical": all colors are given a canonical name and unused colors are removed. Going from partitions to graph colorings and back is the identity. ## Main definitions * `simple_graph.partition` is a structure to represent a partition of a simple graph * `simple_graph.partition.parts_card_le` is whether a given partition is an `n`-partition. (a partition with at most `n` parts). * `simple_graph.partitionable n` is whether a given graph is `n`-partite * `simple_graph.partition.to_coloring` creates colorings from partitions * `simple_graph.coloring.to_partition` creates partitions from colorings ## Main statements * `simple_graph.partitionable_iff_colorable` is that `n`-partitionability and `n`-colorability are equivalent. -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- A `partition` of a simple graph `G` is a structure constituted by * `parts`: a set of subsets of the vertices `V` of `G` * `is_partition`: a proof that `parts` is a proper partition of `V` * `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices -/ structure partition := (parts : set (set V)) (is_partition : setoid.is_partition parts) (independent : ∀ (s ∈ parts), is_antichain G.adj s) /-- Whether a partition `P` has at most `n` parts. A graph with a partition satisfying this predicate called `n`-partite. (See `simple_graph.partitionable`.) -/ def partition.parts_card_le {G : simple_graph V} (P : G.partition) (n : ℕ) : Prop := ∃ (h : P.parts.finite), h.to_finset.card ≤ n /-- Whether a graph is `n`-partite, which is whether its vertex set can be partitioned in at most `n` independent sets. -/ def partitionable (n : ℕ) : Prop := ∃ (P : G.partition), P.parts_card_le n namespace partition variables {G} (P : G.partition) /-- The part in the partition that `v` belongs to -/ def part_of_vertex (v : V) : set V := classical.some (P.is_partition.2 v) lemma part_of_vertex_mem (v : V) : P.part_of_vertex v ∈ P.parts := by { obtain ⟨h, -⟩ := (P.is_partition.2 v).some_spec.1, exact h, } lemma mem_part_of_vertex (v : V) : v ∈ P.part_of_vertex v := by { obtain ⟨⟨h1, h2⟩, h3⟩ := (P.is_partition.2 v).some_spec, exact h2.1 } lemma part_of_vertex_ne_of_adj {v w : V} (h : G.adj v w) : P.part_of_vertex v ≠ P.part_of_vertex w := begin intro hn, have hw := P.mem_part_of_vertex w, rw ←hn at hw, exact P.independent _ (P.part_of_vertex_mem v) (P.mem_part_of_vertex v) hw (G.ne_of_adj h) h, end /-- Create a coloring using the parts themselves as the colors. Each vertex is colored by the part it's contained in. -/ def to_coloring : G.coloring P.parts := coloring.mk (λ v, ⟨P.part_of_vertex v, P.part_of_vertex_mem v⟩) $ λ _ _ hvw, by { rw [ne.def, subtype.mk_eq_mk], exact P.part_of_vertex_ne_of_adj hvw } /-- Like `simple_graph.partition.to_coloring` but uses `set V` as the coloring type. -/ def to_coloring' : G.coloring (set V) := coloring.mk P.part_of_vertex $ λ _ _ hvw, P.part_of_vertex_ne_of_adj hvw lemma to_colorable [fintype P.parts] : G.colorable (fintype.card P.parts) := P.to_coloring.to_colorable end partition variables {G} /-- Creates a partition from a coloring. -/ @[simps] def coloring.to_partition {α : Type v} (C : G.coloring α) : G.partition := { parts := C.color_classes, is_partition := C.color_classes_is_partition, independent := begin rintros s ⟨c, rfl⟩, apply C.color_classes_independent, end } /-- The partition where every vertex is in its own part. -/ @[simps] instance : inhabited (partition G) := ⟨G.self_coloring.to_partition⟩ lemma partitionable_iff_colorable {n : ℕ} : G.partitionable n ↔ G.colorable n := begin split, { rintro ⟨P, hf, h⟩, haveI : fintype P.parts := hf.fintype, rw set.finite.card_to_finset at h, apply P.to_colorable.mono h, }, { rintro ⟨C⟩, refine ⟨C.to_partition, C.color_classes_finite, le_trans _ (fintype.card_fin n).le⟩, generalize_proofs h, haveI : fintype C.color_classes := C.color_classes_finite.fintype, rw h.card_to_finset, exact C.card_color_classes_le }, end end simple_graph
490f87f9e93428f2a4166e8a438a4eb8a3e2cd81
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/rat/floor.lean
40182da92fe3389ca1892a7583c4993407da69b8
[]
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
2,122
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.floor import Mathlib.tactic.field_simp import Mathlib.PostPort namespace Mathlib /-! # Floor Function for Rational Numbers ## Summary We define the `floor` function and the `floor_ring` instance on `ℚ`. Some technical lemmas relating `floor` to integer division and modulo arithmetic are derived as well as some simple inequalities. ## Tags rat, rationals, ℚ, floor -/ namespace rat /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ protected def floor : ℚ → ℤ := sorry protected theorem le_floor {z : ℤ} {r : ℚ} : z ≤ rat.floor r ↔ ↑z ≤ r := sorry protected instance floor_ring : floor_ring ℚ := floor_ring.mk rat.floor rat.le_floor protected theorem floor_def {q : ℚ} : floor q = num q / ↑(denom q) := cases_on q fun (q_num : ℤ) (q_denom : ℕ) (q_pos : 0 < q_denom) (q_cop : nat.coprime (int.nat_abs q_num) q_denom) => Eq.refl (floor (mk' q_num q_denom q_pos q_cop)) theorem floor_int_div_nat_eq_div {n : ℤ} {d : ℕ} : floor (↑n / ↑d) = n / ↑d := sorry end rat theorem int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % ↑d = n - ↑d * floor (↑n / ↑d) := eq.mpr (id (Eq._oldrec (Eq.refl (n % ↑d = n - ↑d * floor (↑n / ↑d))) (eq_sub_of_add_eq (int.mod_add_div n ↑d)))) (eq.mpr (id (Eq._oldrec (Eq.refl (n - ↑d * (n / ↑d) = n - ↑d * floor (↑n / ↑d))) rat.floor_int_div_nat_eq_div)) (Eq.refl (n - ↑d * (n / ↑d)))) theorem nat.coprime_sub_mul_floor_rat_div_of_coprime {n : ℕ} {d : ℕ} (n_coprime_d : nat.coprime n d) : nat.coprime (int.nat_abs (↑n - ↑d * floor (↑n / ↑d))) d := sorry namespace rat theorem num_lt_succ_floor_mul_denom (q : ℚ) : num q < (floor q + 1) * ↑(denom q) := sorry theorem fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q) : num (fract (q⁻¹)) < num q := sorry
b277487bc5dd41c6c418b2256e239c2378cac8b9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Data/Lsp/Diagnostics.lean
a22bb4cd055b70384bd873bbc1d35dd21f9a3880
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
3,962
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity where | error | warning | information | hint deriving Inhabited, BEq instance : FromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | Except.ok 1 => DiagnosticSeverity.error | Except.ok 2 => DiagnosticSeverity.warning | Except.ok 3 => DiagnosticSeverity.information | Except.ok 4 => DiagnosticSeverity.hint | _ => throw "unknown DiagnosticSeverity"⟩ instance : ToJson DiagnosticSeverity := ⟨fun | DiagnosticSeverity.error => 1 | DiagnosticSeverity.warning => 2 | DiagnosticSeverity.information => 3 | DiagnosticSeverity.hint => 4⟩ inductive DiagnosticCode where | int (i : Int) | string (s : String) deriving Inhabited, BEq instance : FromJson DiagnosticCode := ⟨fun | num (i : Int) => DiagnosticCode.int i | str s => DiagnosticCode.string s | _ => throw "the diagnostic code can only be a string or an integer"⟩ instance : ToJson DiagnosticCode := ⟨fun | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag where | unnecessary | deprecated deriving Inhabited, BEq instance : FromJson DiagnosticTag := ⟨fun j => match j.getNat? with | Except.ok 1 => DiagnosticTag.unnecessary | Except.ok 2 => DiagnosticTag.deprecated | _ => throw "unknown DiagnosticTag"⟩ instance : ToJson DiagnosticTag := ⟨fun | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation where location : Location message : String deriving Inhabited, BEq, ToJson, FromJson structure Diagnostic where range : Range /-- extension: preserve semantic range of errors when truncating them for display purposes -/ fullRange : Range := range severity? : Option DiagnosticSeverity := none code? : Option DiagnosticCode := none source? : Option String := none message : String tags? : Option (Array DiagnosticTag) := none relatedInformation? : Option (Array DiagnosticRelatedInformation) := none deriving Inhabited, BEq, ToJson, FromJson structure PublishDiagnosticsParams where uri : DocumentUri version? : Option Int := none diagnostics: Array Diagnostic deriving Inhabited, BEq, ToJson, FromJson /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToDiagnostic (text : FileMap) (m : Message) : IO Diagnostic := do let low : Lsp.Position := text.leanPosToLspPos m.pos let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos let high : Lsp.Position := match m.endPos with | some endPos => /- Truncate messages that are more than one line long. This is a workaround to avoid big blocks of "red squiggly lines" on VS Code. TODO: should it be a parameter? -/ let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos text.leanPosToLspPos endPos | none => low let range : Range := ⟨low, high⟩ let fullRange : Range := ⟨low, fullHigh⟩ let severity := match m.severity with | MessageSeverity.information => DiagnosticSeverity.information | MessageSeverity.warning => DiagnosticSeverity.warning | MessageSeverity.error => DiagnosticSeverity.error let source := "Lean 4 server" let message ← m.data.toString pure { range := range fullRange := fullRange severity? := severity source? := source message := message } end Lsp end Lean
d8b38bf956a42299556d90f3ad8dc61398a685ff
e06332abb44b4720a102c91b393254505e242022
/chapter1.hlean
39296d8f55b0a376e2ed80a11e898b20800b7a6e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
11Kilobytes/hott-exercises-lean
69501ee7fef64cb8669384d4356d43941c75a702
a859755be688d3f22f14fbdfa35f5f5c32c438d3
refs/heads/master
1,611,265,681,636
1,455,643,818,000
1,455,643,818,000
48,048,788
1
1
null
1,455,643,819,000
1,450,190,626,000
Lean
UTF-8
Lean
false
false
15,081
hlean
-- Copyright 2015 Kabelo Moiloa -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. import algebra.ring import function open sigma open prod open eq section ex2 section sigma open sigma.ops variables {A : Type} {B : A → Type} {C : Type} (f : Π (a : A), B(a) → C) definition sigma_rec (p : Σ (x : A), B x) : C := f (pr₁ p) (pr₂ p) theorem sigma_comp (a : A) (p : B a) : sigma_rec f ⟨a, p⟩ = (f a p) := rfl end sigma section prod open prod.ops variables {A : Type} {B : Type} {C : Type} (f : A → B → C) definition prod_rec (p : A × B) : C := f (pr₁ p) (pr₂ p) definition prod_comp (a : A) (b : B) : prod_rec f (a, b) = (f a b) := rfl end prod end ex2 section ex3 section sigma open sigma.ops variables {A : Type} {B : A → Type} {C : (Σ (x : A), B x) → Type} (f : Π (a : A) (b : B a), C ⟨a, b⟩) definition sigma_ind (p : Σ (x : A), B x) : C p := (sigma.eta p) ▸ (f (pr₁ p) (pr₂ p)) theorem sigma_ind_comp (a : A) (b : B a) : sigma_ind f ⟨a, b⟩ = (f a b) := rfl end sigma section prod open prod.ops variables {A : Type} {B : Type} {C : A × B → Type} (f : Π (a : A) (b : B), C (a, b)) definition prod_ind (p : A × B) : C p := (prod.eta p) ▸ (f (pr₁ p) (pr₂ p)) definition prod_ind_comp (a : A) (b : B) : prod_ind f (a, b) = (f a b) := rfl end prod end ex3 open prod.ops open nat definition iter {C : Type} (c₀ : C) (cS : C → C) : ℕ → C | iter 0 := c₀ | iter (succ n) := cS (iter n) section ex4 variables {C : Type} (c₀ : C) (cS : ℕ → C → C) definition rec_pair : ℕ → ℕ × C := iter (0, c₀) (λ x, (succ (pr₁ x), cS (pr₁ x) (pr₂ x))) definition rec' (n : ℕ) : C := pr₂ (rec_pair c₀ cS n) theorem rec_comp₁ : rec' c₀ cS 0 = c₀ := rfl lemma rec_pr₁ (n : ℕ) : pr₁ (rec_pair c₀ cS n) = n := nat.rec_on n (show pr₁ (rec_pair c₀ cS 0) = 0, from rfl) (take n, assume IH : pr₁ (rec_pair c₀ cS n) = n, show (pr₁ (rec_pair c₀ cS (succ n)) = (succ n)), from calc pr₁ (rec_pair c₀ cS (succ n)) = pr₁ (succ (pr₁ (rec_pair c₀ cS n)), _) : rfl ... = succ (pr₁ (rec_pair c₀ cS n)) : rfl ... = succ n : ap succ IH) theorem rec_comp₂ (n : ℕ) : rec' c₀ cS (succ n) = cS n (rec' c₀ cS n) := nat.rec_on n (show rec' c₀ cS (succ 0) = cS 0 (rec' c₀ cS 0), from rfl) (take n, assume IH : rec' c₀ cS (succ n) = cS n (rec' c₀ cS n), show rec' c₀ cS (succ (succ n)) = cS (succ n) (rec' c₀ cS (succ n)), from calc rec' c₀ cS (succ (succ n)) = pr₂ (rec_pair c₀ cS (succ (succ n))) : rfl ... = cS (pr₁ (rec_pair c₀ cS (succ n))) (pr₂ (rec_pair c₀ cS (succ n))) : rfl ... = cS (succ n) (pr₂ (rec_pair c₀ cS (succ n))) : { rec_pr₁ c₀ cS (succ n) } ... = cS (succ n) (rec' c₀ cS (succ n)) : { IH }) end ex4 namespace ex5 open sigma.ops bool definition union.{u v} (A : Type.{u}) (B : Type.{v}) : Type.{max u v} := Σ (x : bool), (bool.rec_on x (lift A) (lift B)) infix ` +₂ `:65 := union variables {A : Type} {B : Type} definition inl (a : A) : A +₂ B := ⟨ff, (lift.up a)⟩ definition inr (b : B) : A +₂ B := ⟨tt, (lift.up b)⟩ variables {C : A +₂ B → Type} (rec_l : Π (a : A), C (inl a)) (rec_r : Π (b : B), C (inr b)) definition union_ind : Π (x : A +₂ B), C x | union_ind ⟨ff, a⟩ := (lift.up_down a) ▸ (rec_l (lift.down a)) | union_ind ⟨tt, b⟩ := (lift.up_down b) ▸ (rec_r (lift.down b)) theorem union_comp₁ (a : A) : (union_ind rec_l rec_r (inl a)) = (rec_l a) := by reflexivity theorem union_comp₂ (b : B) : (union_ind rec_l rec_r (inr b)) = (rec_r b) := by reflexivity end ex5 section ex6 open sigma.ops bool definition product.{u v} (A : Type.{u}) (B : Type.{v}) : Type.{max u v} := Π (x : bool), (bool.rec_on x (lift A) (lift B)) infix ` ×₂ `:65 := product variables {A : Type} {B : Type} definition make_pair (a : A) (b : B) : A ×₂ B := (bool.rec (lift.up a) (lift.up b)) definition proj₁ (p : A ×₂ B) : A := (lift.down (p ff)) definition proj₂ (p : A ×₂ B) : B := (lift.down (p tt)) definition product_eta (p : A ×₂ B) : (make_pair (proj₁ p) (proj₂ p)) = p := eq_of_homotopy (take x : bool, match x with | tt := !lift.up_down | ff := !lift.up_down end) variables {C : A ×₂ B → Type} (f : Π (a : A) (b : B), C (make_pair a b)) definition product_ind (p : A ×₂ B) : C p := (product_eta p) ▸ (f (proj₁ p) (proj₂ p)) definition product_comp (a : A) (b : B) : (product_ind f (make_pair a b)) = (f a b) := assert p : (λ x, bool.rec_on x rfl rfl) = (λ x, refl (make_pair a b x)), from eq_of_homotopy (bool.rec rfl rfl), calc product_ind f (make_pair a b) = eq_of_homotopy (λ x, bool.rec_on x rfl rfl) ▸ f a b : rfl ... = transport C (eq_of_homotopy (λ x, rfl)) (f a b) : by rewrite p ... = refl (make_pair a b) ▸ f a b : by rewrite eq_of_homotopy_idp ... = f a b : rfl end ex6 section ex7 open sigma.ops variables {A : Type} (a : A) {P : Π (x : A), a = x → Type} {d : P a (refl a)} definition contr_components (x y : A) (p : x = y) : ⟨x, (refl x)⟩ = ⟨y, p⟩ := eq.rec_on' p (λ a, rfl) definition contr_path_space (a : A) (s : Σ (y : A), a = y) : ⟨a, (refl a)⟩ = s := (sigma.eta s) ▸ contr_components a (pr₁ s) (pr₂ s) definition eq_ind (x : A) (p : a = x) : P x p := transport (λ s, P (pr₁ s) (pr₂ s)) (contr_path_space a ⟨x, p⟩) d definition eq_comp : eq_ind a a (refl a) = a := rfl end ex7 section ex8 open nat definition exp : ℕ → ℕ → ℕ | exp x 0 := 1 | exp x (succ n) := x * exp x n definition exp' : ℕ → ℕ → ℕ := function.flip (nat.rec (λ n, 1) (λ n f x, x * f x)) theorem add_zero (a : ℕ) : a + 0 = a := rfl theorem zero_add (a : ℕ) : 0 + a = a := nat.rec_on a (show 0 + 0 = 0, from rfl) (take a, assume IH : 0 + a = a, show 0 + (succ a) = (succ a), from calc 0 + (succ a) = (succ (0 + a)) : rfl ... = (succ a) : ap succ IH) theorem add_assoc (a b c : ℕ) : (a + b) + c = a + (b + c) := nat.rec_on c (show (a + b) + 0 = a + (b + 0), from rfl) (take n, assume IH : (a + b) + n = a + (b + n), show (a + b) + (succ n) = a + (b + (succ n)), from calc (a + b) + (succ n) = succ ((a + b) + n) : rfl ... = succ (a + (b + n)) : ap succ IH ... = a + (succ (b + n)) : rfl ... = a + (b + (succ n)) : rfl) theorem one_add (a : ℕ) : (succ a) = 1 + a := nat.rec_on a (show (succ 0) = 1 + 0, from rfl) (take a, assume IH : (succ a) = 1 + a, show (succ (succ a)) = 1 + (succ a), from calc (succ (succ a)) = (succ a) + 1 : rfl ... = (1 + a) + 1 : { IH } ... = 1 + (a + 1) : add_assoc 1 a 1 ... = 1 + (succ a) : rfl) theorem add_comm (a b : ℕ) : a + b = b + a := nat.rec_on b (show a + 0 = 0 + a, from (zero_add a)⁻¹) (take b, assume IH : a + b = b + a, show a + (succ b) = (succ b) + a, from calc a + (succ b) = (succ (a + b)) : rfl ... = (succ (b + a)) : ap succ IH ... = 1 + (b + a) : one_add (b + a) ... = (1 + b) + a : add_assoc 1 b a ... = (succ b) + a : { (one_add b)⁻¹ }) theorem one_mul (a : ℕ) : 1 * a = a := nat.rec_on a (show 1 * 0 = 0, from rfl) (take a, assume IH : 1 * a = a, show 1 * (succ a) = (succ a), from calc 1 * (succ a) = (1 * a) + 1 : rfl ... = a + 1 : { IH } ... = (succ a) : rfl) theorem mul_one (a : ℕ) : a * 1 = a := calc a * 1 = (a * 0) + a : rfl ... = 0 + a : rfl ... = a : zero_add a theorem zero_mul (a : ℕ) : 0 * a = 0 := nat.rec_on a (show 0 * 0 = 0, from rfl) (take a, assume IH : 0 * a = 0, show 0 * (succ a) = 0, from calc 0 * (succ a) = 0 * a + 0 : rfl ... = 0 + 0 : { IH } ... = 0 : rfl) theorem mul_zero (a : ℕ) : a * 0 = 0 := rfl theorem right_distrib (a b c : ℕ) : (a + b) * c = a * c + b * c := nat.rec_on c (show (a + b) * 0 = a * 0 + b * 0, from rfl) (take c, assume IH : (a + b) * c = a * c + b * c, show (a + b) * (succ c) = a * (succ c) + b * (succ c), from calc (a + b) * (succ c) = ((a + b) * c) + (a + b) : rfl ... = (a * c + b * c) + (a + b) : { IH } ... = a * c + (b * c + (a + b)) : { add_assoc (a * c) (b * c) (a + b) } ... = a * c + (b * c + (b + a)) : { add_comm a b } ... = a * c + ((b * c + b) + a) : { (add_assoc (b * c) b a)⁻¹ } ... = a * c + (b * (succ c) + a) : rfl ... = a * c + (a + b * (succ c)) : { add_comm (b * (succ c)) a } ... = (a * c + a) + b * (succ c) : (add_assoc (a * c) a (b * (succ c)))⁻¹ ... = a * (succ c) + b * (succ c) : rfl) lemma succ_mul (a b : ℕ) : (succ a) * b = a * b + b := nat.rec_on b (show (succ a) * 0 = a * 0 + 0, from rfl) (take b, assume IH : (succ a) * b = a * b + b, show (succ a) * (succ b) = a * (succ b) + (succ b), from calc (succ a) * (succ b) = (succ a) * b + (succ a) : rfl ... = (a * b + b) + (succ a) : { IH } ... = a * b + (b + (succ a)) : add_assoc (a * b) b (succ a) ... = a * b + (b + (1 + a)) : { one_add a } ... = a * b + ((b + 1) + a) : { (add_assoc b 1 a)⁻¹ } ... = a * b + ((succ b) + a) : rfl ... = a * b + (a + (succ b)) : { add_comm (succ b) a } ... = (a * b + a) + (succ b) : (add_assoc (a * b) a (succ b))⁻¹ ... = a * (succ b) + (succ b) : rfl) theorem mul_comm (a b : ℕ) : a * b = b * a := nat.rec_on b (show a * 0 = 0 * a, from calc a * 0 = 0 : rfl ... = 0 * a : (zero_mul a)⁻¹) (take b, assume IH : a * b = b * a, show a * (succ b) = (succ b) * a, from calc a * (succ b) = a * b + a : rfl ... = b * a + a : { IH } ... = (succ b) * a : (succ_mul b a)⁻¹) theorem left_distrib (a b c : ℕ) : a * (b + c) = a * b + a * c := nat.rec_on c (show a * (b + 0) = a * b + a * 0, by reflexivity) (take c, assume IH : a * (b + c) = a * b + a * c, show a * (b + (succ c)) = a * b + a * (succ c), from calc a * (b + (succ c)) = a * (succ (b + c)) : rfl ... = a * (b + c) + a : rfl ... = (a * b + a * c) + a : { IH } ... = a * b + (a * c + a) : add_assoc (a * b) (a * c) a ... = a * b + a * (succ c) : rfl) theorem mul_assoc (a b c : ℕ) : (a * b) * c = a * (b * c) := nat.rec_on c (show (a * b) * 0 = a * (b * 0), by reflexivity) (take c, assume IH : (a * b) * c = a * (b * c), show (a * b) * (succ c) = a * (b * (succ c)), from calc (a * b) * (succ c) = (a * b) * c + a * b : rfl ... = a * (b * c) + a * b : { IH } ... = a * ((b * c) + b) : { (left_distrib a (b * c) b)⁻¹ } ... = a * (b * (succ c)) : rfl) definition semiring := {| algebra.semiring ℕ, is_hset_carrier := is_set_of_decidable_eq, add := add, mul := mul, zero := 0, add_zero := add_zero, zero_add := zero_add, add_comm := add_comm, add_assoc := add_assoc, one_mul := one_mul, mul_one := mul_one, zero_mul := zero_mul, mul_zero := mul_zero, left_distrib := left_distrib, right_distrib := right_distrib, mul_assoc := mul_assoc |} end ex8 section ex9 definition less_than (x : ℕ) (y : ℕ) := Σ (d : ℕ), x + (succ d) = y notation x `<₂` y := less_than x y definition Fin (n : ℕ) := Σ (x : ℕ), x <₂ n definition fmax : Π (n : ℕ), Fin (succ n) | fmax 0 := ⟨0, ⟨0, rfl⟩⟩ | fmax (succ n) := ⟨n, ⟨1, rfl⟩⟩ end ex9 section ex10 definition ack : ℕ → ℕ → ℕ := nat.rec (λ n, succ n) (λ m ackₘ, nat.rec (ackₘ 1) (λ n ackₛₘn, ackₘ ackₛₘn)) theorem comp₁ (n : ℕ) : ack 0 n = succ n := rfl theorem comp₂ (m : ℕ) : ack (succ m) 0 = ack m 1 := rfl theorem comp₃ (m n : ℕ) : ack (succ m) (succ n) = ack m (ack (succ m) n) := rfl end ex10 section ex11 definition dn_not {A : Type} (not³A : ¬¬¬A) : ¬A := (suppose a : A, have ¬¬A, from (suppose notA : ¬A, notA a), not³A this) end ex11 section ex12 definition B_implies_A_of_A {A B C : Type} (a : A) : B → A := (take b, show A, from a) definition not_not_A_of_A {A : Type} (a : A) : ¬¬A := (suppose notA : ¬A, notA a) theorem dm {A B : Type} (p : (¬A) + (¬B)) : ¬(A × B) := assume q, obtain (a b), from q, sum.cases_on p (assume notA, notA a) (assume notB, notB b) end ex12 section ex13 theorem not_not_dn {P : Type} : ¬¬(P + (¬P)) := assume notDecP : ¬(P + (¬P)), assert decP : P + (¬P), from sum.inr (assume p : P, notDecP (sum.inl p)), notDecP decP end ex13 section ex14 theorem indiscernibility {A : Type} {C : A → Type} {x y : A} (p : x = y) : C(x) → C(y) := eq.rec_on p id end ex14
acf3cff3731cbee04170e323cb95aed7e3da047c
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex22.lean
74f6c4efc599ea98a5fcdc8c73003639f418e07e
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
329
lean
namespace hide universe variable u constant list : Type u → Type u constant cons : Π A : Type u, A → list A → list A constant nil : Π A : Type u, list A constant head : Π A : Type u, list A → A constant tail : Π A : Type u, list A → list A constant append : Π A : Type u, list A → list A → list A end hide
0d143238407b64666a0721fdef41729503408d1a
be853a09b5de8ba4d9114bd8a816647b584d4573
/src/submissions/practice_2.lean
a72c67d9246ebe831a3b7882e5258854782f8677
[]
no_license
sgoldberg02/cs2120f21mycopy
4a665a92c5dcbb5b35be5461c42268c74366e3fa
216fa0a813508d82594ac95aec0a048249f81291
refs/heads/main
1,692,136,103,389
1,632,328,880,000
1,632,328,880,000
405,192,256
0
0
null
null
null
null
UTF-8
Lean
false
false
11,954
lean
/- Prove the following simple logical conjectures. Give a formal and an English proof of each one. Your English language proofs should be complete in the sense that they identify all the axioms and/or theorems that you use. -/ example : true := true.intro -- example : false := _ -- trick question? why? example : ∀ (P : Prop), P ∨ P ↔ P := begin assume P, apply iff.intro _ _, assume pp, cases pp, exact pp, exact pp, assume p, exact (or.intro_left P p), end /- Assume that we have a proposition P. Since we are trying to prove P ∨ P ↔ P, it suffices to prove P ∨ P → P and P → P ∨ P. To prove P ∨ P → P, assume that P ∨ P is true. Then, we have two cases. In the first case, P is true, which is exactly what we are trying to prove. In the second case, P is true, which is exactly what we are trying to prove. To prove P → P ∨ P, assume that P is true. Then, since it suffices to prove just the left side of P ∨ P, we are done because that is exactly P. -/ example : ∀ (P : Prop), P ∧ P ↔ P := begin assume P, apply iff.intro _ _, assume pp, exact (and.elim_right pp), assume p, exact (and.intro p p), end /- Assume that we have a proposition P. Since we are trying to prove P ∧ P ↔ P, it suffices to prove P ∧ P → P and P → P ∧ P via the introduction rule for iff. To prove P ∧ P → P, assume P ∧ P is true. Then, because P is what we want to prove and this is exactly the right side of P ∧ P, we are done. To prove P → P ∧ P, assume P is true. Because we have a proof of P ∧ P from knowing P is true using the introduction rule for and, and this is exactly a proof of our proposition P ∧ P, we are done. -/ example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P := begin assume P, assume Q, apply iff.intro _ _, assume pq, cases pq, exact (or.inr pq), exact (or.inl pq), assume pq, cases pq, exact (or.inr pq), exact (or.inl pq), end /- Assume we have propositions P and Q. Since we are trying to prove P ∧ Q ↔ Q ∧ P, it suffices to show P ∨ Q → Q ∨ P and Q ∨ P → P ∨ Q. To show P ∨ Q → Q ∨ P, we assume P ∨ Q is true. We have two cases. In the first case, P is true, so that we are done because this is exactly the right side of Q ∨ P. In the second case, Q is true, so that we are done because this is exactly the left side of Q ∨ P. To show Q ∨ P → P ∨ Q, we assume Q ∨ P is true. We have two cases. In the first case, Q is true, so that we are done because this is exactly the right side of P ∨ Q. In the second case, P is true, so that we are done because this is exactly the left side of P ∨ Q. -/ example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P := begin assume P Q, apply iff.intro _ _, assume pq, apply and.intro _ _, exact (and.elim_right pq), exact (and.elim_left pq), assume pq, apply and.intro _ _, exact (and.elim_right pq), exact (and.elim_left pq), end /- Assume we have propositions P Q. Since we wish to show P ∧ Q ↔ Q ∧ P, it suffices to show that P ∧ Q → Q ∧ P and Q ∧ P → P ∧ Q. To show P ∧ Q → Q ∧ P, assume P ∧ Q is true. Then, it suffices to prove Q and P seperately. To prove Q, we are done because this is exactly the right side of P ∧ Q. To prove P, we are done because this is exactly the left side of P ∧ Q. To prove Q ∧ P → P ∧ Q, assume Q ∧ P is true. Then, it suffices to prove P and Q seprately. To prove P, we are done because this is exactly the right side of Q ∧ P. To prove Q, we are done because this is exactly the left side of Q ∧ P. -/ example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin assume P Q R, apply iff.intro _ _, assume pqr, have p : P := and.elim_left pqr, have qr : Q ∨ R := and.elim_right pqr, cases qr, have pq : P ∧ Q := and.intro p qr, exact (or.inl pq), have pr : P ∧ R := and.intro p qr, exact (or.inr pr), assume pqpr, cases pqpr, apply and.intro _ _, exact (and.elim_left pqpr), have q : Q := and.elim_right pqpr, exact (or.inl q), apply and.intro _ _, exact (and.elim_left pqpr), have r : R := and.elim_right pqpr, exact (or.inr r), end /- Assume we have propositions P Q and R. Since we want to prove P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R), it suffices to show P ∧ (Q ∨ R) → (P ∧ Q) ∨ (P ∧ R) and (P ∧ Q) ∨ (P ∧ R) → P ∧ (Q ∨ R). to prove P ∧ (Q ∨ R) → (P ∧ Q) ∨ (P ∧ R), assume P ∧ (Q ∨ R) is true. Then, we have a proof of P and a proof of Q ∨ R. For our proof of Q ∨ R, we have two cases. In the first case, Q is true, so that we have a proof of P ∧ Q and are done because that is precisely the left hand side of (P ∧ Q) ∨ (P ∧ R). In the second case of Q ∨ R, we have a proof of R, so that we have a proof of P ∧ R and are done because that is precisely the right hand side of (P ∧ Q) ∨ (P ∧ R). To prove (P ∧ Q) ∨ (P ∧ R) → P ∧ (Q ∨ R), assume we have a proof of (P ∧ Q) ∨ (P ∧ R) → P ∧ (Q ∨ R). Then, we have two cases. In the first case, P ∧ Q is true. It suffices to prove P and Q ∨ R seprately. To see why P is true, we are done because this is precisely the left side of P ∧ Q. Now, we obtain a proof that Q is true from the proof of P ∧ Q, so that we are done because this is precisely the left side of P ∨ Q. In the second case, P ∧ R is true. It suffices to prove P and Q ∨ R seprately. To see why P is true, we are done because this is exactly the left side of P ∧ R. Now, we obtain of proof of R from the right side of P ∧ R and are done because this is precisely the right side of Q ∨ R. -/ example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin assume P Q R, apply iff.intro _ _, assume pqr, cases pqr, apply and.intro _ _, exact (or.inl pqr), exact (or.inl pqr), have q : Q := and.elim_left pqr, have r : R := and.elim_right pqr, apply and.intro _ _, exact (or.inr q), exact (or.inr r), assume pqpr, have pq : P ∨ Q := and.elim_left pqpr, have pr : P ∨ R := and.elim_right pqpr, cases pq, exact (or.inl pq), cases pr, exact (or.inl pr), have qr : Q ∧ R := and.intro pq pr, exact (or.inr qr), end /- Assume we have propositions P Q R. Since we wish to prove P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R), we can just show P ∨ (Q ∧ R) → (P ∨ Q) ∧ (P ∨ R) and (P ∨ Q) ∧ (P ∨ R) → P ∨ (Q ∧ R). To see why P ∨ (Q ∧ R) → (P ∨ Q) ∧ (P ∨ R) is true, assume P ∨ ( Q ∧ R) is true. Then, we have two cases. In the first case, P is true. To prove (P ∨ Q) ∧ (P ∨ R) is true, we prove P ∨ Q and P ∨ R separately. To see why P ∨ Q is true, we are done because its left side is exactly P, which we have a proof of. To see why P ∨ R is true, we are done because its left side is exactly P, which we have a proof of. To see why (P ∨ Q) ∧ (P ∨ R) → P ∨ (Q ∧ R) is true, assume (P ∨ Q) ∧ (P ∨ R). Now we have a proof of P ∨ Q and P ∨ R. In the first case of P ∨ Q, P is true, so that we are done because this is the left side of P ∨ (Q ∧ R). In the second case of P ∨ Q, Q is true. Now, in the first case of P ∨ R, P is true, so that we are done because this is the left side of P ∨ (Q ∧ R). In the second case of P ∨ R, R is true so that we have a proof of Q ∧ R, and thus we are done because this is the right side of P ∨ (Q ∧ R). -/ example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := begin assume P, assume Q, apply iff.intro _ _, assume ppq, exact (and.elim_left ppq), assume p, apply and.intro _ _, exact p, exact (or.inl p), end /- Assume we have propositions P and Q. Since we want to prove P ∧ (P ∨ Q) ↔ P, it suffices to show P ∧ (P ∨ Q) → P and P → P ∧ (P ∨ Q). To see why P ∧ (P ∨ Q) → P, assume we have a proof of P ∧ (P ∨ Q), so that we are done because P is exactly the right hand side of P ∧ (P ∨ Q). To see why P → P ∧ (P ∨ Q) is true, we assume we have a proof of P. Now, we can prove P and (P ∨ Q) separately. To see why P is true, we are done beause we have a proof of P. To see why P ∨ Q is true, we are done because its left side is exactly P, which we have a proof of. -/ example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := begin assume P, assume Q, apply iff.intro _ _, assume ppq, cases ppq, exact ppq, exact (and.elim_left ppq), assume p, exact (or.inl p), end /- Assume we have propositions P and Q. To see why P ∨ (P ∧ Q) ↔ P is true, it suffices to prove P ∨ (P ∧ Q) → P and P → P ∨ (P ∧ Q). To see why P ∨ (P ∧ Q) → P is true, assume we have a proof of P ∨ (P ∧ Q). Now, we have two cases. In the first case, P is true, so that we are done because P is what we want to prove. In the second case, P ∧ Q is true, so that we are done because P is exactly the left hand side of P ∧ Q. To see why P → P ∨ (P ∧ Q), we assume P is true, and then are done because this is exactly the left side of P ∨ (P ∧ Q). -/ example : ∀ (P : Prop), P ∨ true ↔ true := begin assume P, apply iff.intro _ _, assume pt, apply true.intro, assume t, exact (or.inr t), end /- Assume we have a proposition P. To see why P ∨ true ↔ true is true, we prove P ∨ true → true and true → P ∨ true. To see why P ∨ true → true is true, assume P ∨ true is true. Then, we apply the fact that we know true is true. To see why true → P ∨ true, we assume we have a proof of t. Then, we are done because we have a proof for the right side of P ∨ true. -/ example : ∀ (P : Prop), P ∨ false ↔ P := begin assume P, apply iff.intro _ _, assume pf, cases pf, exact pf, have pp : ¬ P ∧ P := false.elim pf, exact (and.elim_right pp), assume p, exact (or.inl p), end /- Assume we have a proposition P. To see why P ∨ false ↔ P is true, it suffices to prove P ∨ false → P and P → P ∨ false. To see why P ∨ false → P is true, assume P ∨ false is true. Then, we haave two cases. In the first case, we are done because we have a proof for P. In the second case, we obtain a proof of ¬ P ∧ P from the fact that we have assumed false. Now, we are done because P is exactly the right side of ¬ P ∧ P. To see why P → P ∨ false, assume P is true. Then, we have are done because we have a proof of the left side of P ∨ false. -/ example : ∀ (P : Prop), P ∧ true ↔ P := begin assume P, apply iff.intro _ _, assume pt, exact (and.elim_left pt), assume p, apply and.intro _ _, exact p, apply true.intro, end /- Assume we have a proposition P. To see why P ∧ true ↔ P, it suffices to prove P ∧ true → P and P → P ∧ true. To see why P ∧ true → P, we are done because P is the left side of P ∧ true. To see why P → P ∧ true, we assume P is true and then prove P and true separately. To see why P is true, we are done because we have a proof of P. To see why true is true, we are done because we know true is true. -/ example : ∀ (P : Prop), P ∧ false ↔ false := begin assume P, apply iff.intro, assume pf, exact (and.elim_right pf), assume f, apply and.intro _ _, have pp : ¬ P ∧ P := false.elim f, exact (and.elim_right pp), exact f, end /- Assume we have a propositio P. To see why P ∧ false ↔ false is true, we prove P ∧ false → false and false → P ∧ false. To see why P ∧ false → false is true, we assume P ∧ false is true. Then, we have prove false because it is the right side of P ∧ false. To see why false → P ∧ false, we assume false and prove P and false separately. To prove P, we can get a proof of ¬ P ∧ P from false. Now, we have a proof of P from the right side of ¬ P ∧ P. To see prove false, we are done because we already have a proof of false. -/
132be342f5d5aa7af357af3cb56ac160ca154780
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/expr_maps.lean
7f10f3c69e11e9b41e5cdf664d7e48366364d22b
[ "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,931
lean
import Lean.Expr open Lean def exprType : Expr := mkSort levelOne def biDef := BinderInfo.default def exprNat := mkConst `Nat [] -- Type -> Type def TypeArrowType := mkForall `α biDef exprType exprType -- Type -> Type def TypeArrowType2 := mkForall `β biDef exprType exprType -- fun (x : Nat) => x def exprT1 := mkLambda `x biDef exprNat (mkBVar 0) -- fun (y : Nat) => x def exprT2 := mkLambda `y biDef exprNat (mkBVar 0) -- fun (x : Nat) => (f x) def exprT3 := mkLambda `x biDef exprNat (mkApp (mkConst `f []) (mkBVar 0)) -- fun (x : Nat) => (f x) def exprT4 := mkLambda `x BinderInfo.implicit exprNat (mkApp (mkConst `f []) (mkBVar 0)) def check (b : Bool) : IO Unit := unless b do throw $ IO.userError "failed" def tst1 : IO Unit := do IO.println TypeArrowType; IO.println exprT1; IO.println exprT2; IO.println exprT3; IO.println exprT4; check (TypeArrowType == TypeArrowType2); check (ExprStructEq.mk TypeArrowType != ExprStructEq.mk TypeArrowType2); check (!Expr.equal TypeArrowType TypeArrowType2); check (exprT1 == exprT2); check (ExprStructEq.mk exprT1 != ExprStructEq.mk exprT2); check (ExprStructEq.mk exprT1 == ExprStructEq.mk exprT1); check (exprT3 == exprT4); check (ExprStructEq.mk exprT3 != ExprStructEq.mk exprT4); pure () #eval tst1 def tst2 : IO Unit := do let m1 : ExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst2 def tst3 : IO Unit := do let m1 : ExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst3 def tst4 : IO Unit := do let m1 : PersistentExprMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == some 10); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT3 == some 20); IO.println (m1.find? exprT1); pure () #eval tst4 def tst5 : IO Unit := do let m1 : PersistentExprStructMap Nat := {}; let m1 := m1.insert exprT1 10; check (m1.find? exprT1 == some 10); check (m1.find? exprT2 == none); check (m1.find? exprT3 == none); let m1 := m1.insert exprT4 20; check (m1.find? exprT1 == some 10); check (m1.find? exprT4 == some 20); check (m1.find? exprT3 == none); IO.println (m1.find? exprT1); pure () #eval tst5
92c7654055f57f9f9696827668f9bda01098b23b
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/system/io.lean
a21992dde37f13f8406257de8a8daa2baf664cf0
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
9,114
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ import system.io_interface /- The following constants have a builtin implementation -/ constant io_core : Type → Type → Type /- Auxiliary definition used in the builtin implementation of monad_io_random_impl -/ def io_rand_nat : std_gen → nat → nat → nat × std_gen := rand_nat @[instance] constant monad_io_impl : monad_io io_core @[instance] constant monad_io_terminal_impl : monad_io_terminal io_core @[instance] constant monad_io_net_system_impl : monad_io_net_system io_core @[instance] constant monad_io_file_system_impl : monad_io_file_system io_core @[instance] meta constant monad_io_serial_impl : monad_io_serial io_core @[instance] constant monad_io_environment_impl : monad_io_environment io_core @[instance] constant monad_io_process_impl : monad_io_process io_core @[instance] constant monad_io_random_impl : monad_io_random io_core instance io_core_is_monad (e : Type) : monad (io_core e) := monad_io_is_monad io_core e instance io_core_is_monad_fail : monad_fail (io_core io.error) := monad_io_is_monad_fail io_core instance io_core_is_alternative : alternative (io_core io.error) := monad_io_is_alternative io_core @[reducible] def io (α : Type) := io_core io.error α namespace io /- Remark: the following definitions can be generalized and defined for any (m : Type -> Type -> Type) that implements the required type classes. However, the generalized versions are very inconvenient to use, (example: `#eval io.put_str "hello world"` does not work because we don't have enough information to infer `m`.). -/ def iterate {e α} (a : α) (f : α → io_core e (option α)) : io_core e α := monad_io.iterate e α a f def forever {e} (a : io_core e unit) : io_core e unit := iterate () $ λ _, a >> return (some ()) -- TODO(Leo): delete after we merge #1881 def catch {e₁ e₂ α} (a : io_core e₁ α) (b : e₁ → io_core e₂ α) : io_core e₂ α := monad_io.catch e₁ e₂ α a b def finally {α e} (a : io_core e α) (cleanup : io_core e unit) : io_core e α := do res ← catch (sum.inr <$> a) (return ∘ sum.inl), cleanup, match res with | sum.inr res := return res | sum.inl error := monad_io.fail _ _ error end protected def fail {α : Type} (s : string) : io α := monad_io.fail _ _ (io.error.other s) def put_str : string → io unit := monad_io_terminal.put_str def put_str_ln (s : string) : io unit := put_str s >> put_str "\n" def get_line : io string := monad_io_terminal.get_line def cmdline_args : io (list string) := return (monad_io_terminal.cmdline_args io_core) def print {α} [has_to_string α] (s : α) : io unit := put_str ∘ to_string $ s def print_ln {α} [has_to_string α] (s : α) : io unit := print s >> put_str "\n" def handle : Type := monad_io.handle io_core def mk_file_handle (s : string) (m : mode) (bin : bool := ff) : io handle := monad_io_file_system.mk_file_handle s m bin def stdin : io handle := monad_io_file_system.stdin def stderr : io handle := monad_io_file_system.stderr def stdout : io handle := monad_io_file_system.stdout meta def serialize : handle → expr → io unit := monad_io_serial.serialize meta def deserialize : handle → io expr := monad_io_serial.deserialize namespace env def get (env_var : string) : io (option string) := monad_io_environment.get_env env_var /-- get the current working directory -/ def get_cwd : io string := monad_io_environment.get_cwd /-- set the current working directory -/ def set_cwd (cwd : string) : io unit := monad_io_environment.set_cwd cwd end env namespace net def socket : Type := monad_io_net_system.socket io_core def listen : string → nat → io socket := monad_io_net_system.listen def accept : socket → io socket := monad_io_net_system.accept def connect : string → io socket := monad_io_net_system.connect def recv : socket → nat → io char_buffer := monad_io_net_system.recv def send : socket → char_buffer → io unit := monad_io_net_system.send def close : socket → io unit := monad_io_net_system.close end net namespace fs def is_eof : handle → io bool := monad_io_file_system.is_eof def flush : handle → io unit := monad_io_file_system.flush def close : handle → io unit := monad_io_file_system.close def read : handle → nat → io char_buffer := monad_io_file_system.read def write : handle → char_buffer → io unit := monad_io_file_system.write def get_char (h : handle) : io char := do b ← read h 1, if h : b.size = 1 then return $ b.read ⟨0, h.symm ▸ nat.zero_lt_one⟩ else io.fail "get_char failed" def get_line : handle → io char_buffer := monad_io_file_system.get_line def put_char (h : handle) (c : char) : io unit := write h (mk_buffer.push_back c) def put_str (h : handle) (s : string) : io unit := write h (mk_buffer.append_string s) def put_str_ln (h : handle) (s : string) : io unit := put_str h s >> put_str h "\n" def read_to_end (h : handle) : io char_buffer := iterate mk_buffer $ λ r, do done ← is_eof h, if done then return none else do c ← read h 1024, return $ some (r ++ c) def read_file (s : string) (bin := ff) : io char_buffer := do h ← mk_file_handle s io.mode.read bin, read_to_end h def file_exists : string → io bool := monad_io_file_system.file_exists def dir_exists : string → io bool := monad_io_file_system.dir_exists def remove : string → io unit := monad_io_file_system.remove def rename : string → string → io unit := monad_io_file_system.rename def mkdir (path : string) (recursive : bool := ff) : io bool := monad_io_file_system.mkdir path recursive def rmdir : string → io bool := monad_io_file_system.rmdir end fs namespace proc def child : Type := monad_io_process.child io_core def child.stdin : child → handle := monad_io_process.stdin def child.stdout : child → handle := monad_io_process.stdout def child.stderr : child → handle := monad_io_process.stderr def spawn (p : io.process.spawn_args) : io child := monad_io_process.spawn p def wait (c : child) : io nat := monad_io_process.wait c def sleep (n : nat) : io unit := monad_io_process.sleep n end proc def set_rand_gen : std_gen → io unit := monad_io_random.set_rand_gen def rand (lo : nat := std_range.1) (hi : nat := std_range.2) : io nat := monad_io_random.rand lo hi end io meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a) /-- Run the external process specified by `args`. The process will run to completion with its output captured by a pipe, and read into `string` which is then returned. -/ def io.cmd (args : io.process.spawn_args) : io string := do child ← io.proc.spawn { stdout := io.process.stdio.piped, ..args }, buf ← io.fs.read_to_end child.stdout, io.fs.close child.stdout, exitv ← io.proc.wait child, when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ repr exitv, return buf.to_string /-- This is the "back door" into the `io` monad, allowing IO computation to be performed during tactic execution. For this to be safe, the IO computation should be ideally free of side effects and independent of its environment. This primitive is used to invoke external tools (e.g., SAT and SMT solvers) from a tactic. IMPORTANT: this primitive can be used to implement `unsafe_perform_io {α : Type} : io α → option α` or `unsafe_perform_io {α : Type} [inhabited α] : io α → α`. This can be accomplished by executing the resulting tactic using an empty `tactic_state` (we have `tactic_state.mk_empty`). If `unsafe_perform_io` is defined, and used to perform side-effects, users need to take the following precautions: - Use `@[noinline]` attribute in any function to invokes `tactic.unsafe_perform_io`. Reason: if the call is inlined, the IO may be performed more than once. - Set `set_option compiler.cse false` before any function that invokes `tactic.unsafe_perform_io`. This option disables common subexpression elimination. Common subexpression elimination might combine two side effects that were meant to be separate. TODO[Leo]: add `[noinline]` attribute and option `compiler.cse`. -/ meta constant tactic.unsafe_run_io {α : Type} : io α → tactic α /-- Execute the given tactic with a tactic_state object that contains: - The current environment in the virtual machine. - The current set of options in the virtual machine. - Empty metavariable and local contexts. - One single goal of the form `⊢ true`. This action is mainly useful for writing tactics that inspect the environment. -/ meta constant io.run_tactic {α : Type} (a : tactic α) : io α
5a9b768693ac897b8bc505b6f69a26b928442418
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Init/Control.lean
d2aa8404f894f7ccd13744f40275a4481fc962b8
[ "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
606
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.Control.Applicative import Init.Control.Functor import Init.Control.Alternative import Init.Control.Monad import Init.Control.MonadLift import Init.Control.MonadFunctor import Init.Control.MonadRun import Init.Control.MonadControl import Init.Control.State import Init.Control.StateRef import Init.Control.Id import Init.Control.Except import Init.Control.Reader import Init.Control.Option import Init.Control.Conditional
cb4d1cf88e3c8c152b540d4071d9b479edac60b8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Deriving/Hashable.lean
b1b57872973fa7b3a3122eaa3d89101ff994b461
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,592
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Lean.Meta.Inductive import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.Hashable open Command open Lean.Parser.Term open Meta def mkHashableHeader (indVal : InductiveVal) : TermElabM Header := do mkHeader `Hashable 1 indVal def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) : TermElabM Term := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do let mut alts := #[] let mut ctorIdx := 0 let allIndVals := indVal.all.toArray for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let alt ← forallTelescopeReducing ctorInfo.type fun xs _ => do let mut patterns := #[] -- add `_` pattern for indices for _ in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs := #[] let mut rhs ← `($(quote ctorIdx)) -- add `_` for inductive parameters, they are inaccessible for _ in [:indVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i]! let a := mkIdent (← mkFreshUserName `a) ctorArgs := ctorArgs.push a let xTy ← whnf (← inferType x) match xTy.getAppFn with | .const declName .. => match allIndVals.findIdx? (· == declName) with | some x => rhs ← `(mixHash $rhs ($(mkIdent ctx.auxFunNames[x]!) $a:ident)) | none => rhs ← `(mixHash $rhs (hash $a:ident)) | _ => rhs ← `(mixHash $rhs (hash $a:ident)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) alts := alts.push alt ctorIdx := ctorIdx + 1 return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Command := do let auxFunName := ctx.auxFunNames[i]! let indVal := ctx.typeInfos[i]! let header ← mkHashableHeader indVal let body ← mkMatch ctx header indVal let binders := header.binders if ctx.usePartial then -- TODO(Dany): Get rid of this code branch altogether once we have well-founded recursion `(private partial def $(mkIdent auxFunName):ident $binders:bracketedBinder* : UInt64 := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:bracketedBinder* : UInt64 := $body:term) def mkHashFuncs (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual $auxDefs:command* end) private def mkHashableInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "hash" declNames[0]! let cmds := #[← mkHashFuncs ctx] ++ (← mkInstanceCmds ctx `Hashable declNames) trace[Elab.Deriving.hashable] "\n{cmds}" return cmds def mkHashableHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) && declNames.size > 0 then let cmds ← liftTermElabM <| mkHashableInstanceCmds declNames cmds.forM elabCommand return true else return false builtin_initialize registerDerivingHandler ``Hashable mkHashableHandler registerTraceClass `Elab.Deriving.hashable
b71b85f4cbb35651d02253481e0f5fa1119f5ed8
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/async_tactic.lean
e4bde39410996f4f3d848a299bd0990794b034a2
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,851
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import init.meta.tactic import init.meta.interactive namespace tactic private meta def report {α} (s : tactic_state) : option (unit → format) → α | (some fmt) := undefined_core $ to_string $ fmt () ++ format.line ++ to_fmt s | none := undefined_core "silent failure" private meta def run_or_fail {α} (s : tactic_state) (tac : tactic α) : α := match tac s with | (result.success a s) := a | (result.exception fmt _ s') := report s' fmt end meta def run_async {α : Type} (tac : tactic α) : tactic (task α) := do s ← read, return $ task.delay $ λ _, match tac s with | (result.success a s) := a | (result.exception fmt _ s') := report s' fmt end meta def prove_goal_async (tac : tactic unit) : tactic unit := do ctx ← local_context, revert_lst ctx, tgt ← target, tgt ← instantiate_mvars tgt, env ← get_env, tgt ← return $ env^.unfold_untrusted_macros tgt, when tgt^.has_meta_var (fail "goal contains metavariables"), params ← return tgt^.collect_univ_params, lemma_name ← new_aux_decl_name, proof ← run_async (do goal_meta ← mk_meta_var tgt, set_goals [goal_meta], monad.for' ctx (λc, intro c^.local_pp_name), tac, proof ← instantiate_mvars goal_meta, proof ← return $ env^.unfold_untrusted_macros proof, when proof^.has_meta_var $ fail "async proof failed: contains metavariables", return proof), add_decl $ declaration.thm lemma_name params tgt proof, exact (expr.const lemma_name (params^.map level.param)) namespace interactive open interactive.types /-- Proves the first goal asynchronously as a separate lemma. -/ meta def async (tac : irtactic) : tactic unit := prove_goal_async tac end interactive end tactic
44d725b7b9bff12581797345eaa3e78e212194d9
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/support.lean
d30faeb371face200960dff3708f66f27eae3aec
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
10,866
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.conditionally_complete_lattice import algebra.big_operators.basic import algebra.group.prod import algebra.group.pi import algebra.module.pi /-! # Support of a function In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties. We also define `function.mul_support f = {x | f x ≠ 1}`. -/ open set open_locale big_operators namespace function variables {α β A B M N P R S G M₀ G₀ : Type*} {ι : Sort*} section has_one variables [has_one M] [has_one N] [has_one P] /-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/ def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0} /-- `mul_support` of a function is the set of points `x` such that `f x ≠ 1`. -/ @[to_additive] def mul_support (f : α → M) : set α := {x | f x ≠ 1} @[to_additive] lemma nmem_mul_support {f : α → M} {x : α} : x ∉ mul_support f ↔ f x = 1 := not_not @[to_additive] lemma compl_mul_support {f : α → M} : (mul_support f)ᶜ = {x | f x = 1} := ext $ λ x, nmem_mul_support @[simp, to_additive] lemma mem_mul_support {f : α → M} {x : α} : x ∈ mul_support f ↔ f x ≠ 1 := iff.rfl @[simp, to_additive] lemma mul_support_subset_iff {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x, f x ≠ 1 → x ∈ s := iff.rfl @[to_additive] lemma mul_support_subset_iff' {f : α → M} {s : set α} : mul_support f ⊆ s ↔ ∀ x ∉ s, f x = 1 := forall_congr $ λ x, not_imp_comm @[simp, to_additive] lemma mul_support_eq_empty_iff {f : α → M} : mul_support f = ∅ ↔ f = 1 := by { simp_rw [← subset_empty_iff, mul_support_subset_iff', funext_iff], simp } @[simp, to_additive] lemma mul_support_one' : mul_support (1 : α → M) = ∅ := mul_support_eq_empty_iff.2 rfl @[simp, to_additive] lemma mul_support_one : mul_support (λ x : α, (1 : M)) = ∅ := mul_support_one' @[to_additive] lemma mul_support_const {c : M} (hc : c ≠ 1) : mul_support (λ x : α, c) = set.univ := by { ext x, simp [hc] } @[to_additive] lemma mul_support_binop_subset (op : M → N → P) (op1 : op 1 1 = 1) (f : α → M) (g : α → N) : mul_support (λ x, op (f x) (g x)) ⊆ mul_support f ∪ mul_support g := λ x hx, classical.by_cases (λ hf : f x = 1, or.inr $ λ hg, hx $ by simp only [hf, hg, op1]) or.inl @[to_additive] lemma mul_support_sup [semilattice_sup M] (f g : α → M) : mul_support (λ x, f x ⊔ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊔) sup_idem f g @[to_additive] lemma mul_support_inf [semilattice_inf M] (f g : α → M) : mul_support (λ x, f x ⊓ g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (⊓) inf_idem f g @[to_additive] lemma mul_support_max [linear_order M] (f g : α → M) : mul_support (λ x, max (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_sup f g @[to_additive] lemma mul_support_min [linear_order M] (f g : α → M) : mul_support (λ x, min (f x) (g x)) ⊆ mul_support f ∪ mul_support g := mul_support_inf f g @[to_additive] lemma mul_support_supr [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨆ i, f i x) ⊆ ⋃ i, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], intros x hx, simp only [hx, csupr_const] end @[to_additive] lemma mul_support_infi [conditionally_complete_lattice M] [nonempty ι] (f : ι → α → M) : mul_support (λ x, ⨅ i, f i x) ⊆ ⋃ i, mul_support (f i) := @mul_support_supr _ (order_dual M) ι ⟨(1:M)⟩ _ _ f @[to_additive] lemma mul_support_comp_subset {g : M → N} (hg : g 1 = 1) (f : α → M) : mul_support (g ∘ f) ⊆ mul_support f := λ x, mt $ λ h, by simp only [(∘), *] @[to_additive] lemma mul_support_subset_comp {g : M → N} (hg : ∀ {x}, g x = 1 → x = 1) (f : α → M) : mul_support f ⊆ mul_support (g ∘ f) := λ x, mt hg @[to_additive] lemma mul_support_comp_eq (g : M → N) (hg : ∀ {x}, g x = 1 ↔ x = 1) (f : α → M) : mul_support (g ∘ f) = mul_support f := set.ext $ λ x, not_congr hg @[to_additive] lemma mul_support_comp_eq_preimage (g : β → M) (f : α → β) : mul_support (g ∘ f) = f ⁻¹' mul_support g := rfl @[to_additive support_prod_mk] lemma mul_support_prod_mk (f : α → M) (g : α → N) : mul_support (λ x, (f x, g x)) = mul_support f ∪ mul_support g := set.ext $ λ x, by simp only [mul_support, not_and_distrib, mem_union_eq, mem_set_of_eq, prod.mk_eq_one, ne.def] @[to_additive support_prod_mk'] lemma mul_support_prod_mk' (f : α → M × N) : mul_support f = mul_support (λ x, (f x).1) ∪ mul_support (λ x, (f x).2) := by simp only [← mul_support_prod_mk, prod.mk.eta] @[to_additive] lemma mul_support_along_fiber_subset (f : α × β → M) (a : α) : mul_support (λ b, f (a, b)) ⊆ (mul_support f).image prod.snd := by tidy @[simp, to_additive] lemma mul_support_along_fiber_finite_of_finite (f : α × β → M) (a : α) (h : (mul_support f).finite) : (mul_support (λ b, f (a, b))).finite := (h.image prod.snd).subset (mul_support_along_fiber_subset f a) end has_one @[to_additive] lemma mul_support_mul [monoid M] (f g : α → M) : mul_support (λ x, f x * g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (*) (one_mul _) f g @[simp, to_additive] lemma mul_support_inv [group G] (f : α → G) : mul_support (λ x, (f x)⁻¹) = mul_support f := set.ext $ λ x, not_congr inv_eq_one @[simp, to_additive support_neg'] lemma mul_support_inv'' [group G] (f : α → G) : mul_support (f⁻¹) = mul_support f := mul_support_inv f @[simp] lemma mul_support_inv' [group_with_zero G₀] (f : α → G₀) : mul_support (λ x, (f x)⁻¹) = mul_support f := set.ext $ λ x, not_congr inv_eq_one' @[to_additive] lemma mul_support_mul_inv [group G] (f g : α → G) : mul_support (λ x, f x * (g x)⁻¹) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (λ a b, a * b⁻¹) (by simp) f g @[to_additive support_sub] lemma mul_support_group_div [group G] (f g : α → G) : mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (/) (by simp only [one_div, one_inv]) f g lemma mul_support_div [group_with_zero G₀] (f g : α → G₀) : mul_support (λ x, f x / g x) ⊆ mul_support f ∪ mul_support g := mul_support_binop_subset (/) (by simp only [div_one]) f g @[simp] lemma support_mul [mul_zero_class R] [no_zero_divisors R] (f g : α → R) : support (λ x, f x * g x) = support f ∩ support g := set.ext $ λ x, by simp only [mem_support, mul_ne_zero_iff, mem_inter_eq, not_or_distrib] lemma support_smul_subset_right [add_monoid A] [monoid B] [distrib_mul_action B A] (b : B) (f : α → A) : support (b • f) ⊆ support f := λ x hbf hf, hbf $ by rw [pi.smul_apply, hf, smul_zero] lemma support_smul_subset_left [semiring R] [add_comm_monoid M] [module R M] (f : α → R) (g : α → M) : support (f • g) ⊆ support f := λ x hfg hf, hfg $ by rw [pi.smul_apply', hf, zero_smul] lemma support_smul [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] (f : α → R) (g : α → M) : support (f • g) = support f ∩ support g := ext $ λ x, smul_ne_zero @[simp] lemma support_inv [group_with_zero G₀] (f : α → G₀) : support (λ x, (f x)⁻¹) = support f := set.ext $ λ x, not_congr inv_eq_zero @[simp] lemma support_div [group_with_zero G₀] (f g : α → G₀) : support (λ x, f x / g x) = support f ∩ support g := by simp [div_eq_mul_inv] @[to_additive] lemma mul_support_prod [comm_monoid M] (s : finset α) (f : α → β → M) : mul_support (λ x, ∏ i in s, f i x) ⊆ ⋃ i ∈ s, mul_support (f i) := begin rw mul_support_subset_iff', simp only [mem_Union, not_exists, nmem_mul_support], exact λ x, finset.prod_eq_one end lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) := λ x hx, mem_bInter_iff.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) := set.ext $ λ x, by simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists] lemma mul_support_one_add [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (λ x, 1 + f x) = support f := set.ext $ λ x, not_congr add_right_eq_self lemma mul_support_one_add' [has_one R] [add_left_cancel_monoid R] (f : α → R) : mul_support (1 + f) = support f := mul_support_one_add f lemma mul_support_add_one [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (λ x, f x + 1) = support f := set.ext $ λ x, not_congr add_left_eq_self lemma mul_support_add_one' [has_one R] [add_right_cancel_monoid R] (f : α → R) : mul_support (f + 1) = support f := mul_support_add_one f lemma mul_support_one_sub' [has_one R] [add_group R] (f : α → R) : mul_support (1 - f) = support f := by rw [sub_eq_add_neg, mul_support_one_add', support_neg'] lemma mul_support_one_sub [has_one R] [add_group R] (f : α → R) : mul_support (λ x, 1 - f x) = support f := mul_support_one_sub' f end function namespace set open function variables {α β M : Type*} [has_one M] {f : α → M} @[to_additive] lemma image_inter_mul_support_eq {s : set β} {g : β → α} : (g '' s ∩ mul_support f) = g '' (s ∩ mul_support (f ∘ g)) := by rw [mul_support_comp_eq_preimage f g, image_inter_preimage] end set namespace pi variables {A : Type*} {B : Type*} [decidable_eq A] [has_zero B] {a : A} {b : B} lemma support_single_zero : function.support (pi.single a (0 : B)) = ∅ := by simp @[simp] lemma support_single_of_ne (h : b ≠ 0) : function.support (pi.single a b) = {a} := begin ext, simp only [mem_singleton_iff, ne.def, function.mem_support], split, { contrapose!, exact λ h', single_eq_of_ne h' b }, { rintro rfl, rw single_eq_same, exact h } end lemma support_single [decidable_eq B] : function.support (pi.single a b) = if b = 0 then ∅ else {a} := by { split_ifs with h; simp [h] } lemma support_single_subset : function.support (pi.single a b) ⊆ {a} := begin classical, rw support_single, split_ifs; simp end lemma support_single_disjoint {b' : B} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : A} : disjoint (function.support (single i b)) (function.support (single j b')) ↔ i ≠ j := by simpa [support_single, hb, hb'] using ne_comm end pi
6e3440b7746c9b0e9e930a4639e0d83f74f9d2b3
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/linear_algebra/affine_space.lean
7d9b73c94ddd32b034bba9b188f3fd8f46196dc3
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
29,968
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import algebra.add_torsor import linear_algebra.basis noncomputable theory open_locale big_operators /-! # Affine spaces This file defines affine spaces (over modules) and subspaces, affine maps, affine combinations of points, and the affine span of a set of points. ## Implementation notes This file is very minimal and many things are surely omitted. Most results can be deduced from corresponding results for modules or vector spaces. The variables `k` and `V` are explicit rather than implicit arguments to lemmas because otherwise the elaborator sometimes has problems inferring appropriate types and type class instances. Definitions of affine spaces vary as to whether a space with no points is permitted; here, we require a nonempty type of points (via the definition of torsors requiring a nonempty type). ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ /-- `affine_space` is an abbreviation for `add_torsor` in the case where the group is a vector space, or more generally a module, but we omit the type classes `[ring k]` and `[module k V]` in the type synonym itself to simplify type class search.. -/ @[nolint unused_arguments] abbreviation affine_space (k : Type*) (V : Type*) (P : Type*) [add_comm_group V] := add_torsor V P namespace affine_space open add_action open add_torsor variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space k V P] include S /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (vsub_set V s) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k V P`, if the set of points is known to be nonempty. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k V s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k V s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- The set of points in the affine span of a nonempty set of points is nonempty. -/ lemma span_points_nonempty_of_nonempty {s : set P} : s.nonempty → (span_points k V s).nonempty | ⟨p, hp⟩ := ⟨p, mem_span_points k V p s hp⟩ /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k V s) (hv : v ∈ vector_span k V s) : v +ᵥ p ∈ span_points k V s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k V s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k V s) (hp2 : p2 ∈ span_points k V s) : p1 -ᵥ p2 ∈ vector_span k V s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub V (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k V s, { apply (vector_span k V s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k V s).smul_mem (-1 : k) hv2 }, refine (vector_span k V s).add_mem _ hv1v2, unfold vector_span, change p1a -ᵥ p2a ∈ submodule.span k (vsub_set V s), have hp1p2 : p1a -ᵥ p2a ∈ vsub_set V s, { use [p1a, hp1a, p2a, hp2a] }, have hp1p2s : vsub_set V s ⊆ submodule.span k (vsub_set V s) := submodule.subset_span, apply set.mem_of_mem_of_subset hp1p2 hp1p2s end section combination variables {k} {ι : Type*} [fintype ι] /-- A weighted sum of the results of subtracting a base point from the given points. The main cases of interest are where the sum of the weights is 0, in which case the sum is independent of the choice of base point, and where the sum of the weights is 1, in which case the sum added to the base point is independent of the choice of base point. -/ def weighted_vsub_of_point (w : ι → k) (p : ι → P) (b : P) : V := ∑ i, w i • (p i -ᵥ b) /-- `weighted_vsub_of_point` as a linear map on the weights. -/ def weighted_vsub_of_point_linear (p : ι → P) (b : P) : (ι → k) →ₗ[k] V := ∑ i, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b) @[simp] lemma weighted_vsub_of_point_linear_apply (w : ι → k) (p : ι → P) (b : P) : weighted_vsub_of_point_linear V p b w = weighted_vsub_of_point V w p b := by simp [weighted_vsub_of_point_linear, linear_map.sum_apply, weighted_vsub_of_point] /-- The weighted sum when the weights are 0. -/ @[simp] lemma weighted_vsub_of_point_zero (p : ι → P) (b : P) : weighted_vsub_of_point V (0 : ι → k) p b = 0 := by rw [← weighted_vsub_of_point_linear_apply, linear_map.map_zero] /-- The weighted sum, multiplied by a constant. -/ lemma weighted_vsub_of_point_smul (r : k) (w : ι → k) (p : ι → P) (b : P) : r • weighted_vsub_of_point V w p b = weighted_vsub_of_point V (r • w) p b := by simp only [← weighted_vsub_of_point_linear_apply, linear_map.map_smul] /-- The weighted sum, negated. -/ lemma weighted_vsub_of_point_neg (w : ι → k) (p : ι → P) (b : P) : -weighted_vsub_of_point V w p b = weighted_vsub_of_point V (-w) p b := by simp only [← weighted_vsub_of_point_linear_apply, linear_map.map_neg] /-- Adding two weighted sums. -/ lemma weighted_vsub_of_point_add (w₁ w₂ : ι → k) (p : ι → P) (b : P) : weighted_vsub_of_point V w₁ p b + weighted_vsub_of_point V w₂ p b = weighted_vsub_of_point V (w₁ + w₂) p b := by simp only [← weighted_vsub_of_point_linear_apply, linear_map.map_add] /-- Subtracting two weighted sums. -/ lemma weighted_vsub_of_point_sub (w₁ w₂ : ι → k) (p : ι → P) (b : P) : weighted_vsub_of_point V w₁ p b - weighted_vsub_of_point V w₂ p b = weighted_vsub_of_point V (w₁ - w₂) p b := by simp only [← weighted_vsub_of_point_linear_apply, linear_map.map_sub] /-- The weighted sum is independent of the base point when the sum of the weights is 0. -/ lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i, w i = 0) (b₁ b₂ : P) : weighted_vsub_of_point V w p b₁ = weighted_vsub_of_point V w p b₂ := begin apply eq_of_sub_eq_zero, erw ←finset.sum_sub_distrib, conv_lhs { congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←finset.sum_smul, h, zero_smul] end /-- The weighted sum, added to the base point, is independent of the base point when the sum of the weights is 1. -/ lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i, w i = 1) (b₁ b₂ : P) : weighted_vsub_of_point V w p b₁ +ᵥ b₁ = weighted_vsub_of_point V w p b₂ +ᵥ b₂ := begin erw [←vsub_eq_zero_iff_eq V, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc, ←finset.sum_sub_distrib], conv_lhs { congr, skip, congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←finset.sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self] end /-- A weighted sum of the results of subtracting a default base point from the given points. This is intended to be used when the sum of the weights is 0; that condition is specified as a hypothesis on those lemmas that require it. -/ def weighted_vsub (w : ι → k) (p : ι → P) : V := weighted_vsub_of_point V w p (classical.choice S.nonempty) /-- `weighted_vsub` gives the sum of the results of subtracting any base point, when the sum of the weights is 0. -/ lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i, w i = 0) (b : P) : weighted_vsub V w p = weighted_vsub_of_point V w p b := weighted_vsub_of_point_eq_of_sum_eq_zero V w p h _ _ /-- The weighted sum when the weights are 0. -/ @[simp] lemma weighted_vsub_zero (p : ι → P) : weighted_vsub V (0 : ι → k) p = 0 := weighted_vsub_of_point_zero V p _ /-- The weighted sum, multiplied by a constant. -/ lemma weighted_vsub_smul (r : k) (w : ι → k) (p : ι → P) : r • weighted_vsub V w p = weighted_vsub V (r • w) p := weighted_vsub_of_point_smul V r w p _ /-- The weighted sum, negated. -/ lemma weighted_vsub_neg (w : ι → k) (p : ι → P) : -weighted_vsub V w p = weighted_vsub V (-w) p := weighted_vsub_of_point_neg V w p _ /-- Adding two weighted sums. -/ lemma weighted_vsub_add (w₁ w₂ : ι → k) (p : ι → P) : weighted_vsub V w₁ p + weighted_vsub V w₂ p = weighted_vsub V (w₁ + w₂) p := weighted_vsub_of_point_add V w₁ w₂ p _ /-- Subtracting two weighted sums. -/ lemma weighted_vsub_sub (w₁ w₂ : ι → k) (p : ι → P) : weighted_vsub V w₁ p - weighted_vsub V w₂ p = weighted_vsub V (w₁ - w₂) p := weighted_vsub_of_point_sub V w₁ w₂ p _ /-- A weighted sum of the results of subtracting a default base point from the given points, added to that base point. This is intended to be used when the sum of the weights is 1, in which case it is an affine combination (barycenter) of the points with the given weights; that condition is specified as a hypothesis on those lemmas that require it. -/ def affine_combination (w : ι → k) (p : ι → P) : P := weighted_vsub_of_point V w p (classical.choice S.nonempty) +ᵥ (classical.choice S.nonempty) /-- `affine_combination` gives the sum with any base point, when the sum of the weights is 1. -/ lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i, w i = 1) (b : P) : affine_combination V w p = weighted_vsub_of_point V w p b +ᵥ b := weighted_vsub_of_point_vadd_eq_of_sum_eq_one V w p h _ _ /-- Adding a `weighted_vsub` to an `affine_combination`. -/ lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) : weighted_vsub V w₁ p +ᵥ affine_combination V w₂ p = affine_combination V (w₁ + w₂) p := begin erw vadd_assoc, congr, exact weighted_vsub_add V w₁ w₂ p end /-- Subtracting two `affine_combination`s. -/ lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) : affine_combination V w₁ p -ᵥ affine_combination V w₂ p = weighted_vsub V (w₁ - w₂) p := begin erw vadd_vsub_vadd_cancel_right, exact weighted_vsub_sub V w₁ w₂ p end end combination end affine_space open add_torsor affine_space /-- An `affine_subspace k V P` is a subset of an `affine_space k V P` that has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] := (carrier : set P) (direction : submodule k V) (nonempty : carrier.nonempty) (add : ∀ (p : P) (v : V), p ∈ carrier → v ∈ direction → v +ᵥ p ∈ carrier) (sub : ∀ (p1 p2 : P), p1 ∈ carrier → p2 ∈ carrier → p1 -ᵥ p2 ∈ direction) namespace affine_subspace variables (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [S : affine_space k V P] include S instance : has_coe (affine_subspace k V P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k V P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k V P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl /-- The whole affine space as a subspace of itself. -/ def univ : affine_subspace k V P := { carrier := set.univ, direction := submodule.span k set.univ, nonempty := set.nonempty_iff_univ_nonempty.1 S.nonempty, add := λ p v hp hv, set.mem_univ _, sub := begin intros p1 p2 hp1 hp2, apply set.mem_bInter, intros x hx, rw set.mem_set_of_eq at hx, exact set.mem_of_mem_of_subset (set.mem_univ _) hx end } /-- `univ`, coerced to a set, is the whole set of points. -/ @[simp] lemma univ_coe : (univ k V P : set P) = set.univ := rfl /-- All points are in `univ`. -/ lemma mem_univ (p : P) : p ∈ univ k V P := set.mem_univ p instance : inhabited (affine_subspace k V P) := ⟨univ k V P⟩ variables {k V P} /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k V P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, change s1_carrier = s2_carrier at h, congr, { exact h }, { ext v, split, { intro hv, have hm := s1_nonempty.some_mem, have hvp := s1_add s1_nonempty.some v hm hv, conv_rhs at hm { rw h }, conv_rhs at hvp { rw h }, rw ←vadd_vsub V v s1_nonempty.some, exact s2_sub _ _ hvp hm }, { intro hv, have hm := s2_nonempty.some_mem, have hvp := s2_add s2_nonempty.some v hm hv, conv_rhs at hm { rw ←h }, conv_rhs at hvp { rw ←h }, rw ←vadd_vsub V v s2_nonempty.some, exact s1_sub _ _ hvp hm } } end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k V P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd V p hn.some, refine s2.add _ _ hq2 _, rw ←hd, exact s1.sub _ _ hp hq1 }, { intro hp, rw ←vsub_vadd V p hn.some, refine s1.add _ _ hq1 _, rw hd, exact s2.sub _ _ hp hq2 } end /-- Construct an affine subspace from a point and a direction. -/ def mk_of_point_of_direction (p : P) (direction : submodule k V) : affine_subspace k V P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, direction := direction, nonempty := ⟨p, ⟨0, ⟨direction.zero_mem, (add_action.zero_vadd _ _).symm⟩⟩⟩, add := λ p2 v hp2 hv, begin rcases hp2 with ⟨v2, hv2, hp2⟩, use [v + v2, direction.add_mem hv hv2], rw [←add_action.vadd_assoc, hp2] end, sub := λ p1 p2 hp1 hp2, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rw [hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 end } /-- The direction of an affine space constructed from a point and a direction. -/ @[simp] lemma direction_mk_of_point_of_direction (p : P) (direction : submodule k V) : (mk_of_point_of_direction p direction).direction = direction := rfl /-- An affine space constructed from a point and a direction contains that point. -/ lemma mem_mk_of_point_of_direction (p : P) (direction : submodule k V) : p ∈ mk_of_point_of_direction p direction := ⟨0, ⟨direction.zero_mem, (add_action.zero_vadd _ _).symm⟩⟩ /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk_of_point_of_direction_eq {s : affine_subspace k V P} {p : P} (hp : p ∈ s) : mk_of_point_of_direction p s.direction = s := ext_of_direction_eq rfl ⟨p, set.mem_inter (mem_mk_of_point_of_direction _ _) hp⟩ end affine_subspace section affine_span variables (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] /-- The affine span of a nonempty set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) (h : s.nonempty) : affine_subspace k V P := { carrier := span_points k V s, direction := vector_span k V s, nonempty := span_points_nonempty_of_nonempty k V h, add := λ p v hp hv, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k V hp hv, sub := λ p1 p2 hp1 hp2, vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k V hp1 hp2 } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma affine_span_coe (s : set P) (h : s.nonempty) : (affine_span k V P s h : set P) = span_points k V s := rfl /-- A point in a set is in its affine span. -/ lemma affine_span_mem (p : P) (s : set P) (hp : p ∈ s) : p ∈ affine_span k V P s ⟨p, hp⟩ := mem_span_points k V p s hp end affine_span /-- An `affine_map k V1 P1 V2 P2` is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) (V1 : Type*) (P1 : Type*) (V2 : Type*) (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] := (to_fun : P1 → P2) (linear : linear_map k V1 V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] [add_comm_group V3] [module k V3] [affine_space k V3 P3] [add_comm_group V4] [module k V4] [affine_space k V4 P4] instance: has_coe_to_fun (affine_map k V1 P1 V2 P2) := ⟨_, to_fun⟩ /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : affine_map k V1 P1 V2 P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : affine_map k V1 P1 V2 P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : affine_map k V1 P1 V2 P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd V1 p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : affine_map k V1 P1 V2 P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr', ext v, cases (add_torsor.nonempty V1 : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : affine_map k V1 P1 V2 P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ variables (k V1 P1 V2) /-- Constant function as an `affine_map`. -/ def const (p : P2) : affine_map k V1 P1 V2 P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k V1 P1 V2 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k V1 P1 V2 p).linear = 0 := rfl variables {k V1 P1 V2} instance nonempty : nonempty (affine_map k V1 P1 V2 P2) := ⟨const k V1 P1 V2 (classical.choice $ add_torsor.nonempty V2)⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : affine_map k V1 P1 V2 P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, add_action.vadd_assoc] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (affine_map k V1 P1 V2 V2) := { zero := ⟨0, 0, λ p v, (add_action.zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : affine_map k V1 P1 V2 V2) = 0 := rfl @[simp] lemma zero_linear : (0 : affine_map k V1 P1 V2 V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : affine_map k V1 P1 V2 V2) : ⇑(f + g) = f + g := rfl @[simp] lemma add_linear (f g : affine_map k V1 P1 V2 V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine spaces from `P1` to the vector `V2` corresponding to `P2`. -/ instance : affine_space k (affine_map k V1 P1 V2 V2) (affine_map k V1 P1 V2 P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [add_action.vadd_assoc, add_right_comm]⟩, zero_vadd' := λ f, ext $ λ p, add_action.zero_vadd _ (f p), vadd_assoc' := λ f₁ f₂ f₃, ext $ λ p, add_action.vadd_assoc V2 (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd V2 (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub V2 (f p) (g p) } @[simp] lemma vadd_apply (f : affine_map k V1 P1 V2 V2) (g : affine_map k V1 P1 V2 P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : affine_map k V1 P1 V2 P2) (p : P1) : (f -ᵥ g : affine_map k V1 P1 V2 V2) p = f p -ᵥ g p := rfl variables (k V1 P1) /-- Identity map as an affine map. -/ def id : affine_map k V1 P1 V1 P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k V1 P1) = _root_.id := rfl @[simp] lemma id_linear : (id k V1 P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k V1 P1 p = p := rfl variables {k V1 P1 V2} instance : inhabited (affine_map k V1 P1 V1 P1) := ⟨id k V1 P1⟩ /-- Composition of affine maps. -/ def comp (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : affine_map k V1 P1 V3 P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) (p : P1) : f.comp g p = f (g p) := rfl @[simp] lemma comp_id (f : affine_map k V1 P1 V2 P2) : f.comp (id k V1 P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : affine_map k V1 P1 V2 P2) : (id k V2 P2).comp f = f := ext $ λ p, rfl lemma comp_assoc (f₃₄ : affine_map k V3 P3 V4 P4) (f₂₃ : affine_map k V2 P2 V3 P3) (f₁₂ : affine_map k V1 P1 V2 P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl instance : monoid (affine_map k V1 P1 V1 P1) := { one := id k V1 P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : affine_map k V1 P1 V1 P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : affine_map k V1 P1 V1 P1) = _root_.id := rfl /-- The affine map from `k` to `P1` sending `0` to `p` and `1` to `v +ᵥ p`. -/ def line_map (p : P1) (v : V1) : affine_map k k k V1 P1 := { to_fun := λ c, c • v +ᵥ p, linear := linear_map.id.smul_right v, map_vadd' := λ a b, by simp [add_smul, add_action.vadd_assoc] } lemma line_map_apply (p : P1) (v : V1) (c : k) : line_map p v c = c • v +ᵥ p := rfl @[simp] lemma line_map_linear (p : P1) (v : V1) : (line_map p v : affine_map k k k V1 P1).linear = linear_map.id.smul_right v := rfl @[simp] lemma line_map_zero (p : P1) : line_map p (0:V1) = const k k k V1 p := by { ext c, simp [line_map_apply] } @[simp] lemma line_map_apply_zero (p : P1) (v : V1) : line_map p v (0:k) = p := by simp [line_map_apply] @[simp] lemma affine_apply_line_map (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) (c : k) : f (line_map p v c) = line_map (f p) (f.linear v) c := by simp [line_map_apply] @[simp] lemma affine_comp_line_map (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) : f.comp (line_map p v) = line_map (f p) (f.linear v) := ext $ f.affine_apply_line_map p v lemma line_map_vadd_neg (p : P1) (v : V1) : line_map (v +ᵥ p) (-v) = (line_map p v).comp (line_map (1:k) (-1:k)) := by { rw [affine_comp_line_map], simp [line_map_apply] } end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (affine_map k V1 P1 V2 V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : affine_map k V1 P1 V2 V2) : ⇑(c • f) = c • f := rfl variable (V1) /-- `homothety V c r` is the homothety about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : affine_map k V1 P1 V1 P1 := r • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ const k V1 P1 V1 c lemma homothety_def (c : P1) (r : k) : homothety V1 c r = r • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ const k V1 P1 V1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety V1 c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl @[simp] lemma homothety_one (c : P1) : homothety V1 c (1:k) = id k V1 P1 := by { ext p, simp [homothety_apply] } lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety V1 c (r₁ * r₂) = (homothety V1 c r₁).comp (homothety V1 c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety V1 c (0:k) = const k V1 P1 V1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety V1 c (r₁ + r₂) = r₁ • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ homothety V1 c r₂ := by simp only [homothety_def, add_smul, add_action.vadd_assoc] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* affine_map k V1 P1 V1 P1 := ⟨homothety V1 c, homothety_one V1 c, homothety_mul V1 c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom V1 c : k →* _) = homothety V1 c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : affine_map k k k (affine_map k V1 P1 V1 V1) (affine_map k V1 P1 V1 P1) := ⟨homothety V1 c, (linear_map.lsmul k _).flip (id k V1 P1 -ᵥ const k V1 P1 V1 c), function.swap (homothety_add V1 c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine V1 c : affine_map k k k _ _) = homothety V1 c := rfl end affine_map namespace affine_map variables {k : Type*} (V : Type*) (P : Type*) [comm_ring k] [add_comm_group V] [module k V] variables [affine_space k V P] {ι : Type*} [fintype ι] -- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd` /-- A weighted sum, as an affine map on the points involved. -/ def weighted_vsub_of_point (w : ι → k) : affine_map k ((ι → V) × V) ((ι → P) × P) V V := { to_fun := λ p, weighted_vsub_of_point _ w p.fst p.snd, linear := ∑ i, w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _), map_vadd' := begin rintros ⟨p, b⟩ ⟨v, b'⟩, simp [linear_map.sum_apply, weighted_vsub_of_point, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib] end } end affine_map namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : affine_map k V₁ V₁ V₂ V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map
963ab3c506b810b62b759dd06d97d015e736d35f
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/complex/basic.lean
d07602c2ed40066934944667eb2fa3154c8c4920
[ "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
7,565
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.module import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `re_clm` * `im_clm` * `of_real_clm` * `conj_clm` They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear isometries in `of_real_li` and `conj_li`. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex instance : has_norm ℂ := ⟨abs⟩ instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ := { norm_algebra_map_eq := λ x, (abs_of_real $ algebra_map R ℝ x).trans (norm_algebra_map_eq ℝ x), to_algebra := complex.algebra } @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := re_clm.continuous @[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl @[simp] lemma re_clm_norm : ∥re_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥re_clm 1∥ : by simp ... ≤ ∥re_clm∥ : unit_le_op_norm _ _ (by simp) /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := im_clm.continuous @[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl @[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl @[simp] lemma im_clm_norm : ∥im_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥im_clm I∥ : by simp ... ≤ ∥im_clm∥ : unit_le_op_norm _ _ (by simp) /-- The complex-conjugation function from `ℂ` to itself is an isometric linear map. -/ def conj_li : ℂ →ₗᵢ[ℝ] ℂ := ⟨conj_lm, λ x, by simp⟩ /-- Continuous linear map version of the conj function, from `ℂ` to `ℂ`. -/ def conj_clm : ℂ →L[ℝ] ℂ := conj_li.to_continuous_linear_map lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_li.isometry @[continuity] lemma continuous_conj : continuous conj := conj_clm.continuous @[simp] lemma conj_clm_coe : (coe (conj_clm) : ℂ →ₗ[ℝ] ℂ) = conj_lm := rfl @[simp] lemma conj_clm_apply (z : ℂ) : (conj_clm : ℂ → ℂ) z = z.conj := rfl @[simp] lemma conj_clm_norm : ∥conj_clm∥ = 1 := conj_li.norm_to_continuous_linear_map /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_lm, λ x, by simp⟩ /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := isometry_of_real.continuous @[simp] lemma of_real_clm_coe : (coe (of_real_clm) : ℝ →ₗ[ℝ] ℂ) = of_real_lm := rfl @[simp] lemma of_real_clm_apply (x : ℝ) : (of_real_clm : ℝ → ℂ) x = x := rfl @[simp] lemma of_real_clm_norm : ∥of_real_clm∥ = 1 := of_real_li.norm_to_continuous_linear_map noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `conjC` := @is_R_or_C.conj ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
c13551715516f00614c9155d61f7d4e10e5b6511
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/meta/expr.lean
39a8489c5168ba3e6dcc09dbebd41cc759827706
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
37,507
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs 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 /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `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 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 /-- `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 /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- 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 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 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 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) := 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 /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- 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 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 tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file` Use `environment.in_current_file` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- 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
a9fe72217bbbcf900dcb6ef0d791e08dcf562805
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Pointed1Magma.lean
65f3a1a6811fb0b5da38889197c3ee4708b54a1d
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,710
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Pointed1Magma structure Pointed1Magma (A : Type) : Type := (one : A) (op : (A → (A → A))) open Pointed1Magma structure Sig (AS : Type) : Type := (oneS : AS) (opS : (AS → (AS → AS))) structure Product (A : Type) : Type := (oneP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) structure Hom {A1 : Type} {A2 : Type} (Po1 : (Pointed1Magma A1)) (Po2 : (Pointed1Magma A2)) : Type := (hom : (A1 → A2)) (pres_one : (hom (one Po1)) = (one Po2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Po1) x1 x2)) = ((op Po2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Po1 : (Pointed1Magma A1)) (Po2 : (Pointed1Magma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_one : (interp (one Po1) (one Po2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Po1) x1 x2) ((op Po2) y1 y2)))))) inductive Pointed1MagmaTerm : Type | oneL : Pointed1MagmaTerm | opL : (Pointed1MagmaTerm → (Pointed1MagmaTerm → Pointed1MagmaTerm)) open Pointed1MagmaTerm inductive ClPointed1MagmaTerm (A : Type) : Type | sing : (A → ClPointed1MagmaTerm) | oneCl : ClPointed1MagmaTerm | opCl : (ClPointed1MagmaTerm → (ClPointed1MagmaTerm → ClPointed1MagmaTerm)) open ClPointed1MagmaTerm inductive OpPointed1MagmaTerm (n : ℕ) : Type | v : ((fin n) → OpPointed1MagmaTerm) | oneOL : OpPointed1MagmaTerm | opOL : (OpPointed1MagmaTerm → (OpPointed1MagmaTerm → OpPointed1MagmaTerm)) open OpPointed1MagmaTerm inductive OpPointed1MagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpPointed1MagmaTerm2) | sing2 : (A → OpPointed1MagmaTerm2) | oneOL2 : OpPointed1MagmaTerm2 | opOL2 : (OpPointed1MagmaTerm2 → (OpPointed1MagmaTerm2 → OpPointed1MagmaTerm2)) open OpPointed1MagmaTerm2 def simplifyCl {A : Type} : ((ClPointed1MagmaTerm A) → (ClPointed1MagmaTerm A)) | oneCl := oneCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpPointed1MagmaTerm n) → (OpPointed1MagmaTerm n)) | oneOL := oneOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpPointed1MagmaTerm2 n A) → (OpPointed1MagmaTerm2 n A)) | oneOL2 := oneOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Pointed1Magma A) → (Pointed1MagmaTerm → A)) | Po oneL := (one Po) | Po (opL x1 x2) := ((op Po) (evalB Po x1) (evalB Po x2)) def evalCl {A : Type} : ((Pointed1Magma A) → ((ClPointed1MagmaTerm A) → A)) | Po (sing x1) := x1 | Po oneCl := (one Po) | Po (opCl x1 x2) := ((op Po) (evalCl Po x1) (evalCl Po x2)) def evalOpB {A : Type} {n : ℕ} : ((Pointed1Magma A) → ((vector A n) → ((OpPointed1MagmaTerm n) → A))) | Po vars (v x1) := (nth vars x1) | Po vars oneOL := (one Po) | Po vars (opOL x1 x2) := ((op Po) (evalOpB Po vars x1) (evalOpB Po vars x2)) def evalOp {A : Type} {n : ℕ} : ((Pointed1Magma A) → ((vector A n) → ((OpPointed1MagmaTerm2 n A) → A))) | Po vars (v2 x1) := (nth vars x1) | Po vars (sing2 x1) := x1 | Po vars oneOL2 := (one Po) | Po vars (opOL2 x1 x2) := ((op Po) (evalOp Po vars x1) (evalOp Po vars x2)) def inductionB {P : (Pointed1MagmaTerm → Type)} : ((P oneL) → ((∀ (x1 x2 : Pointed1MagmaTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : Pointed1MagmaTerm) , (P x)))) | p1l popl oneL := p1l | p1l popl (opL x1 x2) := (popl _ _ (inductionB p1l popl x1) (inductionB p1l popl x2)) def inductionCl {A : Type} {P : ((ClPointed1MagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P oneCl) → ((∀ (x1 x2 : (ClPointed1MagmaTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClPointed1MagmaTerm A)) , (P x))))) | psing p1cl popcl (sing x1) := (psing x1) | psing p1cl popcl oneCl := p1cl | psing p1cl popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing p1cl popcl x1) (inductionCl psing p1cl popcl x2)) def inductionOpB {n : ℕ} {P : ((OpPointed1MagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P oneOL) → ((∀ (x1 x2 : (OpPointed1MagmaTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpPointed1MagmaTerm n)) , (P x))))) | pv p1ol popol (v x1) := (pv x1) | pv p1ol popol oneOL := p1ol | pv p1ol popol (opOL x1 x2) := (popol _ _ (inductionOpB pv p1ol popol x1) (inductionOpB pv p1ol popol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpPointed1MagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P oneOL2) → ((∀ (x1 x2 : (OpPointed1MagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpPointed1MagmaTerm2 n A)) , (P x)))))) | pv2 psing2 p1ol2 popol2 (v2 x1) := (pv2 x1) | pv2 psing2 p1ol2 popol2 (sing2 x1) := (psing2 x1) | pv2 psing2 p1ol2 popol2 oneOL2 := p1ol2 | pv2 psing2 p1ol2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 p1ol2 popol2 x1) (inductionOp pv2 psing2 p1ol2 popol2 x2)) def stageB : (Pointed1MagmaTerm → (Staged Pointed1MagmaTerm)) | oneL := (Now oneL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClPointed1MagmaTerm A) → (Staged (ClPointed1MagmaTerm A))) | (sing x1) := (Now (sing x1)) | oneCl := (Now oneCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpPointed1MagmaTerm n) → (Staged (OpPointed1MagmaTerm n))) | (v x1) := (const (code (v x1))) | oneOL := (Now oneOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpPointed1MagmaTerm2 n A) → (Staged (OpPointed1MagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | oneOL2 := (Now oneOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (oneT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) end Pointed1Magma
4cee14bef893d30a196eb75591cf2b12c33775ae
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/small.lean
b54426e440b757f41ab4604ebfb45ec9f5c93cef
[ "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
5,079
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.vector.basic /-! # Small types A type is `w`-small if there exists an equivalence to some `S : Type w`. We provide a noncomputable model `shrink α : Type w`, and `equiv_shrink α : α ≃ shrink α`. A subsingleton type is `w`-small for any `w`. If `α ≃ β`, then `small.{w} α ↔ small.{w} β`. -/ universes u w v /-- A type is `small.{w}` if there exists an equivalence to some `S : Type w`. -/ class small (α : Type v) : Prop := (equiv_small : ∃ (S : Type w), nonempty (α ≃ S)) /-- Constructor for `small α` from an explicit witness type and equivalence. -/ lemma small.mk' {α : Type v} {S : Type w} (e : α ≃ S) : small.{w} α := ⟨⟨S, ⟨e⟩⟩⟩ /-- An arbitrarily chosen model in `Type w` for a `w`-small type. -/ @[nolint has_inhabited_instance] def shrink (α : Type v) [small.{w} α] : Type w := classical.some (@small.equiv_small α _) /-- The noncomputable equivalence between a `w`-small type and a model. -/ noncomputable def equiv_shrink (α : Type v) [small.{w} α] : α ≃ shrink α := nonempty.some (classical.some_spec (@small.equiv_small α _)) @[priority 100] instance small_self (α : Type v) : small.{v} α := small.mk' (equiv.refl _) @[priority 100] instance small_max (α : Type v) : small.{max w v} α := small.mk' equiv.ulift.{w}.symm instance small_ulift (α : Type v) : small.{v} (ulift.{w} α) := small.mk' equiv.ulift theorem small_type : small.{max (u+1) v} (Type u) := small_max.{max (u+1) v} _ section open_locale classical theorem small_map {α : Type*} {β : Type*} [hβ : small.{w} β] (e : α ≃ β) : small.{w} α := let ⟨γ, ⟨f⟩⟩ := hβ.equiv_small in small.mk' (e.trans f) theorem small_congr {α : Type*} {β : Type*} (e : α ≃ β) : small.{w} α ↔ small.{w} β := ⟨λ h, @small_map _ _ h e.symm, λ h, @small_map _ _ h e⟩ instance small_subtype (α : Type v) [small.{w} α] (P : α → Prop) : small.{w} { x // P x } := small_map (equiv_shrink α).subtype_equiv_of_subtype' theorem small_of_injective {α : Type v} {β : Type w} [small.{u} β] {f : α → β} (hf : function.injective f) : small.{u} α := small_map (equiv.of_injective f hf) theorem small_of_surjective {α : Type v} {β : Type w} [small.{u} α] {f : α → β} (hf : function.surjective f) : small.{u} β := small_of_injective (function.injective_surj_inv hf) theorem small_subset {α : Type v} {s t : set α} (hts : t ⊆ s) [small.{u} s] : small.{u} t := let f : t → s := λ x, ⟨x, hts x.prop⟩ in @small_of_injective _ _ _ f (λ x y hxy, subtype.ext (subtype.mk.inj hxy)) @[priority 100] instance small_subsingleton (α : Type v) [subsingleton α] : small.{w} α := begin rcases is_empty_or_nonempty α; resetI, { apply small_map (equiv.equiv_pempty α) }, { apply small_map equiv.punit_of_nonempty_of_subsingleton, assumption' }, end /-! We don't define `small_of_fintype` or `small_of_encodable` in this file, to keep imports to `logic` to a minimum. -/ instance small_Pi {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Π a, β a) := ⟨⟨Π a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.Pi_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_sigma {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Σ a, β a) := ⟨⟨Σ a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.sigma_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_prod {α β} [small.{w} α] [small.{w} β] : small.{w} (α × β) := ⟨⟨shrink α × shrink β, ⟨equiv.prod_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_sum {α β} [small.{w} α] [small.{w} β] : small.{w} (α ⊕ β) := ⟨⟨shrink α ⊕ shrink β, ⟨equiv.sum_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_set {α} [small.{w} α] : small.{w} (set α) := ⟨⟨set (shrink α), ⟨equiv.set.congr (equiv_shrink α)⟩⟩⟩ instance small_range {α : Type v} {β : Type w} (f : α → β) [small.{u} α] : small.{u} (set.range f) := small_of_surjective set.surjective_onto_range instance small_image {α : Type v} {β : Type w} (f : α → β) (S : set α) [small.{u} S] : small.{u} (f '' S) := small_of_surjective set.surjective_onto_image theorem not_small_type : ¬ small.{u} (Type (max u v)) | ⟨⟨S, ⟨e⟩⟩⟩ := @function.cantor_injective (Σ α, e.symm α) (λ a, ⟨_, cast (e.3 _).symm a⟩) (λ a b e, (cast_inj _).1 $ eq_of_heq (sigma.mk.inj e).2) instance small_vector {α : Type v} {n : ℕ} [small.{u} α] : small.{u} (vector α n) := small_of_injective (equiv.vector_equiv_fin α n).injective instance small_list {α : Type v} [small.{u} α] : small.{u} (list α) := begin let e : (Σ n, vector α n) ≃ list α := equiv.sigma_fiber_equiv list.length, exact small_of_surjective e.surjective, end end
fb75436bb1158312e2ac7b867aba86bffec8d476
82e44445c70db0f03e30d7be725775f122d72f3e
/src/field_theory/minpoly.lean
e3dac9b2afe7fd53f4244ecca18c7590f4f06f5f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
16,414
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import data.polynomial.field_division import ring_theory.integral_closure import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`. After stating the defining property we specialize to the setting of field extensions and derive some well-known properties, amongst which the fact that minimal polynomials are irreducible, and uniquely determined by their defining property. -/ open_locale classical open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : polynomial A := if hx : is_integral A x then well_founded.min degree_lt_wf _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (well_founded.min_mem degree_lt_wf _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := ne_zero_of_monic (monic hx) lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (well_founded.min_mem degree_lt_wf _ hx).2 }, { exact aeval_zero _ } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (well_founded.not_lt_min degree_lt_wf _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end end ring section integral_domain variables [integral_domain A] section ring variables [ring B] [algebra A B] [nontrivial B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj [nontrivial A] (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin have hdegle : (minpoly A (algebra_map A B a)).nat_degree ≤ 1, { apply with_bot.coe_le_coe.1, rw [←degree_eq_nat_degree (ne_zero (@is_integral_algebra_map A B _ _ _ a)), with_top.coe_one, ←degree_X_sub_C a], refine min A (algebra_map A B a) (monic_X_sub_C a) _, simp only [aeval_C, aeval_X, alg_hom.map_sub, sub_self] }, have hdeg : (minpoly A (algebra_map A B a)).degree = 1, { apply (degree_eq_iff_nat_degree_eq (ne_zero (@is_integral_algebra_map A B _ _ _ a))).2, apply le_antisymm hdegle (nat_degree_pos (@is_integral_algebra_map A B _ _ _ a)) }, have hrw := eq_X_add_C_of_degree_eq_one hdeg, simp only [monic (@is_integral_algebra_map A B _ _ _ a), one_mul, monic.leading_coeff, ring_hom.map_one] at hrw, have h0 : (minpoly A (algebra_map A B a)).coeff 0 = -a, { have hroot := aeval A (algebra_map A B a), rw [hrw, add_comm] at hroot, simp only [aeval_C, aeval_X, aeval_add] at hroot, replace hroot := eq_neg_of_add_eq_zero hroot, rw [←ring_hom.map_neg _ a] at hroot, exact (hf hroot) }, rw hrw, simp only [h0, ring_hom.map_neg, sub_eq_add_neg], end variables (A x) /-- A minimal polynomial is not a unit. -/ lemma not_is_unit : ¬ is_unit (minpoly A x) := begin by_cases hx : is_integral A x, { assume H, exact (ne_of_lt (degree_pos hx)).symm (degree_eq_zero_of_is_unit H) }, { delta minpoly, rw dif_neg hx, simp only [not_is_unit_zero, not_false_iff] } end end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : polynomial A} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin intro ha, refine not_lt_of_ge (minpoly.min A x hamonic ha) _, obtain ⟨hzeroa, b, hb_nunit, prod⟩ := hdvd, have hbmonic : b.monic, { rw monic.def, have := monic hx, rwa [monic.def, prod, leading_coeff_mul, monic.def.mp hamonic, one_mul] at this }, have hzerob : b ≠ 0 := hbmonic.ne_zero, have degbzero : 0 < b.nat_degree, { apply nat.pos_of_ne_zero, intro h, have h₁ := eq_C_of_nat_degree_eq_zero h, rw [←h, ←leading_coeff, monic.def.1 hbmonic, C_1] at h₁, rw h₁ at hb_nunit, have := is_unit_one, contradiction }, rw [prod, degree_mul, degree_eq_nat_degree hzeroa, degree_eq_nat_degree hzerob], exact_mod_cast lt_add_of_pos_right _ degbzero, end /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin cases irreducible_or_factor (minpoly A x) (not_is_unit A x) with hirr hred, { exact hirr }, exfalso, obtain ⟨a, b, ha_nunit, hb_nunit, hab_eq⟩ := hred, have coeff_prod : a.leading_coeff * b.leading_coeff = 1, { rw [←monic.def.1 (monic hx), ←hab_eq], simp only [leading_coeff_mul] }, have hamonic : (a * C b.leading_coeff).monic, { rw monic.def, simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have hbmonic : (b * C a.leading_coeff).monic, { rw [monic.def, mul_comm], simp only [coeff_prod, leading_coeff_mul, leading_coeff_C] }, have prod : minpoly A x = (a * C b.leading_coeff) * (b * C a.leading_coeff), { symmetry, calc a * C b.leading_coeff * (b * C a.leading_coeff) = a * b * (C a.leading_coeff * C b.leading_coeff) : by ring ... = a * b * (C (a.leading_coeff * b.leading_coeff)) : by simp only [ring_hom.map_mul] ... = a * b : by rw [coeff_prod, C_1, mul_one] ... = minpoly A x : hab_eq }, have hzero := aeval A x, rw [prod, aeval_mul, mul_eq_zero] at hzero, cases hzero, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hamonic _ hzero, exact ⟨hamonic.ne_zero, _, mt is_unit_of_mul_is_unit_left hb_nunit, prod⟩ }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hbmonic _ hzero, rw mul_comm at prod, exact ⟨hbmonic.ne_zero, _, mt is_unit_of_mul_is_unit_left ha_nunit, prod⟩ }, end end domain end integral_domain section field variables [field A] section ring variables [ring B] [algebra A B] variables {x : B} variables (A x) /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. -/ lemma degree_le_of_ne_zero {p : polynomial A} (pnz : p ≠ 0) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := calc degree (minpoly A x) ≤ degree (p * C (leading_coeff p)⁻¹) : min A x (monic_mul_leading_coeff_inv pnz) (by simp [hp]) ... = degree p : degree_mul_leading_coeff_inv p pnz /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. -/ lemma unique {p : polynomial A} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) (pmin : ∀ q : polynomial A, q.monic → polynomial.aeval x q = 0 → degree p ≤ degree q) : p = minpoly A x := begin have hx : is_integral A x := ⟨p, pmonic, hp⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := degree_le_of_ne_zero A x hnz (by simp [hp]), contrapose! this, apply degree_sub_lt _ (ne_zero hx), { rw [(monic hx).leading_coeff, pmonic.leading_coeff] }, { exact le_antisymm (min A x pmonic hp) (pmin (minpoly A x) (monic hx) (aeval A x)) } end /-- If an element `x` is a root of a polynomial `p`, then the minimal polynomial of `x` divides `p`. -/ lemma dvd {p : polynomial A} (hp : polynomial.aeval x p = 0) : minpoly A x ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, dvd_zero] }, have hx : is_integral A x, { rw ← is_algebraic_iff_is_integral, exact ⟨p, hp0, hp⟩ }, rw ← dvd_iff_mod_by_monic_eq_zero (monic hx), by_contra hnz, have := degree_le_of_ne_zero A x hnz _, { contrapose! this, exact degree_mod_by_monic_lt _ (monic hx) (ne_zero hx) }, { rw ← mod_by_monic_add_div p (monic hx) at hp, simpa using hp } end lemma dvd_map_of_is_scalar_tower (A K : Type*) {R : Type*} [comm_ring A] [field K] [comm_ring R] [algebra A K] [algebra A R] [algebra K R] [is_scalar_tower A K R] (x : R) : minpoly K x ∣ (minpoly A x).map (algebra_map A K) := by { refine minpoly.dvd K x _, rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } variables {A x} theorem unique' [nontrivial B] {p : polynomial A} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) (hp3 : p.monic) : p = minpoly A x := let ⟨q, hq⟩ := dvd A x hp2 in eq_of_monic_of_associated hp3 (monic ⟨p, ⟨hp3, hp2⟩⟩) $ mul_one (minpoly A x) ▸ hq.symm ▸ associated_mul_mul (associated.refl _) $ associated_one_iff_is_unit.2 $ (hp1.is_unit_or_is_unit hq).resolve_left $ not_is_unit A x lemma unique'' [nontrivial B] {p : polynomial A} (hp1 : _root_.irreducible p) (hp2 : polynomial.aeval x p = 0) : p * C p.leading_coeff⁻¹ = minpoly A x := begin have : p.leading_coeff ≠ 0 := leading_coeff_ne_zero.mpr hp1.ne_zero, apply unique', { exact irreducible_of_associated ⟨⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rwa [←C_mul, inv_mul_cancel, C_1], by rwa [←C_mul, mul_inv_cancel, C_1]⟩, rfl⟩ hp1 }, { rw [aeval_mul, hp2, zero_mul] }, { rwa [polynomial.monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel] }, end /-- If `y` is the image of `x` in an extension, their minimal polynomials coincide. We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails since `is_integral R y` depends on y. -/ lemma eq_of_algebra_map_eq {K S T : Type*} [field K] [comm_ring S] [comm_ring T] [algebra K S] [algebra K T] [algebra S T] [is_scalar_tower K S T] (hST : function.injective (algebra_map S T)) {x : S} {y : T} (hx : is_integral K x) (h : y = algebra_map S T x) : minpoly K x = minpoly K y := minpoly.unique _ _ (minpoly.monic hx) (by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval, ring_hom.map_zero]) (λ q q_monic root_q, minpoly.min _ _ q_monic (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST (h ▸ root_q : polynomial.aeval (algebra_map S T x) q = 0))) section gcd_domain /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. -/ lemma gcd_domain_eq_field_fractions {A R : Type*} (K : Type*) [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] [algebra A K] [is_fraction_ring A K] [algebra K R] [algebra A R] [is_scalar_tower A K R] {x : R} (hx : is_integral A x) : minpoly K x = (minpoly A x).map (algebra_map A K) := begin symmetry, refine unique' _ _ _, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map (polynomial.monic.is_primitive (monic hx))).1 (irreducible hx) }, { have htower := is_scalar_tower.aeval_apply A K R x (minpoly A x), rwa [aeval, eq_comm] at htower }, { exact monic_map _ (monic hx) } end /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. -/ lemma gcd_domain_dvd {A R : Type*} (K : Type*) [integral_domain A] [gcd_monoid A] [field K] [integral_domain R] [algebra A K] [is_fraction_ring A K] [algebra K R] [algebra A R] [is_scalar_tower A K R] {x : R} (hx : is_integral A x) {P : polynomial A} (hprim : is_primitive P) (hroot : polynomial.aeval x P = 0) : minpoly A x ∣ P := begin apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map K (monic.is_primitive (monic hx)) hprim).2, rw ← gcd_domain_eq_field_fractions K hx, refine dvd _ _ _, rwa ← is_scalar_tower.aeval_apply end end gcd_domain variables (B) [nontrivial B] /-- If `B/K` is a nontrivial algebra over a field, and `x` is an element of `K`, then the minimal polynomial of `algebra_map K B x` is `X - C x`. -/ lemma eq_X_sub_C (a : A) : minpoly A (algebra_map A B a) = X - C a := eq_X_sub_C_of_algebra_map_inj a (algebra_map A B).injective lemma eq_X_sub_C' (a : A) : minpoly A a = X - C a := eq_X_sub_C A a variables (A) /-- The minimal polynomial of `0` is `X`. -/ @[simp] lemma zero : minpoly A (0:B) = X := by simpa only [add_zero, C_0, sub_eq_add_neg, neg_zero, ring_hom.map_zero] using eq_X_sub_C B (0:A) /-- The minimal polynomial of `1` is `X - 1`. -/ @[simp] lemma one : minpoly A (1:B) = X - 1 := by simpa only [ring_hom.map_one, C_1, sub_eq_add_neg] using eq_X_sub_C B (1:A) end ring section domain variables [domain B] [algebra A B] variables {x : B} /-- A minimal polynomial is prime. -/ lemma prime (hx : is_integral A x) : prime (minpoly A x) := begin refine ⟨ne_zero hx, not_is_unit A x, _⟩, rintros p q ⟨d, h⟩, have : polynomial.aeval x (p*q) = 0 := by simp [h, aeval A x], replace : polynomial.aeval x p = 0 ∨ polynomial.aeval x q = 0 := by simpa, exact or.imp (dvd A x) (dvd A x) this end /-- If `L/K` is a field extension and an element `y` of `K` is a root of the minimal polynomial of an element `x ∈ L`, then `y` maps to `x` under the field embedding. -/ lemma root {x : B} (hx : is_integral A x) {y : A} (h : is_root (minpoly A x) y) : algebra_map A B y = x := have key : minpoly A x = X - C y := eq_of_monic_of_associated (monic hx) (monic_X_sub_C y) (associated_of_dvd_dvd (dvd_symm_of_irreducible (irreducible_X_sub_C y) (irreducible hx) (dvd_iff_is_root.2 h)) (dvd_iff_is_root.2 h)), by { have := aeval A x, rwa [key, alg_hom.map_sub, aeval_X, aeval_C, sub_eq_zero, eq_comm] at this } /-- The constant coefficient of the minimal polynomial of `x` is `0` if and only if `x = 0`. -/ @[simp] lemma coeff_zero_eq_zero (hx : is_integral A x) : coeff (minpoly A x) 0 = 0 ↔ x = 0 := begin split, { intro h, have zero_root := zero_is_root_of_coeff_zero_eq_zero h, rw ← root hx zero_root, exact ring_hom.map_zero _ }, { rintro rfl, simp } end /-- The minimal polynomial of a nonzero element has nonzero constant coefficient. -/ lemma coeff_zero_ne_zero (hx : is_integral A x) (h : x ≠ 0) : coeff (minpoly A x) 0 ≠ 0 := by { contrapose! h, simpa only [hx, coeff_zero_eq_zero] using h } end domain end field end minpoly
a45db1440bea6166d38ac3328b537cf125542140
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/real/ennreal.lean
b4e1ff1784b767a67a4aadcf3cb944484bdb2d2d
[ "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
57,274
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, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal = ℝ≥0∞ := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ℝ≥0∞` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0∞`: the type of the extended nonnegative real numbers; * `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `ℝ≥0∞` := ennreal" in ennreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} instance : inhabited ℝ≥0∞ := ⟨0⟩ instance : has_coe ℝ≥0 ℝ≥0∞ := ⟨ option.some ⟩ instance : can_lift ℝ≥0∞ ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ℝ≥0∞) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ℝ≥0∞ → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ℝ≥0∞) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ℝ≥0∞ := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ℝ≥0∞).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ℝ≥0∞}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ℝ≥0∞} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ℝ≥0∞}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl @[simp] lemma to_real_nonneg {a : ℝ≥0∞} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ℝ≥0∞).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ℝ≥0∞).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ℝ≥0∞).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ℝ≥0∞).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ℝ≥0∞).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ℝ≥0∞) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ℝ≥0∞} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ℝ≥0∞ → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ℝ≥0∞) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ℝ≥0∞) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ℝ≥0∞) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ℝ≥0∞) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ℝ≥0∞) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ℝ≥0∞) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ℝ≥0∞) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ℝ≥0∞) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ℝ≥0∞) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ℝ≥0∞) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ℝ≥0∞ → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ℝ≥0∞ → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞ := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ℝ≥0∞) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ℝ≥0∞ _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ℝ≥0∞} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end lemma mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ := by { rw [ennreal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp], rintro rfl, norm_num } @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ℝ≥0∞) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ℝ≥0∞) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := with_top.coe_nat n @[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real] @[simp] lemma nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ℝ≥0∞)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [nonpos_iff_eq_zero.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [pos_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_pos_le_add : ∀{a b : ℝ≥0∞}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_pos_le_add h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ℝ≥0∞) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ℝ≥0∞) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ℝ≥0∞) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ℝ≥0∞) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ℝ≥0∞ := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ℝ≥0∞) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ℝ≥0∞) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ℝ≥0∞) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ℝ≥0∞) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ℝ≥0∞} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul @[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul @[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ℝ≥0∞ := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ℝ≥0∞) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ℝ≥0∞) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ℝ≥0∞}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ℝ≥0∞}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, Inf_le h) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, pos_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact pos_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ℝ≥0∞) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ℝ≥0∞} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ℝ≥0∞} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ℝ≥0∞} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ℝ≥0∞} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } lemma of_real_sum_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∑ i in s, f i) = ∑ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_sum, coe_eq_coe], exact nnreal.of_real_sum_of_nonneg hf, end end sum section interval variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ℝ≥0∞ := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : div_inv_monoid ℝ≥0∞ := { inv := has_inv.inv, .. (infer_instance : monoid ℝ≥0∞) } @[simp] lemma inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ := show Inf {b : ℝ≥0∞ | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ℝ≥0∞) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ℝ≥0∞)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one @[simp] lemma div_one {a : ℝ≥0∞} : a / 1 = a := by rw [div_eq_mul_inv, inv_one, mul_one] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow', coe_pow] end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ℝ≥0∞, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ℝ≥0∞, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] } lemma div_lt_top {x y : ℝ≥0∞} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] @[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [div_eq_mul_inv, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ℝ≥0∞) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv], refine (le_div_iff_mul_le _ _).symm; simpa end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at *, exact mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ := top_unique $ le_of_forall_nnreal_lt $ λ r hr, h r lemma div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma mul_div_le : a * (b / a) ≤ b := begin by_cases h0 : a = 0, { simp [h0] }, by_cases hI : a = ∞, { simp [hI] }, rw mul_div_cancel' h0 hI, exact le_refl b end lemma inv_two_add_inv_two : (2:ℝ≥0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top] lemma add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or_distrib] lemma half_pos {a : ℝ≥0∞} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ℝ≥0∞) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ℝ≥0∞) = ((2 : ℝ≥0) : ℝ≥0∞), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ℝ≥0∞) - 2⁻¹ = 2⁻¹ := by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) : ∃n:ℕ, (n:ℝ≥0∞)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ℝ≥0∞), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ℝ≥0∞) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe, nnreal.of_real_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_nnreal_mul_top (a : ℝ≥0∞) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ℝ≥0∞) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ℝ≥0∞) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ℝ≥0∞) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ℝ≥0∞ →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ℝ≥0∞}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ℝ≥0∞ →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ lemma of_real_prod_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) : ennreal.of_real (∏ i in s, f i) = ∏ i in s, ennreal.of_real (f i) := begin simp_rw [ennreal.of_real, ←coe_finset_prod, coe_eq_coe], exact nnreal.of_real_prod_of_nonneg hf, end end real section infi variables {ι : Sort*} {f g : ι → ℝ≥0∞} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ℝ≥0∞} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ℝ≥0∞} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ℝ≥0∞} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ℝ≥0∞)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ℝ≥0∞` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ℝ≥0∞} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] end ennreal
14fe98eda1bb4bddcea2d264e8f0c3e67195925b
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Mathlib.lean
ffae689b03f9af9314dfa1b50b4ea275af546238
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
1,750
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic import Mathport.Syntax.Translate.Tactic.Lean3 import Mathport.Syntax.Translate.Tactic.Mathlib.Alias import Mathport.Syntax.Translate.Tactic.Mathlib.Apply import Mathport.Syntax.Translate.Tactic.Mathlib.Cache import Mathport.Syntax.Translate.Tactic.Mathlib.Choose import Mathport.Syntax.Translate.Tactic.Mathlib.Clear import Mathport.Syntax.Translate.Tactic.Mathlib.Congr import Mathport.Syntax.Translate.Tactic.Mathlib.Converter import Mathport.Syntax.Translate.Tactic.Mathlib.Core import Mathport.Syntax.Translate.Tactic.Mathlib.DocCommands import Mathport.Syntax.Translate.Tactic.Mathlib.Ext import Mathport.Syntax.Translate.Tactic.Mathlib.Finish import Mathport.Syntax.Translate.Tactic.Mathlib.Hint import Mathport.Syntax.Translate.Tactic.Mathlib.Interactive import Mathport.Syntax.Translate.Tactic.Mathlib.Linarith import Mathport.Syntax.Translate.Tactic.Mathlib.Lint import Mathport.Syntax.Translate.Tactic.Mathlib.Misc1 import Mathport.Syntax.Translate.Tactic.Mathlib.Misc2 import Mathport.Syntax.Translate.Tactic.Mathlib.Monotonicity import Mathport.Syntax.Translate.Tactic.Mathlib.NormCast import Mathport.Syntax.Translate.Tactic.Mathlib.NormNum import Mathport.Syntax.Translate.Tactic.Mathlib.Padics import Mathport.Syntax.Translate.Tactic.Mathlib.RCases import Mathport.Syntax.Translate.Tactic.Mathlib.Ring import Mathport.Syntax.Translate.Tactic.Mathlib.Simps import Mathport.Syntax.Translate.Tactic.Mathlib.SolveByElim import Mathport.Syntax.Translate.Tactic.Mathlib.Squeeze import Mathport.Syntax.Translate.Tactic.Mathlib.Suggest
24be274663566867a4ac9cdd7122cd89118bd7e7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/stalks.lean
ce1bcf0f929dbb4320b05ef01c6325a7def97e57
[ "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,586
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebraic_geometry.presheafed_space import category_theory.limits.final import topology.sheaves.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. Additionally, we prove that restriction of presheafed spaces does not change the stalks. -/ noncomputable theory universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space open opposite variables {C : Type u} [category.{v} C] [has_colimits C] local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace /-- The stalk at `x` of a `PresheafedSpace`. -/ abbreviation stalk (X : PresheafedSpace C) (x : X) : C := X.presheaf.stalk x /-- A morphism of presheafed spaces induces a morphism of stalks. -/ def stalk_map {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) (x : X) : Y.stalk (α.base x) ⟶ X.stalk x := (stalk_functor C (α.base x)).map (α.c) ≫ X.presheaf.stalk_pushforward C α.base x @[simp, elementwise, reassoc] lemma stalk_map_germ {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) (U : opens Y.carrier) (x : (opens.map α.base).obj U) : Y.presheaf.germ ⟨α.base x, x.2⟩ ≫ stalk_map α ↑x = α.c.app (op U) ≫ X.presheaf.germ x := by rw [stalk_map, stalk_functor_map_germ_assoc, stalk_pushforward_germ] section restrict /-- For an open embedding `f : U ⟶ X` and a point `x : U`, we get an isomorphism between the stalk of `X` at `f x` and the stalk of the restriction of `X` along `f` at t `x`. -/ def restrict_stalk_iso {U : Top} (X : PresheafedSpace.{v} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) (x : U) : (X.restrict h).stalk x ≅ X.stalk (f x) := begin -- As a left adjoint, the functor `h.is_open_map.functor_nhds x` is initial. haveI := initial_of_adjunction (h.is_open_map.adjunction_nhds x), -- Typeclass resolution knows that the opposite of an initial functor is final. The result -- follows from the general fact that postcomposing with a final functor doesn't change colimits. exact final.colimit_iso (h.is_open_map.functor_nhds x).op ((open_nhds.inclusion (f x)).op ⋙ X.presheaf), end @[simp, elementwise, reassoc] lemma restrict_stalk_iso_hom_eq_germ {U : Top} (X : PresheafedSpace.{v} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) (V : opens U) (x : U) (hx : x ∈ V) : (X.restrict h).presheaf.germ ⟨x, hx⟩ ≫ (restrict_stalk_iso X h x).hom = X.presheaf.germ ⟨f x, show f x ∈ h.is_open_map.functor.obj V, from ⟨x, hx, rfl⟩⟩ := colimit.ι_pre ((open_nhds.inclusion (f x)).op ⋙ X.presheaf) (h.is_open_map.functor_nhds x).op (op ⟨V, hx⟩) @[simp, elementwise, reassoc] lemma restrict_stalk_iso_inv_eq_germ {U : Top} (X : PresheafedSpace.{v} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) (V : opens U) (x : U) (hx : x ∈ V) : X.presheaf.germ ⟨f x, show f x ∈ h.is_open_map.functor.obj V, from ⟨x, hx, rfl⟩⟩ ≫ (restrict_stalk_iso X h x).inv = (X.restrict h).presheaf.germ ⟨x, hx⟩ := by rw [← restrict_stalk_iso_hom_eq_germ, category.assoc, iso.hom_inv_id, category.comp_id] lemma restrict_stalk_iso_inv_eq_of_restrict {U : Top} (X : PresheafedSpace.{v} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) (x : U) : (X.restrict_stalk_iso h x).inv = stalk_map (X.of_restrict h) x := begin ext V, induction V using opposite.rec, let i : (h.is_open_map.functor_nhds x).obj ((open_nhds.map f x).obj V) ⟶ V := hom_of_le (set.image_preimage_subset f _), erw [iso.comp_inv_eq, colimit.ι_map_assoc, colimit.ι_map_assoc, colimit.ι_pre], simp_rw category.assoc, erw colimit.ι_pre ((open_nhds.inclusion (f x)).op ⋙ X.presheaf) (h.is_open_map.functor_nhds x).op, erw ← X.presheaf.map_comp_assoc, exact (colimit.w ((open_nhds.inclusion (f x)).op ⋙ X.presheaf) i.op).symm, end instance of_restrict_stalk_map_is_iso {U : Top} (X : PresheafedSpace.{v} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) (x : U) : is_iso (stalk_map (X.of_restrict h) x) := by { rw ← restrict_stalk_iso_inv_eq_of_restrict, apply_instance } end restrict namespace stalk_map @[simp] lemma id (X : PresheafedSpace.{v} C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.presheaf, tidy, end -- TODO understand why this proof is still gross (i.e. requires using `erw`) @[simp] lemma comp {X Y Z : PresheafedSpace.{v} C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α.base x) : Z.stalk (β.base (α.base x)) ⟶ Y.stalk (α.base x)) ≫ (stalk_map α x : Y.stalk (α.base x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, induction U using opposite.rec, cases U, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left_app, whisker_right_app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc, pushforward.comp_inv_app], -- FIXME Why doesn't simp do this: erw [category_theory.functor.map_id], erw [category_theory.functor.map_id], erw [id_comp, id_comp], end /-- If `α = β` and `x = x'`, we would like to say that `stalk_map α x = stalk_map β x'`. Unfortunately, this equality is not well-formed, as their types are not _definitionally_ the same. To get a proper congruence lemma, we therefore have to introduce these `eq_to_hom` arrows on either side of the equality. -/ lemma congr {X Y : PresheafedSpace.{v} C} (α β : X ⟶ Y) (h₁ : α = β) (x x': X) (h₂ : x = x') : stalk_map α x ≫ eq_to_hom (show X.stalk x = X.stalk x', by rw h₂) = eq_to_hom (show Y.stalk (α.base x) = Y.stalk (β.base x'), by rw [h₁, h₂]) ≫ stalk_map β x' := stalk_hom_ext _ $ λ U hx, by { subst h₁, subst h₂, simp } lemma congr_hom {X Y : PresheafedSpace.{v} C} (α β : X ⟶ Y) (h : α = β) (x : X) : stalk_map α x = eq_to_hom (show Y.stalk (α.base x) = Y.stalk (β.base x), by rw h) ≫ stalk_map β x := by rw [← stalk_map.congr α β h x x rfl, eq_to_hom_refl, category.comp_id] lemma congr_point {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) (x x' : X) (h : x = x') : stalk_map α x ≫ eq_to_hom (show X.stalk x = X.stalk x', by rw h) = eq_to_hom (show Y.stalk (α.base x) = Y.stalk (α.base x'), by rw h) ≫ stalk_map α x' := by rw stalk_map.congr α α rfl x x' h instance is_iso {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) [is_iso α] (x : X) : is_iso (stalk_map α x) := { out := begin let β : Y ⟶ X := category_theory.inv α, have h_eq : (α ≫ β).base x = x, { rw [is_iso.hom_inv_id α, id_base, Top.id_app] }, -- Intuitively, the inverse of the stalk map of `α` at `x` should just be the stalk map of `β` -- at `α x`. Unfortunately, we have a problem with dependent type theory here: Because `x` -- is not *definitionally* equal to `β (α x)`, the map `stalk_map β (α x)` has not the correct -- type for an inverse. -- To get a proper inverse, we need to compose with the `eq_to_hom` arrow -- `X.stalk x ⟶ X.stalk ((α ≫ β).base x)`. refine ⟨eq_to_hom (show X.stalk x = X.stalk ((α ≫ β).base x), by rw h_eq) ≫ (stalk_map β (α.base x) : _), _, _⟩, { rw [← category.assoc, congr_point α x ((α ≫ β).base x) h_eq.symm, category.assoc], erw ← stalk_map.comp β α (α.base x), rw [congr_hom _ _ (is_iso.inv_hom_id α), stalk_map.id, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] }, { rw [category.assoc, ← stalk_map.comp, congr_hom _ _ (is_iso.hom_inv_id α), stalk_map.id, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp] }, end } /-- An isomorphism between presheafed spaces induces an isomorphism of stalks. -/ def stalk_iso {X Y : PresheafedSpace.{v} C} (α : X ≅ Y) (x : X) : Y.stalk (α.hom.base x) ≅ X.stalk x := as_iso (stalk_map α.hom x) @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_map {X Y : PresheafedSpace.{v} C} (f : X ⟶ Y) {x y : X} (h : x ⤳ y) : Y.presheaf.stalk_specializes (f.base.map_specializes h) ≫ stalk_map f x = stalk_map f y ≫ X.presheaf.stalk_specializes h := by { delta PresheafedSpace.stalk_map, simp [stalk_map] } end stalk_map end algebraic_geometry.PresheafedSpace
ab748b16137f00ca3c219ed7244a0b8f901e1553
4fa161becb8ce7378a709f5992a594764699e268
/src/ring_theory/principal_ideal_domain.lean
36f3ea7431beb49093f06ec756d9ffe54daab657
[ "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
8,158
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes, Morenikeji Neri -/ import ring_theory.noetherian import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a commutative ring in which all ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[integral domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on commutative rings, saying that every ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_domain`: a noncomputable definition, putting a UFD structure on a PID. Note that the definition of a UFD is currently not a predicate, as it contains data of factorizations of non-zero elements. # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal [ring R] [add_comm_group M] [module R M] (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) /-- A commutative ring is a principal ideal ring if all ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [comm_ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal namespace submodule.is_principal variables [comm_ring R] [add_comm_group M] [module R M] /-- `generator I`, if `I` is a principal submodule, is the `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID should prove that if p < q then q maximal; 0 isn't prime in a non-ID lemma to_maximal_ideal [integral_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.2 (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, domain.mul_right_inj this] at hz, exact hz.symm ▸ ideal.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ ideal.add_mem S (ideal.mul_mem_right S hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ ideal.sub_mem S hx (ideal.mul_mem_right S hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ ideal.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end namespace principal_ideal_ring open is_principal_ideal_ring variables [integral_domain R] [is_principal_ideal_ring R] @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring : is_noetherian_ring R := ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, submodule.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezeI, rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, mul_dvd_of_is_unit_right hb] end⟩ lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, irreducible_of_prime⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ p.prime := associates.forall_associated.2 $ assume a, by rw [associates.irreducible_mk_iff, associates.prime_mk, irreducible_iff_prime] section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (is_noetherian_ring.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated a (factors a).prod := begin unfold factors, rw [dif_neg h], exact classical.some_spec (is_noetherian_ring.exists_factors a h) end /-- The unique factorization domain structure given by the principal ideal domain. This is not added as type class instance, since the `factors` might be computed in a different way. E.g. factors could return normalized values. -/ noncomputable def to_unique_factorization_domain : unique_factorization_domain R := { factors := factors, factors_prod := assume a ha, associated.symm (factors_spec a ha).2, prime_factors := assume a ha, by simpa [irreducible_iff_prime] using (factors_spec a ha).1 } end end principal_ideal_ring
0948044923f646c48d8e35c48055b4ee81a1d567
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/matrix/notation.lean
7e0bbc3a240114131ac3e1de9c239e362ccfd038
[ "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
9,260
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.matrix.basic import data.fin.vec_notation /-! # Matrix and vector notation This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of the matrix notation `![a, b] = vec_cons a (vec_cons b vec_empty)` defined in `data.fin.vec_notation`. ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations We reuse notation `![a, b]` for `vec_cons a (vec_cons b vec_empty)`. It is a localized notation in the `matrix` locale. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} {o n m : ℕ} {m' n' o' : Type*} open_locale matrix /-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example: ``` #eval ![![1, 2], ![3, 4]] + ![![3, 4], ![5, 6]] -- ![![4, 6], ![8, 10]] ``` -/ instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) := pi_fin.has_repr @[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma cons_dot_product_cons (x : α) (v : fin n → α) (y : α) (w : fin n → α) : dot_product (vec_cons x v) (vec_cons y w) = x * y + dot_product v w := by simp end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _ @[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul [fintype n'] (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty [fintype n'] (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = λ _, ![] := funext (λ _, empty_eq _) lemma mul_val_succ [fintype n'] (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl @[simp] lemma cons_mul [fintype n'] (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) : vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty [fintype n'] (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) : vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) : vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec [fintype n'] (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec [fintype n'] (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, rw [vec_mul_vec, pi.smul_apply, smul_eq_mul] } end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor section vec2_and_vec3 lemma vec2_eq {a₀ a₁ b₀ b₁ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) : ![a₀, a₁] = ![b₀, b₁] := by subst_vars lemma vec3_eq {a₀ a₁ a₂ b₀ b₁ b₂ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) (h₂ : a₂ = b₂) : ![a₀, a₁, a₂] = ![b₀, b₁, b₂] := by subst_vars lemma vec2_add [has_add α] (a₀ a₁ b₀ b₁ : α) : ![a₀, a₁] + ![b₀, b₁] = ![a₀ + b₀, a₁ + b₁] := by rw [cons_add_cons, cons_add_cons, empty_add_empty] lemma vec3_add [has_add α] (a₀ a₁ a₂ b₀ b₁ b₂ : α) : ![a₀, a₁, a₂] + ![b₀, b₁, b₂] = ![a₀ + b₀, a₁ + b₁, a₂ + b₂] := by rw [cons_add_cons, cons_add_cons, cons_add_cons, empty_add_empty] lemma smul_vec2 {R : Type*} [has_scalar R α] (x : R) (a₀ a₁ : α) : x • ![a₀, a₁] = ![x • a₀, x • a₁] := by rw [smul_cons, smul_cons, smul_empty] lemma smul_vec3 {R : Type*} [has_scalar R α] (x : R) (a₀ a₁ a₂ : α) : x • ![a₀, a₁, a₂] = ![x • a₀, x • a₁, x • a₂] := by rw [smul_cons, smul_cons, smul_cons, smul_empty] variables [add_comm_monoid α] [has_mul α] lemma vec2_dot_product' {a₀ a₁ b₀ b₁ : α} : ![a₀, a₁] ⬝ᵥ ![b₀, b₁] = a₀ * b₀ + a₁ * b₁ := by rw [cons_dot_product_cons, cons_dot_product_cons, dot_product_empty, add_zero] @[simp] lemma vec2_dot_product (v w : fin 2 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 := vec2_dot_product' lemma vec3_dot_product' {a₀ a₁ a₂ b₀ b₁ b₂ : α} : ![a₀, a₁, a₂] ⬝ᵥ ![b₀, b₁, b₂] = a₀ * b₀ + a₁ * b₁ + a₂ * b₂ := by rw [cons_dot_product_cons, cons_dot_product_cons, cons_dot_product_cons, dot_product_empty, add_zero, add_assoc] @[simp] lemma vec3_dot_product (v w : fin 3 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 + v 2 * w 2 := vec3_dot_product' end vec2_and_vec3 end matrix
93a5f11ca6fbd2ec6b1727188a0fcdd9a6968857
cf39355caa609c0f33405126beee2739aa3cb77e
/library/smt/prove.lean
78498ea4f3184db1660f1df74425ac0993aa12b6
[ "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
564
lean
namespace smt open tactic private meta def collect_props : list expr → tactic (list expr) | [] := return [] | (H :: Hs) := do Eqs ← collect_props Hs, Htype ← infer_type H >>= infer_type >>= whnf, return $ if Htype = `(Prop) then (H :: Eqs) else Eqs -- This tactic is just a placeholder, designed to be modified for specific performance experiments meta def prove : tactic unit := do local_context >>= collect_props >>= revert_lst, trace "SMT state, after reverting propositions:", trace_state, `[simp { contextual := tt }] end smt
d72f94e4c7da7f4808a124db42d8a0d55518ad49
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/eraseSuffix.lean
c9478c98d0eef685c5d9534191298bcb56b1b267
[ "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
364
lean
example : (`foo.bla).eraseSuffix? `bla == some `foo := rfl example : (`foo.bla).eraseSuffix? `boo == none := rfl example : (`foo.bla).eraseSuffix? `foo.bla == some .anonymous := rfl example : (`foo.bla.boo).eraseSuffix? `bla == none := rfl example : (`foo.bla.boo).eraseSuffix? `boo == `foo.bla := rfl example : (`foo.bla.boo).eraseSuffix? `bla.boo == `foo := rfl
b2a1705d3aad03ec37dbed425dea634faf3432c5
46125763b4dbf50619e8846a1371029346f4c3db
/src/analysis/convex/topology.lean
ef7b352ec0b1f8c9853ea81fef37bfd755057654
[ "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
7,616
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 analysis.normed_space.finite_dimension /-! # 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 /-! ### 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.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 : 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] local attribute [instance] set.pointwise_add set.smul_set /-- 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 }, (smul_set_eq_image b (interior s)).symm ▸ (is_open_pointwise_add_left ((is_open_map_smul_of_ne_zero hne _) is_open_interior))) (λ hne, (smul_set_eq_image a (interior s)).symm ▸ (is_open_pointwise_add_right ((is_open_map_smul_of_ne_zero hne _) is_open_interior))), (subset_interior_iff_subset_of_open h).mpr $ subset.trans begin apply pointwise_add_subset_add; rw [smul_set_eq_image, smul_set_eq_image]; exact image_subset _ interior_subset end (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) : 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) := closed_of_compact _ hs.compact_convex_hull 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] end normed_space
50770d6fb3a93325bd5c753d5264520437bd5cbc
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tmp/even_odd.lean
852e0e5886ceac95a43673f4d1a03235e1ce98d0
[ "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
705
lean
import data.vector open nat universes u v set_option trace.eqn_compiler.wf_rec true set_option trace.debug.eqn_compiler.wf_rec true set_option trace.debug.eqn_compiler.mutual true mutual def even, odd with even : nat → bool | 0 := tt | (a+1) := odd a with odd : nat → bool | 0 := ff | (a+1) := even a #eval even._main 3 #eval even._main 4 #eval odd._main 3 #eval odd._main 4 mutual def f, g {α β : Type u} (f : α → β) (p : α × β) with f : Π n : nat, vector (α × β) n | 0 := vector.nil | (succ n) := vector.cons p $ (g n p.1).map (λ b, (p.1, b)) with g : Π n : nat, α → vector β n | 0 a := vector.nil | (succ n) a := vector.cons p.2 $ (f n).map (λ p, p.2)
8764c1b8f111ff8b2ebeb94e0fda1b6b775cfd8f
38aa1f7792ba7c73b43619c5d089e15d69cd32eb
/lamps_array.lean
99fbc6cb8ff2da17182f0cdb93c18ea05162d831
[]
no_license
mirefek/my-lean-experiments
f8ec3efa4013285b80cd45c219a7bc8b6294b8cc
1218fecbf568669ac123256d430a151a900f67b3
refs/heads/master
1,679,449,694,211
1,616,190,468,000
1,616,190,468,000
154,370,734
1
0
null
null
null
null
UTF-8
Lean
false
false
5,273
lean
import tactic import tactic.norm_cast import data.rat import data.fintype import data.real.basic import data.nat.parity noncomputable theory open_locale classical /--- problem statement ---/ def lamp_switch_seq (n k : ℕ) := array k (fin (n+n)) --local attribute [instance] classical.prop_decidable instance (n k : ℕ) : has_mem (fin (n+n)) (lamp_switch_seq n k) := array.has_mem instance (n k : ℕ) : fintype (lamp_switch_seq n k) := begin unfold lamp_switch_seq, apply_instance end def lamp_state (n : ℕ) := array (n+n) bool def ini_state (n : ℕ) : (lamp_state n) := ⟨λ i : fin (n+n), ff⟩ def target_state (n : ℕ) : (lamp_state n) := ⟨λ i : fin (n+n), (i:ℕ) < n⟩ def switch_lamp {n : ℕ} (i : fin (n+n)) (s1 : lamp_state n) : lamp_state n := s1.write i (¬s1.read i) -- := ⟨λ j : fin (n+n), xor (i = j) (s1.read j)⟩ def fin_state {n k : ℕ} (seq : lamp_switch_seq n k) : lamp_state n := seq.foldl (ini_state n) switch_lamp def is_N_seq {n k : ℕ} (seq : lamp_switch_seq n k) : Prop := (fin_state seq = target_state n) def is_M_seq {n k : ℕ} (seq : lamp_switch_seq n k) : Prop := is_N_seq seq ∧ ∀ l ∈ seq, (l : ℕ) < n def N_seq (n k : ℕ) := @subtype (lamp_switch_seq n k) is_N_seq def M_seq (n k : ℕ) := @subtype (lamp_switch_seq n k) is_M_seq instance (n k : ℕ) : fintype (N_seq n k) := by apply subtype.fintype instance (n k : ℕ) : fintype (M_seq n k) := by apply subtype.fintype def N_num (n k : ℕ) := fintype.card (N_seq n k) def M_num (n k : ℕ) := fintype.card (M_seq n k) /- The statement of the theorem -/ def lamp_prop : Prop := ∀ n k : ℕ, 0 < n → n ≤ k → nat.even (k-n) → (N_num n k : ℚ) / (M_num n k) = 2^(k-n) /- Proof -/ def to_fin_2n_small {n : ℕ} (i : fin n) : fin (n+n) := ⟨i, nat.lt_add_left i.val n n i.is_lt⟩ def to_fin_2n_big {n : ℕ} (i : fin n) : fin (n+n) := ⟨i+n, add_lt_add_right i.is_lt n⟩ def is_D_seq {n k : ℕ} (seq : lamp_switch_seq n k) : Prop := let fs := fin_state seq in ∀ i : fin n, xor (fs.read (to_fin_2n_small i)) (fs.read (to_fin_2n_big i)) def D_seq (n k : ℕ) := @subtype (lamp_switch_seq n k) is_D_seq instance (n k : ℕ) : fintype (D_seq n k) := by apply subtype.fintype def D_num (n k : ℕ) := fintype.card (D_seq n k) lemma N_num_by_D_num (n k : ℕ) : (N_num n k) * 2^n = (D_num n k) := begin sorry end lemma M_num_by_D_num (n k : ℕ) : (M_num n k) * 2^k = (D_num n k) := begin sorry end -- proving that M ≠ 0 def nontriv_val_small {n k : ℕ} {i : fin k} (c : i.val < n) : fin (n+n) := ⟨i, nat.lt_add_left i.val n n c⟩ def nontriv_val_big {n k : ℕ} {i : fin k} (n_pos : 0 < n) (c : ¬i.val < n) : fin (n+n) := ⟨0, nat.lt_add_left 0 n n n_pos⟩ def nontriv_seq (n k : ℕ) (n_pos : 0 < n) : lamp_switch_seq n k := ⟨λ i : fin k, dite (i.val < n) nontriv_val_small (nontriv_val_big n_pos) ⟩ lemma nontriv_correct (n k : ℕ) (n_pos : 0 < n) (nk_lt : n ≤ k) (nk_parity : nat.even (k-n)) : is_N_seq (nontriv_seq n k n_pos) := begin sorry end lemma nontriv_all_small (n k : ℕ) (n_pos : 0 < n) : ∀ l ∈ (nontriv_seq n k n_pos), ↑l < n := begin let seq := nontriv_seq n k n_pos, show ∀ l ∈ seq, ↑l < n, intros, obtain ⟨si, hs⟩ : ∃ si, seq.data si = l, from H, rw ←hs, cases classical.em (si.val < n) with si_small si_big, -- si_small have : seq.data si = nontriv_val_small si_small, from dif_pos si_small, rw this, show si.val < n, from si_small, -- si_big have : seq.data si = nontriv_val_big n_pos si_big, from dif_neg si_big, rw this, show 0 < n, from n_pos, end lemma fintype.card_pos (α : Type) [ft : fintype α] (x : α) : 0 < fintype.card α := begin apply finset.card_pos.2, apply exists.intro, show α, from x, show x ∈ finset.univ, from finset.mem_univ x end lemma M_num_nontriv {n k : ℕ} (n_pos : 0 < n) (nk_le : n ≤ k) (nk_parity : nat.even (k-n)) : M_num n k > 0 := begin let seq : lamp_switch_seq n k := (nontriv_seq n k n_pos), have : is_M_seq seq, begin apply and.intro, show is_N_seq seq, begin apply nontriv_correct, show n ≤ k, from nk_le, show nat.even (k-n), from nk_parity, end, show ∀ l ∈ seq, ↑l < n, by apply nontriv_all_small, end, apply fintype.card_pos, show M_seq n k, from ⟨seq, this⟩ end -- final arithmetics lemma lamp_arith (M N D n k : ℕ) (h1 : N * 2^n = D) (h2 : M * 2^k = D) (non_triv : M > 0) (nk_le : n ≤ k) : (N / M : ℚ) = 2^(k-n) := begin rw div_eq_iff_mul_eq, rw ← domain.mul_left_inj (ne_of_gt $ pow_pos two_pos n : (2^n : ℚ) ≠ 0), rw [← mul_assoc, ← pow_add, nat.add_sub_cancel' nk_le], rw mul_comm at h1 h2, exact_mod_cast h2.trans h1.symm, exact_mod_cast ne_of_gt non_triv end /- Proof of the main theorem -/ theorem lamp_thm : lamp_prop := begin show ∀ n k : ℕ, 0 < n → n ≤ k → nat.even (k-n) → (N_num n k : ℚ) / (M_num n k) = 2^(k-n), intros n k n_pos nk_le nk_parity, apply lamp_arith, show N_num n k * 2^n = D_num n k, by apply N_num_by_D_num, show M_num n k * 2^k = D_num n k, by apply M_num_by_D_num, show M_num n k > 0, from M_num_nontriv n_pos nk_le nk_parity, show n ≤ k, from nk_le, end
ffd860d4d6767496339160b589b7e08407438c69
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/star/complex.lean
512dd0d99440f063d5fa04543ebb52107a8db948
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,446
lean
/- Copyright (c) 2022 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.normed_space.star.basic import algebra.star.module import analysis.complex.basic /-! # Complex normed star modules and algebras Facts about star modules and star algebras over the complex numbers. ## Main definitions * `star_module.mul_neg_I_lin`: multiplication by -I as a real-linear equivalence between the skew-adjoint and self-adjoint elements of a star module. * `star_module.im`: the imaginary part of an element of a star module, defined via `skew_adjoint_part`. -/ variables {E : Type*} namespace star_module open_locale complex_conjugate open complex variables [add_comm_group E] [star_add_monoid E] [module ℂ E] [star_module ℂ E] /-- Multiplication by -I as a real-linear equivalence between the skew-adjoint and self-adjoint elements of a star module. -/ @[simps] def mul_neg_I_lin : skew_adjoint E ≃ₗ[ℝ] self_adjoint E := { to_fun := λ x, ⟨-I • x, by simp [self_adjoint.mem_iff]⟩, inv_fun := λ x, ⟨I • x, by simp [skew_adjoint.mem_iff]⟩, map_add' := λ x y, by { ext, simp only [add_subgroup.coe_add, smul_add, add_subgroup.coe_mk] }, map_smul' := λ r x, by { ext, simp only [neg_smul, neg_inj, skew_adjoint.coe_smul, add_subgroup.coe_mk, ring_hom.id_apply, self_adjoint.coe_smul, smul_neg, smul_comm I], }, left_inv := λ x, by simp only [neg_smul, add_subgroup.coe_mk, smul_neg, ←mul_smul, I_mul_I, neg_neg, one_smul, set_like.eta], right_inv := λ x, by simp only [←mul_smul, I_mul_I, add_subgroup.coe_mk, neg_mul, neg_neg, one_smul, set_like.eta] } /-- The imaginary part of an element of a star module, as a real-linear map. -/ @[simps] noncomputable def im : E →ₗ[ℝ] self_adjoint E := mul_neg_I_lin.to_linear_map.comp (skew_adjoint_part ℝ) /-- The real part of an element of a star module, as a real-linear map. This is simply an abbreviation for `self_adjoint_part ℝ`. -/ @[simps] noncomputable abbreviation re : E →ₗ[ℝ] self_adjoint E := self_adjoint_part ℝ /-- An element of a complex star module can be decomposed into self-adjoint "real" and "imaginary" parts -/ lemma re_add_im (x : E) : (re x : E) + I • im x = x := by simp [←mul_smul, I_mul_I, ←smul_add, ←two_smul ℝ] end star_module
340df8c7a5b2f4c8ee2f1675f25ce3392c69dba0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/category/omega_complete_partial_order.lean
cd733cbbb7e2ea8bd7f8193fb47f68a74d147e7d
[]
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,934
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.omega_complete_partial_order import Mathlib.order.category.Preorder import Mathlib.category_theory.limits.shapes.products import Mathlib.category_theory.limits.shapes.equalizers import Mathlib.category_theory.limits.constructions.limits_of_products_and_equalizers import Mathlib.PostPort universes u u_1 v u_2 namespace Mathlib /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ /-- The category of types with a omega complete partial order. -/ def ωCPO := category_theory.bundled omega_complete_partial_order namespace ωCPO protected instance omega_complete_partial_order.continuous_hom.category_theory.bundled_hom : category_theory.bundled_hom omega_complete_partial_order.continuous_hom := category_theory.bundled_hom.mk omega_complete_partial_order.continuous_hom.to_fun omega_complete_partial_order.continuous_hom.id omega_complete_partial_order.continuous_hom.comp protected instance large_category : category_theory.large_category ωCPO := category_theory.bundled_hom.category omega_complete_partial_order.continuous_hom /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type u_1) [omega_complete_partial_order α] : ωCPO := category_theory.bundled.of α protected instance inhabited : Inhabited ωCPO := { default := of PUnit } protected instance omega_complete_partial_order (α : ωCPO) : omega_complete_partial_order ↥α := category_theory.bundled.str α namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO) : category_theory.limits.fan f := category_theory.limits.fan.mk (of ((j : J) → ↥(f j))) fun (j : J) => omega_complete_partial_order.continuous_hom.of_mono (pi.monotone_apply j) sorry /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : category_theory.limits.is_limit (product f) := category_theory.limits.is_limit.mk fun (s : category_theory.limits.cone (category_theory.discrete.functor f)) => omega_complete_partial_order.continuous_hom.mk (fun (t : ↥(category_theory.limits.cone.X s)) (j : J) => coe_fn (category_theory.nat_trans.app (category_theory.limits.cone.π s) j) t) sorry sorry protected instance category_theory.limits.has_product (J : Type v) (f : J → ωCPO) : category_theory.limits.has_product f := category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk (product f) (is_product J f)) end has_products protected instance omega_complete_partial_order_equalizer {α : Type u_1} {β : Type u_2} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) (g : α →𝒄 β) : omega_complete_partial_order (Subtype fun (a : α) => coe_fn f a = coe_fn g a) := omega_complete_partial_order.subtype (fun (a : α) => coe_fn f a = coe_fn g a) sorry namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α : Type u_1} {β : Type u_2} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) (g : α →𝒄 β) : (Subtype fun (a : α) => coe_fn f a = coe_fn g a) →𝒄 α := omega_complete_partial_order.continuous_hom.of_mono (preorder_hom.subtype.val fun (a : α) => coe_fn f a = coe_fn g a) sorry /-- A construction of the equalizer fork. -/ def equalizer {X : ωCPO} {Y : ωCPO} (f : X ⟶ Y) (g : X ⟶ Y) : category_theory.limits.fork f g := category_theory.limits.fork.of_ι (equalizer_ι f g) sorry /-- The equalizer fork is a limit. -/ def is_equalizer {X : ωCPO} {Y : ωCPO} (f : X ⟶ Y) (g : X ⟶ Y) : category_theory.limits.is_limit (equalizer f g) := category_theory.limits.fork.is_limit.mk' (equalizer f g) fun (s : category_theory.limits.fork f g) => { val := omega_complete_partial_order.continuous_hom.mk (fun (x : ↥(category_theory.functor.obj (category_theory.functor.obj (category_theory.functor.const category_theory.limits.walking_parallel_pair) (category_theory.limits.cone.X s)) category_theory.limits.walking_parallel_pair.zero)) => { val := coe_fn (category_theory.limits.fork.ι s) x, property := sorry }) sorry sorry, property := sorry } end has_equalizers protected instance category_theory.limits.has_products : category_theory.limits.has_products ωCPO := fun (J : Type v) => category_theory.limits.has_limits_of_shape.mk fun (F : category_theory.discrete J ⥤ ωCPO) => category_theory.limits.has_limit_of_iso (category_theory.iso.symm category_theory.discrete.nat_iso_functor) protected instance category_theory.limits.parallel_pair.category_theory.limits.has_limit {X : ωCPO} {Y : ωCPO} (f : X ⟶ Y) (g : X ⟶ Y) : category_theory.limits.has_limit (category_theory.limits.parallel_pair f g) := category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk (has_equalizers.equalizer f g) (has_equalizers.is_equalizer f g)) protected instance category_theory.limits.has_equalizers : category_theory.limits.has_equalizers ωCPO := category_theory.limits.has_equalizers_of_has_limit_parallel_pair ωCPO protected instance category_theory.limits.has_limits : category_theory.limits.has_limits ωCPO := category_theory.limits.limits_from_equalizers_and_products
76caf0a1920a29b5240bc22e8c776046a63fb085
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/asymptotics/asymptotic_equivalent.lean
e0dc4078fc0e500828469a5512f6b1ebaac41811
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
11,588
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotics import analysis.normed.order.basic /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent l u v`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomain `β`. While the definition only requires `β` to be a `normed_add_comm_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent l u v`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_add_comm_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) ## Implementation Notes Note that `is_equivalent` takes the parameters `(l : filter α) (u v : α → β)` in that order. This is to enable `calc` support, as `calc` requires that the last two explicit arguments are `u v`. -/ namespace asymptotics open filter function open_locale topological_space section normed_add_comm_group variables {α β : Type*} [normed_add_comm_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (l : filter α) (u v : α → β) := (u - v) =o[l] v localized "notation (name := asymptotics.is_equivalent) u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent l u v" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : (u - v) =o[l] v := h lemma is_equivalent.is_O (h : u ~[l] v) : u =O[l] v := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : v =O[l] u := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans {l : filter α} {u v w : α → β} (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent.congr_left {u v w : α → β} {l : filter α} (huv : u ~[l] v) (huw : u =ᶠ[l] w) : w ~[l] v := huv.congr' (huw.sub (eventually_eq.refl _ _)) (eventually_eq.refl _ _) lemma is_equivalent.congr_right {u v w : α → β} {l : filter α} (huv : u ~[l] v) (hvw : v =ᶠ[l] w) : u ~[l] w := (huv.symm.congr_left hvw).symm lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_zero_iff_is_O_zero : u ~[l] 0 ↔ u =O[l] (0 : α → β) := begin refine ⟨is_equivalent.is_O, λ h, _⟩, rw [is_equivalent_zero_iff_eventually_zero, eventually_eq_iff_exists_mem], exact ⟨{x : α | u x = 0}, is_O_zero_right_iff.mp h, λ x hx, hx⟩, end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { subst c, rw ← is_o_one_iff ℝ at hu ⊢, simpa using (huv.symm.is_o.trans hu).add hu }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ lemma is_equivalent.add_is_o (huv : u ~[l] v) (hwv : w =o[l] v) : (u + w) ~[l] v := by simpa only [is_equivalent, add_sub_right_comm] using huv.add hwv lemma is_equivalent.sub_is_o (huv : u ~[l] v) (hwv : w =o[l] v) : (u - w) ~[l] v := by simpa only [sub_eq_add_neg] using huv.add_is_o hwv.neg_left lemma is_o.add_is_equivalent (hu : u =o[l] w) (hv : v ~[l] w) : (u + v) ~[l] w := add_comm v u ▸ hv.add_is_o hu lemma is_o.is_equivalent (huv : (u - v) =o[l] v) : u ~[l] v := huv lemma is_equivalent.neg (huv : u ~[l] v) : (λ x, - u x) ~[l] (λ x, - v x) := begin rw is_equivalent, convert huv.is_o.neg_left.neg_right, ext, simp, end end normed_add_comm_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_div_nhds_zero, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ‖φ x - 1‖ * ‖u x‖ ≤ (c/2) / C * ‖u x‖ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*‖v x‖) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ‖v x‖ : by {field_simp [hC.ne.symm], ring}, calc ‖((λ (x : α), φ x • u x) - v) x‖ = ‖(φ x - 1) • u x + (u x - v x)‖ : by simp [sub_smul, sub_add] ... ≤ ‖(φ x - 1) • u x‖ + ‖u x - v x‖ : norm_add_le _ _ ... = ‖φ x - 1‖ * ‖u x‖ + ‖u x - v x‖ : by rw norm_smul ... ≤ c / 2 * ‖v x‖ + ‖u x - v x‖ : add_le_add_right key _ ... ≤ c / 2 * ‖v x‖ + c / 2 * ‖v x‖ : add_le_add_left huvx _ ... = c * ‖v x‖ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv₀ hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := by simpa only [div_eq_mul_inv] using htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ lemma is_equivalent.tendsto_at_bot [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_bot) : tendsto v l at_bot := begin convert tendsto_neg_at_top_at_bot.comp (huv.neg.tendsto_at_top $ tendsto_neg_at_bot_at_top.comp hu), ext, simp end lemma is_equivalent.tendsto_at_bot_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_bot ↔ tendsto v l at_bot := ⟨huv.tendsto_at_bot, huv.symm.tendsto_at_bot⟩ end normed_linear_ordered_field end asymptotics open filter asymptotics open_locale asymptotics variables {α β : Type*} [normed_add_comm_group β] lemma filter.eventually_eq.is_equivalent {u v : α → β} {l : filter α} (h : u =ᶠ[l] v) : u ~[l] v := is_equivalent.congr_right (is_o_refl_left _ _) h
f4a67bd8c0f84cb26fcf89a7213584178465a3ee
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/part.lean
deb48d93a9278b82ca98ebedb9a4ea6029d5d7df
[ "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,104
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import data.equiv.basic /-! # Partial values of a type -/ /-- `part α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} part (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace part variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert a `part α` with a decidable domain to an option -/ def to_option (o : part α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `part` extensionality -/ theorem ext' : ∀ {o p : part α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `part` eta expansion -/ @[simp] theorem eta : Π (o : part α), (⟨o.dom, λ h, o.get h⟩ : part α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : part α) : Prop := ∃ h, o.get h = a instance : has_mem α (part α) := ⟨part.mem⟩ theorem mem_eq (a : α) (o : part α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : part α}, o.dom ↔ ∃y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : part α} (h) : get o h ∈ o := ⟨_, rfl⟩ /-- `part` extensionality -/ @[ext] theorem ext {o p : part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `part` has a `false` domain and an empty function. -/ def none : part α := ⟨false, false.rec _⟩ instance : inhabited (part α) := ⟨none⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `part` has a `true` domain and the function returns `a`. -/ def some (a : α) : part α := ⟨true, λ_, a⟩ theorem mem_unique : ∀ {a b : α} {o : part α}, a ∈ o → b ∈ o → a = b | _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem mem.left_unique : relator.left_unique ((∈) : α → part α → Prop) := ⟨λ a o b, mem_unique⟩ theorem get_eq_of_mem {o : part α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : part α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : part α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : part α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa [not_mem_none])⟩ theorem eq_none_iff' {o : part α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ lemma some_ne_none (x : α) : some x ≠ none := by { intro h, change none.dom, rw [← h], trivial } lemma ne_none_iff {o : part α} : o ≠ none ↔ ∃x, o = some x := begin split, { rw [ne, eq_none_iff], intro h, push_neg at h, cases h with x hx, use x, rwa [eq_some_iff] }, { rintro ⟨x, rfl⟩, apply some_ne_none } end lemma eq_none_or_eq_some (o : part α) : o = none ∨ ∃ x, o = some x := begin classical, by_cases h : o.dom, { rw dom_iff_mem at h, right, apply exists_imp_exists _ h, simp [eq_some_iff] }, { rw eq_none_iff', exact or.inl h }, end @[simp] lemma some_inj {a b : α} : part.some a = some b ↔ a = b := function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (part.mk.inj h).2) trivial) @[simp] lemma some_get {a : part α} (ha : a.dom) : part.some (part.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : part α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ lemma get_eq_get_of_eq (a : part α) (ha : a.dom) {b : part α} (h : a = b) : a.get ha = b.get (h ▸ ha) := by { congr, exact h } instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true /-- Retrieves the value of `a : part α` if it exists, and return the provided default value otherwise. -/ def get_or_else (a : part α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d @[simp] lemma get_or_else_none (d : α) : get_or_else none d = d := dif_neg id @[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a := dif_pos trivial @[simp] theorem mem_to_option {o : part α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end /-- Converts an `option α` into a `part α`. -/ def of_option : option α → part α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := part.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (part α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : part α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : part α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : part α) = some a := rfl @[elab_as_eliminator] protected lemma induction_on {P : part α → Prop} (a : part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, part.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := part.none_decidable | (option.some a) := part.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : part α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option /-- `part α` is (classically) equivalent to `option α`. -/ noncomputable def equiv_option : part α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ /-- We give `part α` the order where everything is greater than `none`. -/ instance : order_bot (part α) := { le := λ x y, ∀ i, i ∈ x → i ∈ y, le_refl := λ x y, id, le_trans := λ x y z f g i, g _ ∘ f _, le_antisymm := λ x y f g, part.ext $ λ z, ⟨f _, g _⟩, bot := none, bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } } instance : preorder (part α) := by apply_instance lemma le_total_of_le_of_le {x y : part α} (z : part α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := begin rcases part.eq_none_or_eq_some x with h | ⟨b, h₀⟩, { rw h, left, apply order_bot.bot_le _ }, right, intros b' h₁, rw part.eq_some_iff at h₀, replace hx := hx _ h₀, replace hy := hy _ h₁, replace hx := part.mem_unique hx hy, subst hx, exact h₀ end /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → part α) : part α := ⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : part α) (g : α → part β) : part β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `part` just maps the value and maintains the same domain. -/ def map (f : α → β) (o : part α) : part β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : part α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : part α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → part α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → part α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ lemma assert_pos {p : Prop} {f : p → part α} (h : p) : assert p f = f h := begin dsimp [assert], cases h' : f h, simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff], apply function.hfunext, { simp only [h,h',exists_prop_of_true] }, { cc } end lemma assert_neg {p : Prop} {f : p → part α} (h : ¬ p) : assert p f = none := begin dsimp [assert,none], congr, { simp only [h, not_false_iff, exists_prop_of_false] }, { apply function.hfunext, { simp only [h, not_false_iff, exists_prop_of_false] }, cc }, end theorem mem_bind {f : part α} {g : α → part β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : part α} {g : α → part β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ @[simp] theorem bind_none (f : α → part β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → part β) : (some a).bind f = f a := ext $ by simp theorem bind_some_eq_map (f : α → β) (x : part α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] theorem bind_assoc {γ} (f : part α) (g : α → part β) (k : β → part γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → part γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → part β) (x : part α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : part α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad part := { pure := @some, map := @map, bind := @part.bind } instance : is_lawful_monad part := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : part α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : part α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : part α) (g : α → part β) : f >>= g = f.bind g := rfl lemma bind_le {α} (x : part α) (f : α → part β) (y : part β) : x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) := begin split; intro h, { intros a h' b, replace h := h b, simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h, apply h _ h' }, { intros b h', simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h', rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ }, end instance : monad_fail part := { fail := λ_ _, none, ..part.monad } /-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) : ∀ (o : part α), (p → o.dom) → part α | ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : part α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin cases o, dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/ meta def unwrap (o : part α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → part α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : part α} {g : α → part β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : part α} {g : α → part β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl end part
1c68a8ee7c2abfa6d654a9d9d7c5b7230ab1912e
ebb7367fa8ab324601b5abf705720fd4cc0e8598
/algebra/module.hlean
7475fb7f4c8cb1f8883607a60a21a38b0d4231b8
[ "Apache-2.0" ]
permissive
radams78/Spectral
3e34916d9bbd0939ee6a629e36744827ff27bfc2
c8145341046cfa2b4960ef3cc5a1117d12c43f63
refs/heads/master
1,610,421,583,830
1,481,232,014,000
1,481,232,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,294
hlean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad Modules prod vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field open algebra structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ structure left_module (R M : Type) [ringR : ring R] extends has_scalar R M, ab_group M renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm := (smul_left_distrib : Π (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : Π (r s : R) (x : M), smul (ring.add _ r s) x = (add (smul r x) (smul s x))) (mul_smul : Π r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : Π x, smul one x = x) /- we make it a class now (and not as part of the structure) to avoid left_module.to_ab_group to be an instance -/ attribute left_module [class] definition add_ab_group_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : add_ab_group M := @left_module.to_ab_group R M K H definition has_scalar_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : has_scalar R M := @left_module.to_has_scalar R M K H section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !left_module.smul_left_distrib proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !left_module.smul_right_distrib proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !left_module.mul_smul proposition one_smul (u : M) : (1 : R) • u = u := !left_module.one_smul proposition zero_smul (u : M) : (0 : R) • u = 0 := have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this proposition smul_zero (a : R) : a • (0 : M) = 0 := have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V
8aa86f9db28380b5c200a7b9884d1d5056d9a5ed
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.24.lean
5d0fe45ab3226f4612b47d137ceec8fb12cd9141
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
536
lean
import standard open nat inductive foo [class] := mk : nat → nat → foo definition foo.a [p : foo] : nat := foo.rec_on p (λ a b, a) definition i1 [instance] [priority std.priority.default+10] : foo := foo.mk 1 1 definition i2 [instance] : foo := foo.mk 2 2 example : foo.a = 1 := rfl definition i3 [instance] [priority std.priority.default+20] : foo := foo.mk 3 3 example : foo.a = 3 := rfl attribute i3 [priority 500] example : foo.a = 1 := rfl attribute i1 [priority std.priority.default-10] example : foo.a = 2 := rfl
07bbac581c450137e92dfb1f20382e118dfa3fae
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/determinant.lean
c7a57875c72afe6b988469968b3fce935a6af1c8
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
26,059
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.finite_dimensional import linear_algebra.general_linear_group import linear_algebra.matrix.reindex import tactic.field_simp import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.basis /-! # Determinant of families of vectors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) * `linear_equiv.det`: the determinant of an isomorphism `f : M ≃ₗ[R] M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix set function variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [comm_ring A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [comm_ring R] [nontrivial R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) namespace matrix /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def index_equiv_of_inv [nontrivial A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (to_lin'_of_inv hMM' hM'M) lemma det_comm [decidable_eq n] (M N : matrix n n A) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- If there exists a two-sided inverse `M'` for `M` (indexed differently), then `det (N ⬝ M) = det (M ⬝ N)`. -/ lemma det_comm' [decidable_eq m] [decidable_eq n] {M : matrix n m A} {N : matrix m n A} {M' : matrix m n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N) = det (N ⬝ M) := begin nontriviality A, -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices, which is easy. let e := index_equiv_of_inv hMM' hM'M, rw [← det_submatrix_equiv_self e, ← submatrix_mul_equiv _ _ _ (equiv.refl n) _, det_comm, submatrix_mul_equiv, equiv.coe_refl, submatrix_id_id] end /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. See `matrix.det_conj` and `matrix.det_conj'` for the case when `M' = M⁻¹` or vice versa. -/ lemma det_conj_of_mul_eq_one [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := by rw [← det_comm' hM'M hMM', ← matrix.mul_assoc, hM'M, matrix.one_mul] end matrix end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [comm_ring A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj_of_mul_eq_one]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ @[irreducible] def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := by { rw [det_aux], refl } lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical -- Discourage the elaborator from unfolding `det` and producing a huge term by marking it -- as irreducible. /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ @[irreducible] protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } @[simp] lemma det_to_matrix' {ι : Type*} [fintype ι] [decidable_eq ι] (f : (ι → A) →ₗ[A] (ι → A)) : det f.to_matrix' = f.det := by simp [← to_matrix_eq_to_matrix'] @[simp] lemma det_to_lin (b : basis ι R M) (f : matrix ι ι R) : linear_map.det (matrix.to_lin b b f) = f.det := by rw [← linear_map.det_to_matrix b, linear_map.to_matrix_to_lin] @[simp] lemma det_to_lin' (f : matrix ι ι R) : linear_map.det (f.to_lin') = f.det := by simp only [← to_lin_eq_to_lin', det_to_lin] /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one /-- Multiplying a map by a scalar `c` multiplies its determinant by `c ^ dim M`. -/ @[simp] lemma det_smul {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (c : 𝕜) (f : M →ₗ[𝕜] M) : linear_map.det (c • f) = c ^ (finite_dimensional.finrank 𝕜 M) * linear_map.det f := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { haveI : finite_dimensional 𝕜 M, { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_fintype_basis hs }, simp only [← det_to_matrix (finite_dimensional.fin_basis 𝕜 M), linear_equiv.map_smul, fintype.card_fin, det_smul] }, { classical, have : finite_dimensional.finrank 𝕜 M = 0 := finrank_eq_zero_of_not_exists_basis H, simp [coe_det, H, this] } end lemma det_zero' {ι : Type*} [finite ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, casesI nonempty_fintype ι, rwa [← det_to_matrix b, linear_equiv.map_zero, det_zero] } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. We give a formula that also works in infinite dimension, where we define the determinant to be `1`. -/ @[simp] lemma det_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] : linear_map.det (0 : M →ₗ[𝕜] M) = (0 : 𝕜) ^ (finite_dimensional.finrank 𝕜 M) := by simp only [← zero_smul 𝕜 (1 : M →ₗ[𝕜] M), det_smul, mul_one, monoid_hom.map_one] lemma det_eq_one_of_subsingleton [subsingleton M] (f : M →ₗ[R] M) : (f : M →ₗ[R] M).det = 1 := begin have b : basis (fin 0) R M := basis.empty M, rw ← f.det_to_matrix b, exact matrix.det_is_empty, end lemma det_eq_one_of_finrank_eq_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (h : finite_dimensional.finrank 𝕜 M = 0) (f : M →ₗ[𝕜] M) : (f : M →ₗ[𝕜] M).det = 1 := begin classical, refine @linear_map.det_cases M _ 𝕜 _ _ _ (λ t, t = 1) f _ rfl, intros s b, haveI : is_empty s, { rw ← fintype.card_eq_zero_iff, exact (finite_dimensional.finrank_eq_card_basis b).symm.trans h }, exact matrix.det_is_empty end /-- Conjugating a linear map by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj {N : Type*} [add_comm_group N] [module A N] (f : M →ₗ[A] M) (e : M ≃ₗ[A] N) : linear_map.det ((e : M →ₗ[A] N) ∘ₗ (f ∘ₗ (e.symm : N →ₗ[A] M))) = linear_map.det f := begin classical, by_cases H : ∃ (s : finset M), nonempty (basis s A M), { rcases H with ⟨s, ⟨b⟩⟩, rw [← det_to_matrix b f, ← det_to_matrix (b.map e), to_matrix_comp (b.map e) b (b.map e), to_matrix_comp (b.map e) b b, ← matrix.mul_assoc, matrix.det_conj_of_mul_eq_one], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans_self, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.self_trans_symm, linear_equiv.refl_to_linear_map, to_matrix_id] } }, { have H' : ¬ (∃ (t : finset N), nonempty (basis t A N)), { contrapose! H, rcases H with ⟨s, ⟨b⟩⟩, exact ⟨_, ⟨(b.map e.symm).reindex_finset_range⟩⟩ }, simp only [coe_det, H, H', pi.one_apply, dif_neg, not_false_iff] } end /-- If a linear map is invertible, so is its determinant. -/ lemma is_unit_det {A : Type*} [comm_ring A] [module A M] (f : M →ₗ[A] M) (hf : is_unit f) : is_unit f.det := begin obtain ⟨g, hg⟩ : ∃ g, f.comp g = 1 := hf.exists_right_inv, have : linear_map.det f * linear_map.det g = 1, by simp only [← linear_map.det_comp, hg, monoid_hom.map_one], exact is_unit_of_mul_eq_one _ _ this, end /-- If a linear map has determinant different from `1`, then the space is finite-dimensional. -/ lemma finite_dimensional_of_det_ne_one {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M →ₗ[𝕜] M) (hf : f.det ≠ 1) : finite_dimensional 𝕜 M := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_fintype_basis hs }, { classical, simp [linear_map.coe_det, H] at hf, exact hf.elim } end /-- If the determinant of a map vanishes, then the map is not onto. -/ lemma range_lt_top_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : f.range < ⊤ := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [lt_top_iff_ne_top, not_not, ← is_unit_iff_range_eq_top] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end /-- If the determinant of a map vanishes, then the map is not injective. -/ lemma bot_lt_ker_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : ⊥ < f.ker := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [bot_lt_iff_ne_bot, not_not, ← is_unit_iff_ker_eq_bot] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end end linear_map namespace linear_equiv /-- On a `linear_equiv`, the domain of `linear_map.det` can be promoted to `Rˣ`. -/ protected def det : (M ≃ₗ[R] M) →* Rˣ := (units.map (linear_map.det : (M →ₗ[R] M) →* R)).comp (linear_map.general_linear_group.general_linear_equiv R M).symm.to_monoid_hom @[simp] lemma coe_det (f : M ≃ₗ[R] M) : ↑f.det = linear_map.det (f : M →ₗ[R] M) := rfl @[simp] lemma coe_inv_det (f : M ≃ₗ[R] M) : ↑(f.det⁻¹) = linear_map.det (f.symm : M →ₗ[R] M) := rfl @[simp] lemma det_refl : (linear_equiv.refl R M).det = 1 := units.ext $ linear_map.det_id @[simp] lemma det_trans (f g : M ≃ₗ[R] M) : (f.trans g).det = g.det * f.det := map_mul _ g f @[simp] lemma det_symm (f : M ≃ₗ[R] M) : f.symm.det = f.det⁻¹ := map_inv _ f /-- Conjugating a linear equiv by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj (f : M ≃ₗ[R] M) (e : M ≃ₗ[R] M') : ((e.symm.trans f).trans e).det = f.det := by rw [←units.eq_iff, coe_det, coe_det, ←comp_coe, ←comp_coe, linear_map.det_conj] end linear_equiv /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_mul_det_symm {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f : M →ₗ[A] M).det * (f.symm : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_symm_mul_det {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f.symm : M →ₗ[A] M).det * (f : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := is_unit_of_mul_eq_one _ _ f.det_mul_det_symm /-- The determinant of `f.symm` is the inverse of that of `f` when `f` is a linear equiv. -/ lemma linear_equiv.det_coe_symm {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M ≃ₗ[𝕜] M) : (f.symm : M →ₗ[𝕜] M).det = (f : M →ₗ[𝕜] M).det ⁻¹ := by field_simp [is_unit.ne_zero f.is_unit_det'] /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } @[simp] lemma linear_equiv.coe_of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : (linear_equiv.of_is_unit_det h : M →ₗ[R] M') = f := by { ext x, refl } /-- Builds a linear equivalence from a linear map on a finite-dimensional vector space whose determinant is nonzero. -/ @[reducible] def linear_map.equiv_of_det_ne_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] [finite_dimensional 𝕜 M] (f : M →ₗ[𝕜] M) (hf : linear_map.det f ≠ 0) : M ≃ₗ[𝕜] M := have is_unit (linear_map.to_matrix (finite_dimensional.fin_basis 𝕜 M) (finite_dimensional.fin_basis 𝕜 M) f).det := by simp only [linear_map.det_to_matrix, is_unit_iff_ne_zero.2 hf], linear_equiv.of_is_unit_det this lemma linear_map.associated_det_of_eq_comp (e : M ≃ₗ[R] M) (f f' : M →ₗ[R] M) (h : ∀ x, f x = f' (e x)) : associated f.det f'.det := begin suffices : associated (f' ∘ₗ ↑e).det f'.det, { convert this using 2, ext x, exact h x }, rw [← mul_one f'.det, linear_map.det_comp], exact associated.mul_left _ (associated_one_iff_is_unit.mpr e.is_unit_det') end lemma linear_map.associated_det_comp_equiv {N : Type*} [add_comm_group N] [module R N] (f : N →ₗ[R] M) (e e' : M ≃ₗ[R] N) : associated (f ∘ₗ ↑e).det (f ∘ₗ ↑e').det := begin refine linear_map.associated_det_of_eq_comp (e.trans e'.symm) _ _ _, intro x, simp only [linear_map.comp_apply, linear_equiv.coe_coe, linear_equiv.trans_apply, linear_equiv.apply_symm_apply], end /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros inst v i x y, cases subsingleton.elim inst ‹_›, simp only [e.to_matrix_update, linear_equiv.map_add, finsupp.coe_add], exact det_update_column_add _ _ _ _, end, map_smul' := begin intros inst u i c x, cases subsingleton.elim inst ‹_›, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] @[simp] lemma basis.det_is_empty [is_empty ι] : e.det = alternating_map.const_of_is_empty R M 1 := begin ext v, exact matrix.det_is_empty, end /-- `basis.det` is not the zero map. -/ lemma basis.det_ne_zero [nontrivial R] : e.det ≠ 0 := λ h, by simpa [h] using e.det_self lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan.ge with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ /-- Any alternating map to `R` where `ι` has the cardinality of a basis equals the determinant map with respect to that basis, multiplied by the value of that alternating map on that basis. -/ lemma alternating_map.eq_smul_basis_det (f : alternating_map R M R ι) : f = f e • e.det := begin refine basis.ext_alternating e (λ i h, _), let σ : equiv.perm ι := equiv.of_bijective i (finite.injective_iff_bijective.1 h), change f (e ∘ σ) = (f e • e.det) (e ∘ σ), simp [alternating_map.map_perm, basis.det_self] end @[simp] lemma alternating_map.map_basis_eq_zero_iff {ι : Type*} [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e = 0 ↔ f = 0 := ⟨λ h, begin casesI nonempty_fintype ι, letI := classical.dec_eq ι, simpa [h] using f.eq_smul_basis_det e end, λ h, h.symm ▸ alternating_map.zero_apply _⟩ lemma alternating_map.map_basis_ne_zero_iff {ι : Type*} [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e ≠ 0 ↔ f ≠ 0 := not_congr $ f.map_basis_eq_zero_iff e variables {A : Type*} [comm_ring A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } @[simp] lemma basis.det_comp_basis [module A M'] (b : basis ι A M) (b' : basis ι A M') (f : M →ₗ[A] M') : b'.det (f ∘ b) = linear_map.det (f ∘ₗ (b'.equiv b (equiv.refl ι) : M' →ₗ[A] M)) := begin rw [basis.det_apply, ← linear_map.det_to_matrix b', linear_map.to_matrix_comp _ b, matrix.det_mul, linear_map.to_matrix_basis_equiv, matrix.det_one, mul_one], congr' 1, ext i j, rw [basis.to_matrix_apply, linear_map.to_matrix_apply] end lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] } lemma basis.det_map' (b : basis ι R M) (f : M ≃ₗ[R] M') : (b.map f).det = b.det.comp_linear_map f.symm := alternating_map.ext $ b.det_map f @[simp] lemma pi.basis_fun_det : (pi.basis_fun R ι).det = matrix.det_row_alternating := begin ext M, rw [basis.det_apply, basis.coe_pi_basis_fun.to_matrix_eq_transpose, det_transpose], end /-- If we fix a background basis `e`, then for any other basis `v`, we can characterise the coordinates provided by `v` in terms of determinants relative to `e`. -/ lemma basis.det_smul_mk_coord_eq_det_update {v : ι → M} (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v)) (i : ι) : (e.det v) • (basis.mk hli hsp).coord i = e.det.to_multilinear_map.to_linear_map v i := begin apply (basis.mk hli hsp).ext, intros k, rcases eq_or_ne k i with rfl | hik; simp only [algebra.id.smul_eq_mul, basis.coe_mk, linear_map.smul_apply, linear_map.coe_mk, multilinear_map.to_linear_map_apply], { rw [basis.mk_coord_apply_eq, mul_one, update_eq_self], congr, }, { rw [basis.mk_coord_apply_ne hik, mul_zero, eq_comm], exact e.det.map_eq_zero_of_eq _ (by simp [hik, function.update_apply]) hik, }, end /-- If a basis is multiplied columnwise by scalars `w : ι → Rˣ`, then the determinant with respect to this basis is multiplied by the product of the inverse of these scalars. -/ lemma basis.det_units_smul (e : basis ι R M) (w : ι → Rˣ) : (e.units_smul w).det = (↑(∏ i, w i)⁻¹ : R) • e.det := begin ext f, change matrix.det (λ i j, (e.units_smul w).repr (f j) i) = (↑(∏ i, w i)⁻¹ : R) • matrix.det (λ i j, e.repr (f j) i), simp only [e.repr_units_smul], convert matrix.det_mul_column (λ i, (↑((w i)⁻¹) : R)) (λ i j, e.repr (f j) i), simp [← finset.prod_inv_distrib] end /-- The determinant of a basis constructed by `units_smul` is the product of the given units. -/ @[simp] lemma basis.det_units_smul_self (w : ι → Rˣ) : e.det (e.units_smul w) = ∏ i, w i := by simp [basis.det_apply] /-- The determinant of a basis constructed by `is_unit_smul` is the product of the given units. -/ @[simp] lemma basis.det_is_unit_smul {w : ι → R} (hw : ∀ i, is_unit (w i)) : e.det (e.is_unit_smul hw) = ∏ i, w i := e.det_units_smul_self _
b4805f33b190e1ee6202ae46aa8b8ca9656ebb5b
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/clifford_algebra/even_equiv.lean
caf1ccefbe51964293800fe4f2c8865d7939ef97
[ "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
11,306
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.conjugation import linear_algebra.clifford_algebra.even import linear_algebra.quadratic_form.prod /-! # Isomorphisms with the even subalgebra of a Clifford algebra This file provides some notable isomorphisms regarding the even subalgebra, `clifford_algebra.even`. ## Main definitions * `clifford_algebra.equiv_even`: Every Clifford algebra is isomorphic as an algebra to the even subalgebra of a Clifford algebra with one more dimension. * `clifford_algebra.even_equiv.Q'`: The quadratic form used by this "one-up" algebra. * `clifford_algebra.to_even`: The simp-normal form of the forward direction of this isomorphism. * `clifford_algebra.of_even`: The simp-normal form of the reverse direction of this isomorphism. * `clifford_algebra.even_equiv_even_neg`: Every even subalgebra is isomorphic to the even subalgebra of the Clifford algebra with negated quadratic form. * `clifford_algebra.even_to_neg`: The simp-normal form of each direction of this isomorphism. ## Main results * `clifford_algebra.coe_to_even_reverse_involute`: the behavior of `clifford_algebra.to_even` on the "Clifford conjugate", that is `clifford_algebra.reverse` composed with `clifford_algebra.involute`. -/ namespace clifford_algebra variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables (Q : quadratic_form R M) /-! ### Constructions needed for `clifford_algebra.equiv_even` -/ namespace equiv_even /-- The quadratic form on the augmented vector space `M × R` sending `v + r•e0` to `Q v - r^2`. -/ @[reducible] def Q' : quadratic_form R (M × R) := (Q.prod $ -@quadratic_form.sq R _) lemma Q'_apply (m : M × R) : Q' Q m = Q m.1 - m.2 * m.2 := (sub_eq_add_neg _ _).symm /-- The unit vector in the new dimension -/ def e0 : clifford_algebra (Q' Q) := ι (Q' Q) (0, 1) /-- The embedding from the existing vector space -/ def v : M →ₗ[R] clifford_algebra (Q' Q) := (ι (Q' Q)) ∘ₗ linear_map.inl _ _ _ lemma ι_eq_v_add_smul_e0 (m : M) (r : R) : ι (Q' Q) (m, r) = v Q m + r • e0 Q := by rw [e0, v, linear_map.comp_apply, linear_map.inl_apply, ←linear_map.map_smul, prod.smul_mk, smul_zero, smul_eq_mul, mul_one, ←linear_map.map_add, prod.mk_add_mk, zero_add, add_zero] lemma e0_mul_e0 : e0 Q * e0 Q = -1 := (ι_sq_scalar _ _).trans $ by simp lemma v_sq_scalar (m : M) : v Q m * v Q m = algebra_map _ _ (Q m) := (ι_sq_scalar _ _).trans $ by simp lemma neg_e0_mul_v (m : M) : -(e0 Q * v Q m) = v Q m * e0 Q := begin refine neg_eq_of_add_eq_zero_right ((ι_mul_ι_add_swap _ _).trans _), dsimp [quadratic_form.polar], simp only [add_zero, mul_zero, mul_one, zero_add, neg_zero, quadratic_form.map_zero, add_sub_cancel, sub_self, map_zero, zero_sub], end lemma neg_v_mul_e0 (m : M) : -(v Q m * e0 Q) = e0 Q * v Q m := begin rw neg_eq_iff_eq_neg, exact (neg_e0_mul_v _ m).symm end @[simp] lemma e0_mul_v_mul_e0 (m : M) : e0 Q * v Q m * e0 Q = v Q m := by rw [←neg_v_mul_e0, ←neg_mul, mul_assoc, e0_mul_e0, mul_neg_one, neg_neg] @[simp] lemma reverse_v (m : M) : reverse (v Q m) = v Q m := reverse_ι _ @[simp] lemma involute_v (m : M) : involute (v Q m) = -v Q m := involute_ι _ @[simp] lemma reverse_e0 : reverse (e0 Q) = e0 Q := reverse_ι _ @[simp] lemma involute_e0 : involute (e0 Q) = -e0 Q := involute_ι _ end equiv_even open equiv_even /-- The embedding from the smaller algebra into the new larger one. -/ def to_even : clifford_algebra Q →ₐ[R] clifford_algebra.even (Q' Q) := begin refine clifford_algebra.lift Q ⟨_, λ m, _⟩, { refine linear_map.cod_restrict _ _ (λ m, submodule.mem_supr_of_mem ⟨2, rfl⟩ _), exact (linear_map.mul_left R $ e0 Q).comp (v Q), rw [subtype.coe_mk, pow_two], exact submodule.mul_mem_mul (linear_map.mem_range_self _ _) (linear_map.mem_range_self _ _), }, { ext1, dsimp only [subalgebra.coe_mul, linear_map.cod_restrict_apply, linear_map.comp_apply, linear_map.mul_left_apply, linear_map.inl_apply, subalgebra.coe_algebra_map], rw [←mul_assoc, e0_mul_v_mul_e0, v_sq_scalar] } end @[simp] lemma to_even_ι (m : M) : (to_even Q (ι Q m) : clifford_algebra (Q' Q)) = e0 Q * v Q m := begin rw [to_even, clifford_algebra.lift_ι_apply, linear_map.cod_restrict_apply], refl, end /-- The embedding from the even subalgebra with an extra dimension into the original algebra. -/ def of_even : clifford_algebra.even (Q' Q) →ₐ[R] clifford_algebra Q := begin /- Recall that we need: * `f ⟨0,1⟩ ⟨x,0⟩ = ι x` * `f ⟨x,0⟩ ⟨0,1⟩ = -ι x` * `f ⟨x,0⟩ ⟨y,0⟩ = ι x * ι y` * `f ⟨0,1⟩ ⟨0,1⟩ = -1` -/ let f : (M × R) →ₗ[R] (M × R) →ₗ[R] clifford_algebra Q := ((algebra.lmul R (clifford_algebra Q)).to_linear_map.comp $ ((ι Q).comp (linear_map.fst _ _ _)) + (algebra.linear_map R _).comp (linear_map.snd _ _ _)).compl₂ (((ι Q).comp (linear_map.fst _ _ _)) - (algebra.linear_map R _).comp (linear_map.snd _ _ _)), have f_apply : ∀ x y, f x y = (ι Q x.1 + algebra_map R _ x.2) * (ι Q y.1 - algebra_map R _ y.2) := λ x y, rfl, have hc : ∀ (r : R) (x : clifford_algebra Q), commute (algebra_map _ _ r) x := algebra.commutes, have hm : ∀ m : M × R, ι Q m.1 * ι Q m.1 - algebra_map R _ m.2 * algebra_map R _ m.2 = algebra_map R _ (Q' Q m), { intro m, rw [ι_sq_scalar, ←ring_hom.map_mul, ←ring_hom.map_sub, sub_eq_add_neg, Q'_apply, sub_eq_add_neg] }, refine even.lift (Q' Q) ⟨f, _, _⟩; simp_rw [f_apply], { intro m, rw [←(hc _ _).symm.mul_self_sub_mul_self_eq, hm] }, { intros m₁ m₂ m₃, rw [←mul_smul_comm, ←mul_assoc, mul_assoc(_ + _), ←(hc _ _).symm.mul_self_sub_mul_self_eq', algebra.smul_def, ←mul_assoc, hm] }, end lemma of_even_ι (x y : M × R) : of_even Q ((even.ι _).bilin x y) = (ι Q x.1 + algebra_map R _ x.2) * (ι Q y.1 - algebra_map R _ y.2) := even.lift_ι _ _ _ _ lemma to_even_comp_of_even : (to_even Q).comp (of_even Q) = alg_hom.id R _ := even.alg_hom_ext (Q' Q) $ even_hom.ext _ _ $ linear_map.ext $ λ m₁, linear_map.ext $ λ m₂, subtype.ext $ let ⟨m₁, r₁⟩ := m₁, ⟨m₂, r₂⟩ := m₂ in calc ↑(to_even Q (of_even Q ((even.ι (Q' Q)).bilin (m₁, r₁) (m₂, r₂)))) = (e0 Q * v Q m₁ + algebra_map R _ r₁) * (e0 Q * v Q m₂ - algebra_map R _ r₂) : by rw [of_even_ι, alg_hom.map_mul, alg_hom.map_add, alg_hom.map_sub, alg_hom.commutes, alg_hom.commutes, subalgebra.coe_mul, subalgebra.coe_add, subalgebra.coe_sub, to_even_ι, to_even_ι, subalgebra.coe_algebra_map, subalgebra.coe_algebra_map] ... = e0 Q * v Q m₁ * (e0 Q * v Q m₂) + r₁ • e0 Q * v Q m₂ - r₂ • e0 Q * v Q m₁ - algebra_map R _ (r₁ * r₂) : by rw [mul_sub, add_mul, add_mul, ←algebra.commutes, ←algebra.smul_def, ←map_mul, ←algebra.smul_def, sub_add_eq_sub_sub, smul_mul_assoc, smul_mul_assoc] ... = v Q m₁ * v Q m₂ + r₁ • e0 Q * v Q m₂ + v Q m₁ * r₂ • e0 Q + (r₁ • e0 Q) * r₂ • e0 Q : have h1 : e0 Q * v Q m₁ * (e0 Q * v Q m₂) = v Q m₁ * v Q m₂, by rw [←mul_assoc, e0_mul_v_mul_e0], have h2 : -(r₂ • e0 Q * v Q m₁) = v Q m₁ * r₂ • e0 Q, by rw [mul_smul_comm, smul_mul_assoc, ←smul_neg, neg_e0_mul_v], have h3 : - algebra_map R _ (r₁ * r₂) = (r₁ • e0 Q) * r₂ • e0 Q, by rw [algebra.algebra_map_eq_smul_one, smul_mul_smul, e0_mul_e0, smul_neg], by rw [sub_eq_add_neg, sub_eq_add_neg, h1, h2, h3] ... = ι _ (m₁, r₁) * ι _ (m₂, r₂) : by rw [ι_eq_v_add_smul_e0, ι_eq_v_add_smul_e0, mul_add, add_mul, add_mul, add_assoc] lemma of_even_comp_to_even : (of_even Q).comp (to_even Q) = alg_hom.id R _ := clifford_algebra.hom_ext $ linear_map.ext $ λ m, calc of_even Q (to_even Q (ι Q m)) = of_even Q ⟨_, (to_even Q (ι Q m)).prop⟩ : by rw subtype.coe_eta ... = (ι Q 0 + algebra_map R _ 1) * (ι Q m - algebra_map R _ 0) : begin simp_rw to_even_ι, exact of_even_ι Q _ _, end ... = ι Q m : by rw [map_one, map_zero, map_zero, sub_zero, zero_add, one_mul] /-- Any clifford algebra is isomorphic to the even subalgebra of a clifford algebra with an extra dimension (that is, with vector space `M × R`), with a quadratic form evaluating to `-1` on that new basis vector. -/ @[simps] def equiv_even : clifford_algebra Q ≃ₐ[R] clifford_algebra.even (Q' Q) := alg_equiv.of_alg_hom (to_even Q) (of_even Q) (to_even_comp_of_even Q) (of_even_comp_to_even Q) /-- The representation of the clifford conjugate (i.e. the reverse of the involute) in the even subalgebra is just the reverse of the representation. -/ lemma coe_to_even_reverse_involute (x : clifford_algebra Q) : ↑(to_even Q (reverse (involute x))) = reverse (to_even Q x : clifford_algebra (Q' Q)) := begin induction x using clifford_algebra.induction, case h_grade0 : r { simp only [alg_hom.commutes, subalgebra.coe_algebra_map, reverse.commutes] }, case h_grade1 : m { simp only [involute_ι, subalgebra.coe_neg, to_even_ι, reverse.map_mul, reverse_v, reverse_e0, reverse_ι, neg_e0_mul_v, map_neg] }, case h_mul : x y hx hy { simp only [map_mul, subalgebra.coe_mul, reverse.map_mul, hx, hy] }, case h_add : x y hx hy { simp only [map_add, subalgebra.coe_add, hx, hy] }, end /-! ### Constructions needed for `clifford_algebra.even_equiv_even_neg` -/ /-- One direction of `clifford_algebra.even_equiv_even_neg` -/ def even_to_neg (Q' : quadratic_form R M) (h : Q' = -Q) : clifford_algebra.even Q →ₐ[R] clifford_algebra.even Q' := even.lift Q { bilin := -(even.ι Q' : _).bilin, contract := λ m, by simp_rw [linear_map.neg_apply, even_hom.contract, h, quadratic_form.neg_apply, map_neg, neg_neg], contract_mid := λ m₁ m₂ m₃, by simp_rw [linear_map.neg_apply, neg_mul_neg, even_hom.contract_mid, h, quadratic_form.neg_apply, smul_neg, neg_smul] } @[simp] lemma even_to_neg_ι (Q' : quadratic_form R M) (h : Q' = -Q) (m₁ m₂ : M) : even_to_neg Q Q' h ((even.ι Q).bilin m₁ m₂) = -(even.ι Q').bilin m₁ m₂ := even.lift_ι _ _ m₁ m₂ lemma even_to_neg_comp_even_to_neg (Q' : quadratic_form R M) (h : Q' = -Q) (h' : Q = -Q') : (even_to_neg Q' Q h').comp (even_to_neg Q Q' h) = alg_hom.id R _ := begin ext m₁ m₂ : 4, dsimp only [even_hom.compr₂_bilin, linear_map.compr₂_apply, alg_hom.to_linear_map_apply, alg_hom.comp_apply, alg_hom.id_apply], rw [even_to_neg_ι, map_neg, even_to_neg_ι, neg_neg] end /-- The even subalgebras of the algebras with quadratic form `Q` and `-Q` are isomorphic. Stated another way, `𝒞ℓ⁺(p,q,r)` and `𝒞ℓ⁺(q,p,r)` are isomorphic. -/ @[simps] def even_equiv_even_neg : clifford_algebra.even Q ≃ₐ[R] clifford_algebra.even (-Q) := alg_equiv.of_alg_hom (even_to_neg Q _ rfl) (even_to_neg (-Q) _ (neg_neg _).symm) (even_to_neg_comp_even_to_neg _ _ _ _) (even_to_neg_comp_even_to_neg _ _ _ _) end clifford_algebra
3e42c39281f85d4eecc0dd2644c430b2a7951bc0
ef47cc39429c8f578004338bf040c9c309b26766
/src/solutions/friday/manifolds.lean
d1813a54a59b71ee99f1650e16dcb9f359f0a59b
[]
no_license
farmanb/lftcm2020
29f1c646437a8f8b00ee2e07c8b663ca04bfa16f
1948bfaf58e3b340b39cd9b8366aa4f13e5ffa7d
refs/heads/master
1,669,697,152,764
1,595,275,412,000
1,595,275,412,000
285,654,242
0
0
null
1,596,742,086,000
1,596,742,085,000
null
UTF-8
Lean
false
false
41,904
lean
import for_mathlib.manifolds noncomputable theory open_locale manifold classical big_operators open set universe u /-! ## Reminder on updating the exercises These instructions are now available at: https://leanprover-community.github.io/lftcm2020/exercises.html To get a new copy of the exercises, run the following commands in your terminal: ``` leanproject get lftcm2020 cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises code lftcm2020 ``` To update your exercise files, run the following commands: ``` cd /path/to/lftcm2020 git pull leanproject get-mathlib-cache ``` Don’t forget to copy the updated files to `src/my_exercises`. -/ /-! ## An overview of manifolds in Lean, discussing design decisions Warning: there are sorries in this section, they are not supposed to be filled! The exercises section start later, and there you will have plenty of sorries to fill. What is a manifold? 1) allow field other than `ℝ` or `ℂ`? 2) allow infinite dimension? 3) allow boundary? 4) allow model space depending on the point of the manifold? Bourbaki: 2, 4 (and just definitions and statements, no proofs!) Lean: 1, 2, 3 Perelman geometrization theorem : any compact connected irreducible 3-manifold can be cut along tori into finitely many pieces, each of which has a _geometric structure_ of finite volume, i.e., it is locally like a model space, with changes of coordinates given locally by the action of a Lie group Typical dynamics theorem : let `M` be a compact manifold, and `f : M → M` a map with property such and such. Then ... Or : Consider a hyperbolic surface of genus `g`, and a random geodesic of length `T`. How many times does it typically self-intersect? Manifold in Lean: * charted space structure, i.e., set of local homeos to a model space. This is data, fixed once and for all (and a typeclass) * compatibility condition, i.e., the change of coordinates should belong to some subgroup of the group of local homeos of the model space. This is Prop (and a typeclass). The same manifold can be at the same time an analytic manifold, a smooth manifold and a topological manifold (with the same fixed atlas). * A charted space is a smooth manifold (with corners) if it is compatible with the smooth groupoid on the model space. To cover uniformly both situations with and without boundary, the smooth groupoid is with respect to a map `I : H → E` (think of `H` as the half-space and `E` the full space), which is the identity in the boundaryless situation, the inclusion in the half-space situation. This map `I` is called a _model with corners_. The most standard ones (identity in `ℝ^n` and inclusion of half-space in `ℝ^n`) have dedicated notations: `𝓡 n` and `𝓡∂ n`. -/ #check charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) #check has_groupoid (Icc (0 : ℝ) 1) (times_cont_diff_groupoid ∞ (𝓡∂ 1)) #check smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) -- atlases are not maximal in general #check (times_cont_diff_groupoid ∞ (𝓡∂ 1)).maximal_atlas (Icc (0 : ℝ) 1) -- let's try to put a smooth manifold structure on the sphere -- (we don't have submanifolds yet, but it's coming in the near future) @[derive topological_space] definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space (fin (n+1))) 1 instance (n : ℕ) : has_coe (sphere n) (euclidean_space (fin (n+1))) := ⟨subtype.val⟩ instance (n : ℕ) : charted_space (euclidean_space (fin n)) (sphere n) := { atlas := begin sorry end, chart_at := begin sorry end, mem_chart_source := begin sorry end, chart_mem_atlas := begin sorry end } instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) := { compatible := begin assume e e' he he', sorry end } -- smooth functions def inc (n : ℕ) : sphere n → euclidean_space (fin (n+1)) := λ p : sphere n, (p : euclidean_space (fin (n+1))) lemma inc_smooth (n : ℕ) : times_cont_mdiff (𝓡 n) (𝓡 (n+1)) ∞ (inc n) := begin rw times_cont_mdiff_iff, split, { exact continuous_subtype_coe, }, { assume x y, sorry } end lemma inc_continuous (n : ℕ) : continuous (inc n) := (inc_smooth n).continuous lemma inc_mdifferentiable (n : ℕ) : mdifferentiable (𝓡 n) (𝓡 (n+1)) (inc n) := (inc_smooth n).mdifferentiable le_top -- tangent space and tangent bundles example (n : ℕ) (p : sphere n) (v : tangent_space (𝓡 n) p) : tangent_bundle (𝓡 n) (sphere n) := ⟨p, v⟩ -- tangent map, derivatives example (n : ℕ) : times_cont_mdiff ((𝓡 n).prod (𝓡 n)) ((𝓡 (n+1)).prod (𝓡 (n+1))) ∞ (tangent_map (𝓡 n) (𝓡 (n+1)) (inc n)) := (inc_smooth n).times_cont_mdiff_tangent_map le_top example (n : ℕ) (f : sphere n → sphere (n^2)) (p : sphere n) (v : tangent_space (𝓡 n) p) : mfderiv (𝓡 n) (𝓡 (n^2)) f p v = (tangent_map (𝓡 n) (𝓡 (n^2)) f ⟨p, v⟩).2 := rfl /- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal embedding? Note that we haven't defined immersions in mathlib, but you can jut require that the fiber derivative is injective everywhere, which is easy to express if you know that the derivative of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is `mfderiv (𝓡 2) (𝓡 3) f x`. Don't forget to require the global smoothness of the map! You may need to know that the interval `[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure, where the corresponding model with corners is called `𝓡∂ 1`. -/ theorem sphere_eversion : ∃ f : (Icc (0 : ℝ) 1) × sphere 2 → euclidean_space (fin 3), times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f ∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2), function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p) ∧ ∀ (p : sphere 2), f (0, p) = p ∧ ∀ (p : sphere 2), f (1, p) = - p := sorry /- Dicussing three (controversial?) design decisions #### Local homeos What is a local homeo `f` between an open subset of `E` and an open subset of `F`? 1) a map defined on a subtype: `f x` only makes sense for `x : f.source` 2) a map defined on the whole space `E`, but taking values in `option F = F ∪ {junk}`, with `f x = junk` when `x ∉ f.source` 3) a map defined on the whole space `E`, taking values in `F`, and we don't care about its values outside of `f.source`. Just like division by zero! But worse: * issue with 1): you keep intersecting chart domains. But the subtype `u ∩ v` is not the same as the subtype `v ∩ u`, so you keep adding casts everywhere * issue with 2): if you want to say that a chart is smooth, then you define to define smooth functions between `option E` and `option F` when `E` and `F` are vector spaces. All notions need to be redefined with `option`. * issue with 3): it works perfectly well, but it makes mathematicians unhappy/uneasy (and it is *not* equivalent to 1) or 2) when one of the spaces is empty) I picked 3) #### Tangent vectors What is a tangent vector (for a manifold `M` modelled on a vector space `E`)? 1) An equivalence class of germs of curves 2) A derivation 3) Physicist point of view: I don't know what a tangent vector is, but I know in charts. Mathematician's interpretation: equivalence class of `(e, v)` where `e` is a chart at `x`, `v` a vector in the vector space, and `(e, v) ∼ (e', v')` if `D(e' ∘ e ⁻¹) v = v'` 4) ... Issues: 1) Pictures are pretty, but this doesn't bring anything compared to 3) when you go down to details. And what about boundaries, where you can only have a half-curve 2) Need partitions of unity to show that this is local and coincides with the usual point of view. Doesn't work well in finite smoothness, nor in complex manifolds 3) Fine, works in all situations, but requires a lot of work to define the equivalence classes, the topology, check that the topology is compatible with the vector space structure, and so on. In a vector space, the tangent space is not defeq to the vector space itself 4) Pick one favorite chart at `x`, say `e_x`, and *define* the tangent space at `x` to be `E`, but "seen" in the chart `e_x` (this will show up in the definition of the derivative : the derivative of `f : M → M'` at `x` is defined to be the derivative of the map `e_{f x} ∘ f ∘ e_x⁻¹`). Works perfectly fine, but makes mathematicians unhappy/uneasy. (Axiom of choice? In fact we put the choice of `e_x` in the *definition* of charted spaces, so not further choice) I picked 4) #### Smooth functions in manifolds with boundary Usual definition of smooth functions in a half space: extend to a smooth function a little bit beyond the boundary, so one only really needs to speak of smooth functions in open subsets of vector spaces. When you define the derivative, you will need to check that it does not depend on the choice of the extension. Even worse when you want to define the tangent bundle: choose an open extension of your manifold with boundary, and then check that the restriction of the tangent bundle does not depend on the choice of the extension. Very easy when handwaving, nightmare to formalize. (What is the extension of the manifold with boundary? Another type?) Instead, if you define derivatives in (non-open) domains, you can talk of smooth functions in domains, and do everything without extending. Need to know this early enough: when starting to define derivatives, you should already think of manifolds with boundaries! That's what we did in mathlib. Difficulty: if a domain `s` is too small (think `s = ℝ ⊆ ℝ^2`), the values of `f` on `s` do not prescribe uniquely a derivative, so `fderiv_within_at ℝ f s x` may behave badly: derivative of a sum might be different from sum of derivatives, as there is an arbitrary choice to be made. This does not happen with the half-space, as it is large enough: derivatives within domains only work well if the tangent directions span the whole space. Predicate `unique_diff_on` for sets in vector spaces. You won't find this in books! -/ /-! ## Exercises -/ /-! ### Local homeomorphisms Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only relevant set is the *source*, which should be mapped homeomorphically to the *target*. -/ -- set up a simple helper simp lemma to simplify our life later. @[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 := begin -- sorry simp [neg_lt, and_comm], -- sorry end /- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/ def my_first_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, -x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/, map_source' := begin -- sorry assume x hx, simp [hx], -- sorry end, map_target' := begin -- sorry assume x hx, simp [hx], -- sorry end, left_inv' := begin -- sorry simp, -- sorry end, right_inv' := begin -- sorry simp, -- sorry end, open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/, open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/, continuous_to_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/, continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ } /- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/ lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 := begin -- sorry exact ne_of_lt (lt_trans h.2 (by norm_num)) -- sorry end lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 := begin -- sorry assume h', simp at h, linarith, -- sorry end /- Now, define a second local homeomorphism which is almost like the previous one. You may find the following lemma useful for `continuous_to_fun`: -/ #check continuous_on.congr def my_second_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, if x = 3 then 0 else - x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/, map_source' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/, map_target' := /- inline sorry -/λ x hx, by simp [hx]/- inline sorry -/, left_inv' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/, right_inv' := /- inline sorry -/λ x hx, by simp [hx, neg_ne_3_of_mem_Ioo hx]/- inline sorry -/, open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/, open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/, continuous_to_fun := begin -- sorry refine continuous_neg.continuous_on.congr (λ x hx, _), simp [hx, ne_3_of_mem_Ioo hx], -- sorry end, continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ } /- Although the two above local homeos are the same for all practical purposes as they coincide where relevant, they are not *equal*: -/ lemma my_first_local_homeo_ne_my_second_local_homeo : my_first_local_homeo ≠ my_second_local_homeo := begin -- sorry assume h, have : my_first_local_homeo 3 = my_second_local_homeo 3, by rw h, simp [my_first_local_homeo, my_second_local_homeo] at this, linarith, -- sorry end /- The right equivalence relation for local homeos is not equality, but `eq_on_source`. Indeed, the two local homeos we have defined above coincide from this point of view. -/ #check local_homeomorph.eq_on_source lemma eq_on_source_my_first_local_homeo_my_second_local_homeo : local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo := begin -- sorry refine ⟨rfl, λ x hx, _⟩, simp [my_first_local_homeo, my_second_local_homeo, ne_3_of_mem_Ioo hx], -- sorry end /-! ### An example of a charted space structure on `ℝ` A charted space is a topological space together with a set of local homeomorphisms to a model space, whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space structure with model space `ℝ`, where the unique chart is the identity: -/ #check charted_space_self ℝ /- For educational purposes only, we will put another charted space structure on `ℝ` using the local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the topology. -/ @[derive topological_space] def myℝ : Type := ℝ instance : charted_space ℝ myℝ := { atlas := { local_homeomorph.refl ℝ, my_first_local_homeo }, chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ, mem_chart_source := begin -- sorry assume x, split_ifs, { exact h }, { exact mem_univ _ } -- sorry end, chart_mem_atlas := begin -- sorry assume x, split_ifs; simp, -- sorry end } /- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of coordinates are smooth. In Lean, this is written with `has_groupoid`. A groupoid is a set of local homeomorphisms of the model space (for example, local homeos that are smooth on their domain). A charted space admits the groupoid as a structure groupoid if all the changes of coordinates belong to the groupoid. There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again `model_with_corners_self ℝ ℝ`, let us introduce a shortcut -/ abbreviation 𝓡1 := model_with_corners_self ℝ ℝ /- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`, but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not the same as `ℝ`! Still, since they are of the same nature, the notation we have just introduced is very close, compare `𝓡1` with `𝓡 1` (and try not to get confused): -/ instance smooth_myℝ : has_groupoid myℝ (times_cont_diff_groupoid ∞ 𝓡1) := begin -- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth -- and their inverse are smooth. For symmetry reasons, it suffices to check one direction apply has_groupoid_of_pregroupoid, -- take two charts `e` and `e'` assume e e' he he', -- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp` -- and then follow the advice simp [atlas] at he he', dsimp, -- to continue, some hints: -- (1) don't hesitate to use the fact that the restriction of a smooth function to a -- subset is still smooth there (`times_cont_diff.times_cont_diff_on`) -- (2) hopefully, there is a theorem saying that the negation function is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. -- sorry rcases he with rfl|rfl; rcases he' with rfl|rfl, { exact times_cont_diff_id.times_cont_diff_on }, { exact times_cont_diff_id.neg.times_cont_diff_on }, { exact times_cont_diff_id.neg.times_cont_diff_on }, { convert times_cont_diff_id.times_cont_diff_on, ext x, simp [my_first_local_homeo], }, -- sorry end /- The statement of the previous instance is not very readable. There is a shortcut notation: -/ instance : smooth_manifold_with_corners 𝓡1 myℝ := {} /- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/ def my_map : myℝ → ℝ := λ x, x /- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ` and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/ /- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the same. So `continuous_id` might help. -/ lemma continuous_my_map : continuous my_map := -- sorry continuous_id -- sorry /- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas on `myℝ` has two elements, while the atlas on `ℝ` has one single element. Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map` is smooth in the usual sense (as a map between vector spaces): -/ -- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry /- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the smoothness of a map, we should always specify explicitly the model with corners we are using, because there might be several around (think of a complex manifold that you may want to consider as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/ lemma times_cont_mdiff_my_map : times_cont_mdiff 𝓡1 𝓡1 ∞ my_map := begin -- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for -- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form. rw times_cont_mdiff_iff, simp only [continuous_my_map] with mfld_simps, -- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ` -- is the identity. assume x y, -- sorry simp [my_map, (∘), chart_at], split_ifs, { exact times_cont_diff_id.neg.times_cont_diff_on }, { exact times_cont_diff_id.times_cont_diff_on }, -- sorry end /- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also be a smooth manifold. -/ -- the type `tangent_bundle 𝓡1 myℝ` makes sense #check tangent_bundle 𝓡1 myℝ /- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`). So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/ example : tangent_bundle 𝓡1 myℝ := ((4 : ℝ), 0) /- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner, and this instance is not really needed. -/ instance tangent_bundle_myℝ : smooth_manifold_with_corners (𝓡1.prod 𝓡1) (tangent_bundle 𝓡1 myℝ) := -- sorry by apply_instance -- sorry /- NB: the model space for the tangent bundle to a product manifold or a tangent space is not `ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally equal. And this would be bad. -/ #check tangent_bundle.charted_space 𝓡1 myℝ /- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the map). Let us check that the `tangent_map` of `my_map` is smooth. -/ lemma times_cont_mdiff_tangent_map_my_map : times_cont_mdiff (𝓡1.prod 𝓡1) (𝓡1.prod 𝓡1) ∞ (tangent_map 𝓡1 𝓡1 my_map) := begin -- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth -- map is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. -- sorry exact times_cont_mdiff_my_map.times_cont_mdiff_tangent_map le_top, -- sorry end /- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could try to build the homeomorphism by hand, using `tangent_map 𝓡1 𝓡1 my_map` in one direction and a similar map in the other direction, but it is probably more efficient to use one of the charts of the tangent bundle. Remember, the model space for `tangent_bundle 𝓡1 myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to construct a homeomorphism with `model_prod ℝ ℝ`. -/ def my_homeo : tangent_bundle 𝓡1 myℝ ≃ₜ (ℝ × ℝ) := begin -- sorry let p : tangent_bundle 𝓡1 myℝ := ((4 : ℝ), 0), let F := chart_at (model_prod ℝ ℝ) p, have A : ¬ ((4 : ℝ) < 1), by norm_num, have S : F.source = univ, by simp [F, chart_at, A, @local_homeomorph.refl_source ℝ _], have T : F.target = univ, by simp [F, chart_at, A, @local_homeomorph.refl_target ℝ _], exact F.to_homeomorph_of_source_eq_univ_target_eq_univ S T, -- sorry end /- Up to now, we have never used the definition of the tangent bundle, and this corresponds to the usual mathematical practice: one doesn't care if the tangent space is defined using germs of curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well, together with the fact that the tangent bundle to a vector space is the product). If you want to know more about the internals of the tangent bundle in mathlib, you can browse through the next section, but it is maybe wiser to skip it on first reading, as it is not needed to use the library -/ section you_should_probably_skip_this /- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent bundle is just `M × E` -/ lemma tangent_bundle_myℝ_is_prod : tangent_bundle 𝓡1 myℝ = (myℝ × ℝ) := /- inline sorry -/rfl/- inline sorry -/ /- This means that you can specify a point in the tangent bundle as a pair `(x, y)`. However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle 𝓡1 myℝ` is *not* the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the manifold and the charts. In vector spaces, the tangent space is canonically the product space, with the same topology, as there is only one chart so there is no strange gluing at play. The equality of the topologies is given in `tangent_bundle_model_space_topology_eq_prod`, but they are not definitionally equal so one can get strange behavior if abusing identifications. Let us register the identification explicitly, as a homeomorphism: -/ def tangent_bundle_vector_space_triv (E : Type u) [normed_group E] [normed_space ℝ E] : tangent_bundle (model_with_corners_self ℝ E) E ≃ₜ E × E := { to_fun := id, inv_fun := id, left_inv := /- inline sorry -/λ x, rfl/- inline sorry -/, right_inv := /- inline sorry -/λ x, rfl/- inline sorry -/, continuous_to_fun := begin -- if you think that `continuous_id` should work but `exact continuous_id` fails, you -- can try `convert continuous_id`: it might show you what doesn't match and let you -- fix it afterwards. -- sorry convert continuous_id, exact (tangent_bundle_model_space_topology_eq_prod _ _).symm -- sorry end, continuous_inv_fun := begin -- sorry convert continuous_id, exact (tangent_bundle_model_space_topology_eq_prod _ _) -- sorry end } /- Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the tangent bundle is *not* the product space with the product topology, as we have used various charts so the gluing is not trivial. The following exercise unfolds the definition to see what is going on. It is not a reasonable exercise, in the sense that one should never ever do this when working with a manifold! -/ lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) : let p : tangent_bundle 𝓡1 myℝ := ((3 : ℝ), 0) in chart_at (model_prod ℝ ℝ) p (x, v) = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) := begin -- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!) -- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you -- are left with a statement speaking of derivatives of real functions, without any manifold code left. -- sorry have : ¬ ((3 : ℝ) < 1), by norm_num, simp only [chart_at, this, mem_Ioo, if_false, and_false], dsimp [tangent_bundle_core, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', topological_fiber_bundle_core.index_at, basic_smooth_bundle_core.to_topological_fiber_bundle_core], split_ifs, { simp only [chart_at, h, my_first_local_homeo, if_true, fderiv_within_univ, prod.mk.inj_iff, mem_Ioo, fderiv_neg differentiable_at_id', fderiv_id', id.def, continuous_linear_map.coe_id', continuous_linear_map.neg_apply] with mfld_simps }, { simp only [chart_at, h, fderiv_within_univ, mem_Ioo, if_false, @local_homeomorph.refl_symm ℝ, fderiv_id, continuous_linear_map.coe_id'] with mfld_simps } -- sorry end end you_should_probably_skip_this /-! ### The language of manifolds In this paragraph, we will try to write down interesting statements of theorems, without proving them. The goal here is that Lean should not complain on the statement, but the proof should be sorried. -/ /- Here is a first example, already filled up, to show you how diffeomorphisms are currently named (we will probably introduce an abbreviation, but this hasn't been done yet). Don't try to fill the sorried proof! -/ /-- Two zero-dimensional connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_zero_dim_connected (M M' : Type*) [topological_space M] [topological_space M'] [charted_space (euclidean_space (fin 0)) M] [charted_space (euclidean_space (fin 0)) M'] [connected_space M] [connected_space M'] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') := sorry /- Do you think that this statement is correct? (note that we have not assumed that our manifolds are smooth, nor that they are separated, but this is maybe automatic in zero dimension). Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content (and adding what is needed before the colon). Don't try to fill the sorried proof! -/ /-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_one_dim_compact_connected -- omit (M M' : Type*) [topological_space M] [topological_space M'] [charted_space (euclidean_space (fin 1)) M] [charted_space (euclidean_space (fin 1)) M'] [connected_space M] [connected_space M'] [compact_space M] [compact_space M'] [t2_space M] [t2_space M'] [smooth_manifold_with_corners (𝓡 1) M] [smooth_manifold_with_corners (𝓡 1) M'] -- omit : -- sorry nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M M') -- sorry := sorry /- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise. Note that Lean won't complain if you don't put these assumptions, as the theorem would still make sense, but it would just turn out to be wrong. The previous statement is not really satisfactory: we would instead like to express that any such manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth manifold yet. Since we have cheated and introduced it (with sorries) at the beginning of the tutorial, let's cheat again and use it to reformulate the previous statement. -/ -- the next result is not trivial, leave it sorried (but you can work on it if you don't like -- manifolds and prefer topology -- then please PR it to mathlib!). instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry /- The next two instances are easier to prove, you can prove them or leave them sorried as you like. For the second one, you may need to use facts of the library such as -/ #check compact_iff_compact_space #check metric.compact_iff_closed_bounded instance (n : ℕ) : t2_space (sphere n) := begin -- sorry dunfold sphere, apply_instance -- sorry end instance (n : ℕ) : compact_space (sphere n) := begin -- sorry dunfold sphere, apply compact_iff_compact_space.1, rw metric.compact_iff_closed_bounded, split, { exact metric.is_closed_sphere }, { rw metric.bounded_iff_subset_ball (0 : euclidean_space (fin (n+1))), exact ⟨1, metric.sphere_subset_closed_ball⟩ } -- sorry end /- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to the circle. Here, you should fill the `sorry` (but luckily you may use `diffeomorph_of_one_dim_compact_connected`). -/ theorem diffeomorph_circle_of_one_dim_compact_connected (M : Type*) [topological_space M] [charted_space (euclidean_space (fin 1)) M] [connected_space M] [compact_space M] [t2_space M] [smooth_manifold_with_corners (𝓡 1) M] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) := -- sorry diffeomorph_of_one_dim_compact_connected M (sphere 1) -- sorry /- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`? (see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind, as in general we only work with one differentiable structure on a space, but it is perfectly capable of expressing this fact if one uses the `@` version of some definitions. Don't try to fill the sorried proof! -/ theorem exotic_ℝ4 : -- sorry let E := (euclidean_space (fin 4)) in ∃ f : ℝ → charted_space E E, ∀ i, @has_groupoid E _ E _ (f i) (times_cont_diff_groupoid ∞ (𝓡 4)) ∧ ∀ i j, nonempty (@structomorph _ _ (times_cont_diff_groupoid ∞ (𝓡 4)) E E _ _ (f i) (f j)) → i = j -- sorry := sorry /-! ### Smooth functions on `[0, 1]` In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially nothing in this direction for now in the library. The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector spaces and `times_cont_mdiff_on` for functions between manifolds. Lemma times_cont_mdiff_g : the inclusion `g` of `[0, 1]` in `ℝ` is smooth. Lemma msmooth_of_smooth : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`. Definition : construct a function `f` from `ℝ` to `[0,1]` which is the identity on `[0, 1]`. Theorem : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ` Hint for Theorem 4: don't try to unfold the definition of the tangent bundle, it will only get you into trouble. Instead, use the derivatives of the maps `f` and `g`, and rely on functoriality to check that they are inverse to each other. (This advice is slightly misleading as these derivatives do not go between the right spaces, so you will need to massage them a little bit). A global advice: don't hesitate to use and abuse `simp`, it is the main workhorse in this area of mathlib. -/ /- After doing the exercise myself, I realized it was (way!) too hard. So I will give at least the statements of the lemmas, to guide you a little bit more. To let you try the original version if you want, I have left a big blank space to avoid spoilers. -/ def g : Icc (0 : ℝ) 1 → ℝ := subtype.val -- smoothness results for `euclidean_space` are expressed for general `L^p` spaces -- (as `euclidean_space` has the `L^2` norm), in: #check pi_Lp.times_cont_diff_coord #check pi_Lp.times_cont_diff_on_iff_coord lemma times_cont_mdiff_g : times_cont_mdiff (𝓡∂ 1) 𝓡1 ∞ g := begin -- sorry rw times_cont_mdiff_iff, refine ⟨continuous_subtype_val, λ x y, _⟩, by_cases h : (x : ℝ) < 1, { simp only [g, chart_at, h, Icc_left_chart, function.comp, model_with_corners_euclidean_half_space, add_zero, dif_pos, if_true, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, subtype.coe_mk, subtype.val_eq_coe] with mfld_simps, refine (pi_Lp.times_cont_diff_coord 0).times_cont_diff_on.congr (λ x hx, _), simp only [mem_inter_eq, mem_set_of_eq] at hx, simp only [hx, le_of_lt hx.right.left, min_eq_left, max_eq_left] }, { simp only [chart_at, h, Icc_right_chart, function.comp, model_with_corners_euclidean_half_space, dif_pos, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, if_false, subtype.coe_mk, subtype.val_eq_coe, g] with mfld_simps, have : times_cont_diff ℝ ⊤ (λ (x : euclidean_space (fin 1)), 1 - x 0) := times_cont_diff_const.sub (pi_Lp.times_cont_diff_coord 0), apply this.times_cont_diff_on.congr (λ x hx, _), simp only [mem_inter_eq, mem_set_of_eq] at hx, have : 0 ≤ 1 - x 0, by linarith, simp only [hx, this, max_eq_left] } -- sorry end lemma msmooth_of_smooth {f : ℝ → Icc (0 : ℝ) 1} {s : set ℝ} (h : times_cont_diff_on ℝ ∞ (λ x, (f x : ℝ)) s) : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f s := begin -- sorry rw times_cont_mdiff_on_iff, split, { have : embedding (subtype.val : Icc (0 : ℝ) 1 → ℝ) := embedding_subtype_coe, exact (embedding.continuous_on_iff this).2 h.continuous_on }, simp only with mfld_simps, assume y, by_cases hy : (y : ℝ) < 1, { simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_left_chart, pi_Lp.times_cont_diff_on_iff_coord], apply h.mono (inter_subset_left _ _) }, { simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_right_chart, pi_Lp.times_cont_diff_on_iff_coord], assume i, apply (times_cont_diff_on_const.sub h).mono (inter_subset_left _ _) } -- sorry end /- A function from `ℝ` to `[0,1]` which is the identity on `[0,1]`. -/ def f : ℝ → Icc (0 : ℝ) 1 := λ x, ⟨max (min x 1) 0, by simp [le_refl, zero_le_one]⟩ lemma times_cont_mdiff_on_f : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f (Icc 0 1) := begin -- sorry apply msmooth_of_smooth, apply times_cont_diff_id.times_cont_diff_on.congr, assume x hx, simp at hx, simp [f, hx], -- sorry end lemma fog : f ∘ g = id := begin -- sorry ext x, rcases x with ⟨x', h'⟩, simp at h', simp [f, g, h'], -- sorry end lemma gof : ∀ x ∈ Icc (0 : ℝ) 1, g (f x) = x := begin -- sorry assume x hx, simp at hx, simp [g, f], simp [hx], -- sorry end def G : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ := λ p, (p.1, (tangent_map (𝓡∂ 1) 𝓡1 g p).2) lemma continuous_G : continuous G := begin -- sorry apply continuous.prod_mk (tangent_bundle_proj_continuous _ _), refine continuous_snd.comp _, have Z := times_cont_mdiff_g.continuous_tangent_map le_top, convert Z, exact (tangent_bundle_model_space_topology_eq_prod ℝ 𝓡1).symm -- sorry end /- in the definition of `F`, we use the map `tangent_bundle_vector_space_triv` (which is just the identity pointwise) to make sure that Lean is not lost between the different topologies. -/ def F : (Icc (0 : ℝ) 1) × ℝ → tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) := λ p, tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) ((tangent_bundle_vector_space_triv ℝ).symm (p.1, p.2)) lemma continuous_F : continuous F := begin -- sorry rw continuous_iff_continuous_on_univ, apply (times_cont_mdiff_on_f.continuous_on_tangent_map_within le_top _).comp, { apply ((tangent_bundle_vector_space_triv ℝ).symm.continuous.comp _).continuous_on, apply (continuous_subtype_coe.comp continuous_fst).prod_mk continuous_snd }, { rintros ⟨⟨x, hx⟩, v⟩ _, simp [tangent_bundle_vector_space_triv], exact hx }, { rw unique_mdiff_on_iff_unique_diff_on, exact unique_diff_on_Icc_zero_one } -- sorry end lemma FoG : F ∘ G = id := begin -- sorry ext1 p, rcases p with ⟨x, v⟩, simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f], dsimp, split, { rcases x with ⟨x', h'⟩, simp at h', simp [h'] }, { change (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) (tangent_map (𝓡∂ 1) 𝓡1 g (x, v))).snd = v, rw [← tangent_map_within_univ, ← tangent_map_within_comp_at, fog, tangent_map_within_univ, tangent_map_id], { refl }, { apply times_cont_mdiff_on_f.mdifferentiable_on le_top, simpa [g] using x.2 }, { apply (times_cont_mdiff_g.times_cont_mdiff_at.mdifferentiable_at le_top).mdifferentiable_within_at }, { assume z hz, simpa [g] using z.2 }, { apply unique_mdiff_on_univ _ (mem_univ _) } } -- sorry end lemma GoF : G ∘ F = id := begin -- sorry ext1 p, rcases p with ⟨x, v⟩, simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f], dsimp, split, { rcases x with ⟨x', h'⟩, simp at h', simp [h'] }, { have A : unique_mdiff_within_at 𝓡1 (Icc 0 1) ((x : ℝ), v).fst, { rw unique_mdiff_within_at_iff_unique_diff_within_at, apply unique_diff_on_Icc_zero_one _ x.2 }, change (tangent_map (𝓡∂ 1) 𝓡1 g (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) (x, v))).snd = v, rw [← tangent_map_within_univ, ← tangent_map_within_comp_at _ _ _ _ A], { have : tangent_map_within 𝓡1 𝓡1 (g ∘ f) (Icc 0 1) (x, v) = tangent_map_within 𝓡1 𝓡1 id (Icc 0 1) (x, v) := tangent_map_within_congr gof _ x.2 A, rw [this, tangent_map_within_id A] }, { apply times_cont_mdiff_g.times_cont_mdiff_on.mdifferentiable_on le_top _ (mem_univ _) }, { apply times_cont_mdiff_on_f.mdifferentiable_on le_top _ x.2 }, { simp only [preimage_univ, subset_univ], } } -- sorry end def my_tangent_homeo : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) ≃ₜ (Icc (0 : ℝ) 1) × ℝ := -- sorry { to_fun := G, inv_fun := F, continuous_to_fun := continuous_G, continuous_inv_fun := continuous_F, left_inv := λ p, show (F ∘ G) p = id p, by rw FoG, right_inv := λ p, show (G ∘ F) p = id p, by rw GoF } -- sorry /-! ### Further things to do 1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`? 2) Try to express and then prove the local inverse theorem in real manifolds: if a map between real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is a local homeomorphism around each point. We already have versions of this statement in mathlib for functions between vector spaces, but this is very much a work in progress. 3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib is ready for this, as the proofs I am thinking of are currently a little bit too high-powered. If you manage to do it, you should absolutely PR it!) 4) Why not contribute to the proof of `sphere_eversion`? You can have a look at https://leanprover-community.github.io/sphere-eversion/ to learn more about this project by Patrick Massot. -/
b76e65d2be30f07e4555ec8275e753fe36d8df21
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/complex/real_deriv.lean
8269ce29d863ed140259d36adfb6d468ba987070
[ "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
7,483
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yourong Zang -/ import analysis.calculus.times_cont_diff import analysis.complex.conformal import analysis.calculus.conformal.normed_space /-! # Real differentiability of complex-differentiable functions `has_deriv_at.real_of_complex` expresses that, if a function on `ℂ` is differentiable (over `ℂ`), then its restriction to `ℝ` is differentiable over `ℝ`, with derivative the real part of the complex derivative. `differentiable_at.conformal_at` states that a real-differentiable function with a nonvanishing differential from the complex plane into an arbitrary complex-normed space is conformal at a point if it's holomorphic at that point. This is a version of Cauchy-Riemann equations. `conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj` proves that a real-differential function with a nonvanishing differential between the complex plane is conformal at a point if and only if it's holomorphic or antiholomorphic at that point. ## TODO * The classical form of Cauchy-Riemann equations * On a connected open set `u`, a function which is `conformal_at` each point is either holomorphic throughout or antiholomorphic throughout. ## Warning We do NOT require conformal functions to be orientation-preserving in this file. -/ section real_deriv_of_complex /-! ### Differentiability of the restriction to `ℝ` of complex functions -/ open complex variables {e : ℂ → ℂ} {e' : ℂ} {z : ℝ} /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_strict_deriv_at.real_of_complex (h : has_strict_deriv_at e e' z) : has_strict_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_strict_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_strict_fderiv_at, have B : has_strict_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_strict_fderiv_at.restrict_scalars ℝ, have C : has_strict_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_strict_fderiv_at, simpa using (C.comp z (B.comp z A)).has_strict_deriv_at end /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_deriv_at.real_of_complex (h : has_deriv_at e e' z) : has_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_fderiv_at, have B : has_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_fderiv_at.restrict_scalars ℝ, have C : has_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_fderiv_at, simpa using (C.comp z (B.comp z A)).has_deriv_at end theorem times_cont_diff_at.real_of_complex {n : with_top ℕ} (h : times_cont_diff_at ℂ n e z) : times_cont_diff_at ℝ n (λ x : ℝ, (e x).re) z := begin have A : times_cont_diff_at ℝ n (coe : ℝ → ℂ) z, from of_real_clm.times_cont_diff.times_cont_diff_at, have B : times_cont_diff_at ℝ n e z := h.restrict_scalars ℝ, have C : times_cont_diff_at ℝ n re (e z), from re_clm.times_cont_diff.times_cont_diff_at, exact C.comp z (B.comp z A) end theorem times_cont_diff.real_of_complex {n : with_top ℕ} (h : times_cont_diff ℂ n e) : times_cont_diff ℝ n (λ x : ℝ, (e x).re) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.real_of_complex variables {E : Type*} [normed_group E] [normed_space ℂ E] lemma has_strict_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_deriv_at f f' x) : has_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv' {f : ℂ → E} {s : set ℂ} {x : ℂ} {f' : E} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (re_clm.smul_right f' + I • im_clm.smul_right f') s x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_within_at.restrict_scalars ℝ lemma has_strict_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_deriv_at f f' x) : has_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv {f : ℂ → ℂ} {s : set ℂ} {f' x : ℂ} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (f' • (1 : ℂ →L[ℝ] ℂ)) s x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_within_at.restrict_scalars ℝ end real_deriv_of_complex section conformality /-! ### Conformality of real-differentiable complex maps -/ open complex continuous_linear_map open_locale complex_conjugate variables /-- A real differentiable function of the complex plane into some complex normed space `E` is conformal at a point `z` if it is holomorphic at that point with a nonvanishing differential. This is a version of the Cauchy-Riemann equations. -/ lemma differentiable_at.conformal_at {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space ℂ E] {z : ℂ} {f : ℂ → E} (hf' : fderiv ℝ f z ≠ 0) (h : differentiable_at ℂ f z) : conformal_at f z := begin rw conformal_at_iff_is_conformal_map_fderiv, rw (h.has_fderiv_at.restrict_scalars ℝ).fderiv at ⊢ hf', apply is_conformal_map_complex_linear, contrapose! hf' with w, simp [w] end /-- A complex function is conformal if and only if the function is holomorphic or antiholomorphic with a nonvanishing differential. -/ lemma conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj {f : ℂ → ℂ} {z : ℂ} : conformal_at f z ↔ (differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) ∧ fderiv ℝ f z ≠ 0 := begin rw conformal_at_iff_is_conformal_map_fderiv, rw is_conformal_map_iff_is_complex_or_conj_linear, apply and_congr_left, intros h, have h_diff := h.imp_symm fderiv_zero_of_not_differentiable_at, apply or_congr, { rw differentiable_at_iff_restrict_scalars ℝ h_diff }, rw ← conj_conj z at h_diff, rw differentiable_at_iff_restrict_scalars ℝ (h_diff.comp _ conj_cle.differentiable_at), refine exists_congr (λ g, rfl.congr _), have : fderiv ℝ conj (conj z) = _ := conj_cle.fderiv, simp [fderiv.comp _ h_diff conj_cle.differentiable_at, this, conj_conj], end end conformality
465ba6a36c94e23585030e64b228471cd35aa198
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/analytic/composition.lean
eeeea5db90346c5c4fb5f7f5daf6bda740107a76
[ "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
58,724
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, Johan Commelin -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions In this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ noncomputable theory variables {𝕜 : Type*} {E F G H : Type*} open filter list open_locale topological_space big_operators classical nnreal ennreal section topological variables [comm_ring 𝕜] [add_comm_group E] [add_comm_group F] [add_comm_group G] variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G] variables [topological_space E] [topological_space F] [topological_space G] /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series variables [topological_add_group E] [has_continuous_const_smul 𝕜 E] variables [topological_add_group F] [has_continuous_const_smul 𝕜 F] variables [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : p.apply_composition (composition.ones n) = λ v i, p 1 (λ _, v (fin.cast_le (composition.length_le _) i)) := begin funext v i, apply p.congr (composition.ones_blocks_fun _ _), intros j hjn hj1, obtain rfl : j = 0, { linarith }, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, composition.ones_embedding, fin.coe_mk], end lemma apply_composition_single (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) (v : fin n → E) : p.apply_composition (composition.single n hn) v = λ j, p n v := begin ext j, refine p.congr (by simp) (λ i hi1 hi2, _), dsimp, congr' 1, convert composition.single_embedding hn ⟨i, hi2⟩, cases j, have : j_val = 0 := le_bot_iff.1 (nat.lt_succ_iff.1 j_property), unfold_coes, congr; try { assumption <|> simp }, end @[simp] lemma remove_zero_apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : p.remove_zero.apply_composition c = p.apply_composition c := begin ext v i, simp [apply_composition, zero_lt_one.trans_le (c.one_le_blocks_fun i), remove_zero_of_pos], end /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact (c.embedding_comp_inv j).symm }, exact function.update_comp_eq_of_injective _ (c.embedding _).injective _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end @[simp] lemma comp_continuous_linear_map_apply_composition {n : ℕ} (p : formal_multilinear_series 𝕜 F G) (f : E →L[𝕜] F) (c : composition n) (v : fin n → E) : (p.comp_continuous_linear_map f).apply_composition c v = p.apply_composition c (f ∘ v) := by simp [apply_composition] end formal_multilinear_series namespace continuous_multilinear_map open formal_multilinear_series variables [topological_add_group E] [has_continuous_const_smul 𝕜 E] variables [topological_add_group F] [has_continuous_const_smul 𝕜 F] /-- Given a formal multilinear series `p`, a composition `c` of `n` and a continuous multilinear map `f` in `c.length` variables, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `f` to the resulting vector. It is called `f.comp_along_composition p c`. -/ def comp_along_composition {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, f (p.apply_composition c v), map_add' := λ v i x y, by simp only [apply_composition_update, continuous_multilinear_map.map_add], map_smul' := λ v i c x, by simp only [apply_composition_update, continuous_multilinear_map.map_smul], cont := f.cont.comp $ continuous_pi $ λ i, (coe_continuous _).comp $ continuous_pi $ λ j, continuous_apply _, } @[simp] lemma comp_along_composition_apply {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : (f.comp_along_composition p c) v = f (p.apply_composition c v) := rfl end continuous_multilinear_map namespace formal_multilinear_series variables [topological_add_group E] [has_continuous_const_smul 𝕜 E] variables [topological_add_group F] [has_continuous_const_smul 𝕜 F] variables [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q c.length).comp_along_composition p c @[simp] lemma comp_along_composition_apply {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : (q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} qₖ (p_{i_1} (...), ..., p_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots. In general, the composition `q ∘ p` only makes sense when the constant coefficient of `p` vanishes. We give a general formula but which ignores the value of `p 0` instead. -/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, ∑ c : composition n, q.comp_along_composition p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : (q.comp p) 0 v = q 0 v' := begin let c : composition 0 := composition.ones 0, dsimp [formal_multilinear_series.comp], have : {c} = (finset.univ : finset (composition 0)), { apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] }, rw [← this, finset.sum_singleton, comp_along_composition_apply], symmetry, congr' end @[simp] lemma comp_coeff_zero' (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : (q.comp p) 0 v = q 0 (λ i, 0) := q.comp_coeff_zero p v _ /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : (q.comp p) 0 = q 0 := by { ext v, exact q.comp_coeff_zero p _ _ } /-- The first coefficient of a composition of formal multilinear series is the composition of the first coefficients seen as continuous linear maps. -/ lemma comp_coeff_one (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 1 → E) : (q.comp p) 1 v = q 1 (λ i, p 1 v) := begin have : {composition.ones 1} = (finset.univ : finset (composition 1)) := finset.eq_univ_of_card _ (by simp [composition_card]), simp only [formal_multilinear_series.comp, comp_along_composition_apply, ← this, finset.sum_singleton], refine q.congr (by simp) (λ i hi1 hi2, _), simp only [apply_composition_ones], exact p.congr rfl (λ j hj1 hj2, by congr) end /-- Only `0`-th coefficient of `q.comp p` depends on `q 0`. -/ lemma remove_zero_comp_of_pos (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (hn : 0 < n) : q.remove_zero.comp p n = q.comp p n := begin ext v, simp only [formal_multilinear_series.comp, comp_along_composition, continuous_multilinear_map.comp_along_composition_apply, continuous_multilinear_map.sum_apply], apply finset.sum_congr rfl (λ c hc, _), rw remove_zero_of_pos _ (c.length_pos_of_pos hn) end @[simp] lemma comp_remove_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : q.comp p.remove_zero = q.comp p := by { ext n, simp [formal_multilinear_series.comp] } end formal_multilinear_series end topological variables [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] [normed_add_comm_group G] [normed_space 𝕜 G] [normed_add_comm_group H] [normed_space 𝕜 H] namespace formal_multilinear_series /-- The norm of `f.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `f` and `p`. -/ lemma comp_along_composition_bound {n : ℕ} (p : formal_multilinear_series 𝕜 E F) (c : composition n) (f : continuous_multilinear_map 𝕜 (λ (i : fin c.length), F) G) (v : fin n → E) : ‖f.comp_along_composition p c v‖ ≤ ‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) * (∏ i : fin n, ‖v i‖) := calc ‖f.comp_along_composition p c v‖ = ‖f (p.apply_composition c v)‖ : rfl ... ≤ ‖f‖ * ∏ i, ‖p.apply_composition c v i‖ : continuous_multilinear_map.le_op_norm _ _ ... ≤ ‖f‖ * ∏ i, ‖p (c.blocks_fun i)‖ * ∏ j : fin (c.blocks_fun i), ‖(v ∘ (c.embedding i)) j‖ : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) * ∏ i (j : fin (c.blocks_fun i)), ‖(v ∘ (c.embedding i)) j‖ : by rw [finset.prod_mul_distrib, mul_assoc] ... = ‖f‖ * (∏ i, ‖p (c.blocks_fun i)‖) * (∏ i : fin n, ‖v i‖) : by { rw [← c.blocks_fin_equiv.prod_comp, ← finset.univ_sigma_univ, finset.prod_sigma], congr } /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ‖q.comp_along_composition p c‖ ≤ ‖q c.length‖ * ∏ i, ‖p (c.blocks_fun i)‖ := continuous_multilinear_map.op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) (comp_along_composition_bound _ _ _) lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ‖q.comp_along_composition p c‖₊ ≤ ‖q c.length‖₊ * ∏ i, ‖p (c.blocks_fun i)‖₊ := by { rw ← nnreal.coe_le_coe, push_cast, exact q.comp_along_composition_norm p c } /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ section variables (𝕜 E) /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id : formal_multilinear_series 𝕜 E E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E) | _ := 0 /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) : (id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ := begin subst n, apply id_apply_one end /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 := by { cases n, { refl }, cases n, { contradiction }, refl } end @[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p := begin ext1 n, dsimp [formal_multilinear_series.comp], rw finset.sum_eq_single (composition.ones n), show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n, { ext v, rw comp_along_composition_apply, apply p.congr (composition.ones_length n), intros, rw apply_composition_ones, refine congr_arg v _, rw [fin.ext_iff, fin.coe_cast_le, fin.coe_mk, fin.coe_mk], }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0, { assume b _ hb, obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k := composition.ne_ones_iff.1 hb, obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k := nth_le_of_mem hk, let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩, have A : 1 < b.blocks_fun j := by convert lt_k, ext v, rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply], apply continuous_multilinear_map.map_coord_zero _ j, dsimp [apply_composition], rw id_apply_ne_one _ _ (ne_of_gt A), refl }, { simp } end @[simp] theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p := begin ext1 n, by_cases hn : n = 0, { rw [hn, h], ext v, rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one], refl }, { dsimp [formal_multilinear_series.comp], have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn, rw finset.sum_eq_single (composition.single n n_pos), show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n, { ext v, rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)], dsimp [apply_composition], refine p.congr rfl (λ i him hin, congr_arg v $ _), ext, simp }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0, { assume b _ hb, have A : b.length ≠ 1, by simpa [composition.eq_single_iff_length] using hb, ext v, rw [comp_along_composition_apply, id_apply_ne_one _ _ A], refl }, { simp } } end /-! ### Summability properties of the composition of formal power series-/ section /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ r > (0 : ℝ≥0), summable (λ i : Σ n, composition n, ‖q.comp_along_composition p i.2‖₊ * r ^ i.1) := begin /- This follows from the fact that the growth rate of `‖qₙ‖` and `‖pₙ‖` is at most geometric, giving a geometric bound on each `‖q.comp_along_composition p op‖`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hq) with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 (lt_min ennreal.zero_lt_one hp) with ⟨rp, rp_pos, hrp⟩, simp only [lt_min_iff, ennreal.coe_lt_one_iff, ennreal.coe_pos] at hrp hrq rp_pos rq_pos, obtain ⟨Cq, hCq0, hCq⟩ : ∃ Cq > 0, ∀ n, ‖q n‖₊ * rq^n ≤ Cq := q.nnnorm_mul_pow_le_of_lt_radius hrq.2, obtain ⟨Cp, hCp1, hCp⟩ : ∃ Cp ≥ 1, ∀ n, ‖p n‖₊ * rp^n ≤ Cp, { rcases p.nnnorm_mul_pow_le_of_lt_radius hrp.2 with ⟨Cp, -, hCp⟩, exact ⟨max Cp 1, le_max_right _ _, λ n, (hCp n).trans (le_max_left _ _)⟩ }, let r0 : ℝ≥0 := (4 * Cp)⁻¹, have r0_pos : 0 < r0 := nnreal.inv_pos.2 (mul_pos zero_lt_four (zero_lt_one.trans_le hCp1)), set r : ℝ≥0 := rp * rq * r0, have r_pos : 0 < r := mul_pos (mul_pos rp_pos rq_pos) r0_pos, have I : ∀ (i : Σ (n : ℕ), composition n), ‖q.comp_along_composition p i.2‖₊ * r ^ i.1 ≤ Cq / 4 ^ i.1, { rintros ⟨n, c⟩, have A, calc ‖q c.length‖₊ * rq ^ n ≤ ‖q c.length‖₊* rq ^ c.length : mul_le_mul' le_rfl (pow_le_pow_of_le_one rq.2 hrq.1.le c.length_le) ... ≤ Cq : hCq _, have B, calc ((∏ i, ‖p (c.blocks_fun i)‖₊) * rp ^ n) = ∏ i, ‖p (c.blocks_fun i)‖₊ * rp ^ c.blocks_fun i : by simp only [finset.prod_mul_distrib, finset.prod_pow_eq_pow_sum, c.sum_blocks_fun] ... ≤ ∏ i : fin c.length, Cp : finset.prod_le_prod' (λ i _, hCp _) ... = Cp ^ c.length : by simp ... ≤ Cp ^ n : pow_le_pow hCp1 c.length_le, calc ‖q.comp_along_composition p c‖₊ * r ^ n ≤ (‖q c.length‖₊ * ∏ i, ‖p (c.blocks_fun i)‖₊) * r ^ n : mul_le_mul' (q.comp_along_composition_nnnorm p c) le_rfl ... = (‖q c.length‖₊ * rq ^ n) * ((∏ i, ‖p (c.blocks_fun i)‖₊) * rp ^ n) * r0 ^ n : by { simp only [r, mul_pow], ring } ... ≤ Cq * Cp ^ n * r0 ^ n : mul_le_mul' (mul_le_mul' A B) le_rfl ... = Cq / 4 ^ n : begin simp only [r0], field_simp [mul_pow, (zero_lt_one.trans_le hCp1).ne'], ring end }, refine ⟨r, r_pos, nnreal.summable_of_le I _⟩, simp_rw div_eq_mul_inv, refine summable.mul_left _ _, have : ∀ n : ℕ, has_sum (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹) (2 ^ (n - 1) / 4 ^ n), { intro n, convert has_sum_fintype (λ c : composition n, (4 ^ n : ℝ≥0)⁻¹), simp [finset.card_univ, composition_card, div_eq_mul_inv] }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, (nnreal.summable_nat_add_iff 1).1 _⟩, convert (nnreal.summable_geometric (nnreal.div_lt_one_of_lt one_lt_two)).mul_left (1 / 4), ext1 n, rw [(this _).tsum_eq, add_tsub_cancel_right], field_simp [← mul_assoc, pow_succ', mul_pow, show (4 : ℝ≥0) = 2 * 2, from (two_mul 2).symm, mul_right_comm] end end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : ℝ≥0) (hr : summable (λ i : (Σ n, composition n), ‖q.comp_along_composition p i.2‖₊ * r ^ i.1)) : (r : ℝ≥0∞) ≤ (q.comp p).radius := begin refine le_radius_of_bound_nnreal _ (∑' i : (Σ n, composition n), ‖comp_along_composition q p i.snd‖₊ * r ^ i.fst) (λ n, _), calc ‖formal_multilinear_series.comp q p n‖₊ * r ^ n ≤ ∑' (c : composition n), ‖comp_along_composition q p c‖₊ * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul' (nnnorm_sum_le _ _) le_rfl end ... ≤ ∑' (i : Σ (n : ℕ), composition n), ‖comp_along_composition q p i.snd‖₊ * r ^ i.fst : nnreal.tsum_comp_le_tsum_of_inj hr sigma_mk_injective end /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (m M N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.Ico m M) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (m M N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source m M N ↔ (m ≤ i.1 ∧ i.1 < M) ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp only [comp_partial_sum_source, finset.mem_Ico, fintype.mem_pi_finset, finset.mem_sigma, iff_self] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (m M N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source m M N) : (Σ n, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩, obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi', exact (hi.2 j).1 end @[simp] lemma comp_change_of_variables_length (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) : composition.length (comp_change_of_variables m M N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, map_of_fn, length_of_fn] end lemma comp_change_of_variables_blocks_fun (m M N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source m M N) (j : fin i.1) : (comp_change_of_variables m M N i hi).2.blocks_fun ⟨j, (comp_change_of_variables_length m M N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [map_of_fn, nth_le_of_fn', function.comp_app], apply congr_arg, exact fin.eta _ _ end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (m M N : ℕ) : set (Σ n, composition n) := {i | (m ≤ i.2.length) ∧ (i.2.length < M) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (m M N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set m M N) : ∃ j (hj : j ∈ comp_partial_sum_source m M N), i = comp_change_of_variables m M N j hj := begin rcases i with ⟨n, c⟩, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi, simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'], conv_lhs { rw ← of_fn_nth_le c.blocks } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (m M N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ ((finset.finite_to_set _).dependent_image _).subset $ comp_partial_sum_target_subset_image_comp_partial_sum_source m M N @[simp] lemma mem_comp_partial_sum_target_iff {m M N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target m M N ↔ m ≤ a.2.length ∧ a.2.length < M ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- `comp_change_of_variables m M N` is a bijection between `comp_partial_sum_source m M N` and `comp_partial_sum_target m M N`, yielding equal sums for functions that correspond to each other under the bijection. As `comp_change_of_variables m M N` is a dependent function, stating that it is a bijection is not directly possible, but the consequence on sums can be stated more easily. -/ lemma comp_change_of_variables_sum {α : Type*} [add_comm_monoid α] (m M N : ℕ) (f : (Σ (n : ℕ), fin n → ℕ) → α) (g : (Σ n, composition n) → α) (h : ∀ e (he : e ∈ comp_partial_sum_source m M N), f e = g (comp_change_of_variables m M N e he)) : ∑ e in comp_partial_sum_source m M N, f e = ∑ e in comp_partial_sum_target m M N, g e := begin apply finset.sum_bij (comp_change_of_variables m M N), -- We should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target m N N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, map_of_fn, length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, rw h }, -- 3 - show that the map is injective { rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq, obtain rfl : k = k', { have := (comp_change_of_variables_length m M N H).symm, rwa [heq, comp_change_of_variables_length] at this, }, congr, funext i, calc blocks_fun i = (comp_change_of_variables m M N _ H).2.blocks_fun _ : (comp_change_of_variables_blocks_fun m M N H i).symm ... = (comp_change_of_variables m M N _ H').2.blocks_fun _ : begin apply composition.blocks_fun_congr; try { rw heq }, refl end ... = blocks_fun' i : comp_change_of_variables_blocks_fun m M N H' i }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source m M N i, simpa [comp_partial_sum_target] using hi } end /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto (λ N, comp_partial_sum_target 0 N N) at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, refine ⟨max n c.length + 1, bot_le, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target 0 N N`. This is precisely the motivation for the definition of `comp_partial_sum_target`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N), q n (λ (i : fin n), p (r i) (λ j, z)) = ∑ i in comp_partial_sum_target 0 N N, q.comp_along_composition p i.2 (λ j, z), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type, in the finset -- `comp_partial_sum_target 0 N N` rw [finset.range_eq_Ico, finset.sum_sigma'], -- use `comp_change_of_variables_sum`, saying that this change of variables respects sums apply comp_change_of_variables_sum 0 N N, rintros ⟨k, blocks_fun⟩ H, apply congr _ (comp_change_of_variables_length 0 N N H).symm, intros, rw ← comp_change_of_variables_blocks_fun 0 N N H, refl end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos : 0 < r, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ≥0∞) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have min_pos : 0 < min rf' r, by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `‖y‖ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target 0 n n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x = ∑ a in finset.Ico 1 n, p a (λ b, y), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (is_open.mem_nhds (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← emetric.is_open_ball.nhds_within_eq B₂] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target 0 n n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, ∑ i in comp_partial_sum_target 0 n n, q.comp_along_composition p i.2 (λ j, y)) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), ∑ i in s, q.comp_along_composition p i.2 (λ j, y)), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ‖(comp_along_composition q p c) (λ (j : fin n), y)‖ ≤ ‖comp_along_composition q p c‖ * ∏ j : fin n, ‖y‖ : by apply continuous_multilinear_map.le_op_norm ... ≤ ‖comp_along_composition q p c‖ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [finset.prod_const, finset.card_fin], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at /-! ### Associativity of the composition of formal multilinear series In this paragraph, we prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition variable {n : ℕ} /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) : i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks := begin refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩, rcases i with ⟨a, b⟩, rcases j with ⟨a', b'⟩, rintros ⟨h, h'⟩, have H : a = a', by { ext1, exact h }, induction H, congr, ext1, exact h' end /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ lemma sigma_pi_composition_eq_iff (u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) : u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases u with ⟨a, b⟩, rcases v with ⟨a', b'⟩, dsimp at H, have h : a = a', { ext1, have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) = map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H, simp only [map_of_fn] at this, change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) = of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this, simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this }, induction h, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i : 2, have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i (by simp [i.is_lt]) = nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i (by simp [i.is_lt]) := nth_le_of_eq H _, rwa [nth_le_of_fn, nth_le_of_fn] at this end /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather (a : composition n) (b : composition a.length) : composition n := { blocks := (a.blocks.split_wrt_composition b).map sum, blocks_pos := begin rw forall_mem_map_iff, intros j hj, suffices H : ∀ i ∈ j, 1 ≤ i, from calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj ... ≤ j.sum : length_le_sum_of_one_le _ H, intros i hi, apply a.one_le_blocks, rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem hj hi, end, blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } } lemma length_gather (a : composition n) (b : composition a.length) : length (a.gather b) = b.length := show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length, by rw [length_map, length_split_wrt_composition] /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin (a.gather b).length) : composition ((a.gather b).blocks_fun i) := { blocks := nth_le (a.blocks.split_wrt_composition b) i (by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }), blocks_pos := assume i hi, a.blocks_pos (by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }), blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] } lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) : composition.length (composition.sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) = composition.blocks_fun b i := show list.length (nth_le (split_wrt_composition a.blocks b) i _) = blocks_fun b i, by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) ⟨j, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) := show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _, by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl } /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length) {i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) : size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i + (size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) := begin induction j with j IHj, { show sum (take ((b.blocks.take i).sum) a.blocks) = sum (take i (map sum (split_wrt_composition a.blocks b))), induction i with i IH, { refl }, { have A : i < b.length := nat.lt_of_succ_lt hi, have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A], have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _, rw [sum_take_succ _ _ B, ← IH A C], have : take (sum (take i b.blocks)) a.blocks = take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks), { rw [take_take, min_eq_left], apply monotone_sum_take _ (nat.le_succ _) }, rw [this, nth_le_map', nth_le_split_wrt_composition, ← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append], congr, rw [take_append_drop] } }, { have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj, have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩), by { convert A, rw [← length_sigma_composition_aux], refl }, have C : size_up_to b i + j < size_up_to b (i + 1), { simp only [size_up_to_succ b hi, add_lt_add_iff_left], exact A }, have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _), have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl, rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B], simp only [sigma_composition_aux, add_assoc, add_left_inj, fin.coe_mk], rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] } end /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (Σ (a : composition n), composition a.length) ≃ (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) := { to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩, inv_fun := λ i, ⟨ { blocks := (of_fn (λ j, (i.2 j).blocks)).join, blocks_pos := begin simp only [and_imp, list.mem_join, exists_imp_distrib, forall_mem_of_fn_iff], exact λ i j hj, composition.blocks_pos _ hj end, blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] }, { blocks := of_fn (λ j, (i.2 j).length), blocks_pos := forall_mem_of_fn_iff.2 (λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)), blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩, left_inv := begin -- the fact that we have a left inverse is essentially `join_split_wrt_composition`, -- but we need to massage it to take care of the dependent setting. rintros ⟨a, b⟩, rw sigma_composition_eq_iff, dsimp, split, { have A := length_map list.sum (split_wrt_composition a.blocks b), conv_rhs { rw [← join_split_wrt_composition a.blocks b, ← of_fn_nth_le (split_wrt_composition a.blocks b)] }, congr, { exact A }, { exact (fin.heq_fun_iff A).2 (λ i, rfl) } }, { have B : composition.length (composition.gather a b) = list.length b.blocks := composition.length_gather _ _, conv_rhs { rw [← of_fn_nth_le b.blocks] }, congr' 1, apply (fin.heq_fun_iff B).2 (λ i, _), rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } end, right_inv := begin -- the fact that we have a right inverse is essentially `split_wrt_composition_join`, -- but we need to massage it to take care of the dependent setting. rintros ⟨c, d⟩, have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks, by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun], rw sigma_pi_composition_eq_iff, dsimp, congr, { ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] }, { rw fin.heq_fun_iff, { assume i, dsimp [composition.sigma_composition_aux], rw [nth_le_of_eq (split_wrt_composition_join _ _ _)], { simp only [nth_le_of_fn'] }, { simp only [map_of_fn] } }, { congr, ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] } } end } end composition namespace formal_multilinear_series open composition theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : (r.comp q).comp p = r.comp (q.comp p) := begin ext n v, /- First, rewrite the two compositions appearing in the theorem as two sums over complicated sigma types, as in the description of the proof above. -/ let f : (Σ (a : composition n), composition a.length) → H := λ c, r c.2.length (apply_composition q c.2 (apply_composition p c.1 v)), let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H := λ c, r c.1.length (λ (i : fin c.1.length), q (c.2 i).length (apply_composition p (c.2 i) (v ∘ c.1.embedding i))), suffices : ∑ c, f c = ∑ c, g c, by simpa only [formal_multilinear_series.comp, continuous_multilinear_map.sum_apply, comp_along_composition_apply, continuous_multilinear_map.map_sum, finset.sum_sigma', apply_composition], /- Now, we use `composition.sigma_equiv_sigma_pi n` to change variables in the second sum, and check that we get exactly the same sums. -/ rw ← (sigma_equiv_sigma_pi n).sum_comp, /- To check that we have the same terms, we should check that we apply the same component of `r`, and the same component of `q`, and the same component of `p`, to the same coordinate of `v`. This is true by definition, but at each step one needs to convince Lean that the types one considers are the same, using a suitable congruence lemma to avoid dependent type issues. This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/ apply finset.sum_congr rfl, rintros ⟨a, b⟩ _, dsimp [f, g, sigma_equiv_sigma_pi], -- check that the `r` components are the same. Based on `composition.length_gather` apply r.congr (composition.length_gather a b).symm, intros i hi1 hi2, -- check that the `q` components are the same. Based on `length_sigma_composition_aux` apply q.congr (length_sigma_composition_aux a b _).symm, intros j hj1 hj2, -- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux` apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm, intros k hk1 hk2, -- finally, check that the coordinates of `v` one is using are the same. Based on -- `size_up_to_size_up_to_add`. refine congr_arg v (fin.eq_of_veq _), dsimp [composition.embedding], rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc], end end formal_multilinear_series
89e1282e24f52add45eaf9e52126fa60b96bb1fe
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/category/Group/Z_Module_equivalence.lean
57669afe8ed51db8d0b454c0661f98637fe2abeb
[ "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
1,329
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.basic /-! The forgetful functor from ℤ-modules to additive commutative groups is an equivalence of categories. TODO: either use this equivalence to transport the monoidal structure from `Module ℤ` to `Ab`, or, having constructed that monoidal structure directly, show this functor is monoidal. -/ open category_theory open category_theory.equivalence universes u /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is full. -/ instance : full (forget₂ (Module ℤ) AddCommGroup.{u}) := { preimage := λ A B f, -- TODO: why `add_monoid_hom.to_int_linear_map` doesn't work here? { to_fun := f, map_add' := add_monoid_hom.map_add f, map_smul' := λ n x, by convert add_monoid_hom.map_int_module_smul f n x } } /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is essentially surjective. -/ instance : ess_surj (forget₂ (Module ℤ) AddCommGroup.{u}) := { obj_preimage := λ A, Module.of ℤ A, iso' := λ A, { hom := 𝟙 A, inv := 𝟙 A, } } instance : is_equivalence (forget₂ (Module ℤ) AddCommGroup.{u}) := equivalence_of_fully_faithfully_ess_surj (forget₂ (Module ℤ) AddCommGroup)
2778a6a0fa15bdf33009d137854eecc1a345a2e9
1446f520c1db37e157b631385707cc28a17a595e
/tests/bench/rbmap_checkpoint.lean
f505c9eede9673f1f1706194472a5078a976f463
[ "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
3,391
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Option.Basic import Init.Data.List.BasicAux import Init.System.IO universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree instance : Inhabited Tree := ⟨Tree.Leaf⟩ variables {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _, _, _ => Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _, _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux (freq : Nat) : Nat → Tree → List Tree → List Tree | 0, m, r => m::r | n+1, m, r => let m := insert m n (n % 10 = 0); let r := if n % freq == 0 then m::r else r; mkMapAux n m r def mkMap (n : Nat) (freq : Nat) : List Tree := mkMapAux freq n Leaf [] def myLen : List Tree → Nat → Nat | Node _ _ _ _ _ :: xs, r => myLen xs (r + 1) | _ :: xs, r => myLen xs r | [], r => r def main (xs : List String) : IO UInt32 := do [n, freq] ← pure xs | throw $ IO.userError "invalid input"; let n := n.toNat; let freq := freq.toNat; let freq := if freq == 0 then 1 else freq; let mList := mkMap n freq; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) mList.head! 0; IO.println (toString (myLen mList 0) ++ " " ++ toString v) *> pure 0
f18a2a62c8d5e310d66e44bb8df9b45df29c9880
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/higherOrderFunctions/box_map.lean
58d4146d45c6ed1608b884b703526357c2e36abf
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
205
lean
universes u₁ u₂ structure box (α : Type u₁) : Type u₁ := mk :: (val : α) def map_box {α : Type u₁} {β : Type u₂} (f : α → β) (b : box α) : box β := box.mk (f b.val)
beb313e683a64c3f94cde5834f832e8e27099b34
626e312b5c1cb2d88fca108f5933076012633192
/src/data/part.lean
b33a99263f27f7a10d0dc0de1a603300e5851efb
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,217
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import data.equiv.basic /-! # Partial values of a type -/ /-- `part α` is the type of "partial values" of type `α`. It is similar to `option α` except the domain condition can be an arbitrary proposition, not necessarily decidable. -/ structure {u} part (α : Type u) : Type u := (dom : Prop) (get : dom → α) namespace part variables {α : Type*} {β : Type*} {γ : Type*} /-- Convert a `part α` with a decidable domain to an option -/ def to_option (o : part α) [decidable o.dom] : option α := if h : dom o then some (o.get h) else none /-- `part` extensionality -/ theorem ext' : ∀ {o p : part α} (H1 : o.dom ↔ p.dom) (H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p | ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1, by cases t; rw [show o = p, from funext $ λp, H2 p p] /-- `part` eta expansion -/ @[simp] theorem eta : Π (o : part α), (⟨o.dom, λ h, o.get h⟩ : part α) = o | ⟨h, f⟩ := rfl /-- `a ∈ o` means that `o` is defined and equal to `a` -/ protected def mem (a : α) (o : part α) : Prop := ∃ h, o.get h = a instance : has_mem α (part α) := ⟨part.mem⟩ theorem mem_eq (a : α) (o : part α) : (a ∈ o) = (∃ h, o.get h = a) := rfl theorem dom_iff_mem : ∀ {o : part α}, o.dom ↔ ∃y, y ∈ o | ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩ theorem get_mem {o : part α} (h) : get o h ∈ o := ⟨_, rfl⟩ /-- `part` extensionality -/ @[ext] theorem ext {o p : part α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p := ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst, λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $ λ a b, ((H _).2 ⟨_, rfl⟩).snd /-- The `none` value in `part` has a `false` domain and an empty function. -/ def none : part α := ⟨false, false.rec _⟩ instance : inhabited (part α) := ⟨none⟩ @[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst /-- The `some a` value in `part` has a `true` domain and the function returns `a`. -/ def some (a : α) : part α := ⟨true, λ_, a⟩ theorem mem_unique : ∀ {a b : α} {o : part α}, a ∈ o → b ∈ o → a = b | _ _ ⟨p, f⟩ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl theorem mem.left_unique : relator.left_unique ((∈) : α → part α → Prop) := ⟨λ a o b, mem_unique⟩ theorem get_eq_of_mem {o : part α} {a} (h : a ∈ o) (h') : get o h' = a := mem_unique ⟨_, rfl⟩ h protected theorem subsingleton (o : part α) : set.subsingleton {a | a ∈ o} := λ a ha b hb, mem_unique ha hb @[simp] theorem get_some {a : α} (ha : (some a).dom) : get (some a) ha = a := rfl theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩ @[simp] theorem mem_some_iff {a b} : b ∈ (some a : part α) ↔ b = a := ⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩ theorem eq_some_iff {a : α} {o : part α} : o = some a ↔ a ∈ o := ⟨λ e, e.symm ▸ mem_some _, λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩ theorem eq_none_iff {o : part α} : o = none ↔ ∀ a, a ∉ o := ⟨λ e, e.symm ▸ not_mem_none, λ h, ext (by simpa [not_mem_none])⟩ theorem eq_none_iff' {o : part α} : o = none ↔ ¬ o.dom := ⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩ lemma some_ne_none (x : α) : some x ≠ none := by { intro h, change none.dom, rw [← h], trivial } lemma ne_none_iff {o : part α} : o ≠ none ↔ ∃x, o = some x := begin split, { rw [ne, eq_none_iff], intro h, push_neg at h, cases h with x hx, use x, rwa [eq_some_iff] }, { rintro ⟨x, rfl⟩, apply some_ne_none } end lemma eq_none_or_eq_some (o : part α) : o = none ∨ ∃ x, o = some x := begin classical, by_cases h : o.dom, { rw dom_iff_mem at h, right, apply exists_imp_exists _ h, simp [eq_some_iff] }, { rw eq_none_iff', exact or.inl h }, end @[simp] lemma some_inj {a b : α} : part.some a = some b ↔ a = b := function.injective.eq_iff (λ a b h, congr_fun (eq_of_heq (part.mk.inj h).2) trivial) @[simp] lemma some_get {a : part α} (ha : a.dom) : part.some (part.get a ha) = a := eq.symm (eq_some_iff.2 ⟨ha, rfl⟩) lemma get_eq_iff_eq_some {a : part α} {ha : a.dom} {b : α} : a.get ha = b ↔ a = some b := ⟨λ h, by simp [h.symm], λ h, by simp [h]⟩ lemma get_eq_get_of_eq (a : part α) (ha : a.dom) {b : part α} (h : a = b) : a.get ha = b.get (h ▸ ha) := by { congr, exact h } instance none_decidable : decidable (@none α).dom := decidable.false instance some_decidable (a : α) : decidable (some a).dom := decidable.true /-- Retrieves the value of `a : part α` if it exists, and return the provided default value otherwise. -/ def get_or_else (a : part α) [decidable a.dom] (d : α) := if ha : a.dom then a.get ha else d @[simp] lemma get_or_else_none (d : α) : get_or_else none d = d := dif_neg id @[simp] lemma get_or_else_some (a : α) (d : α) : get_or_else (some a) d = a := dif_pos trivial @[simp] theorem mem_to_option {o : part α} [decidable o.dom] {a : α} : a ∈ to_option o ↔ a ∈ o := begin unfold to_option, by_cases h : o.dom; simp [h], { exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ }, { exact mt Exists.fst h } end /-- Converts an `option α` into a `part α`. -/ def of_option : option α → part α | option.none := none | (option.some a) := some a @[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o | option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩ | (option.some b) := ⟨λ h, congr_arg option.some h.snd, λ h, ⟨trivial, option.some.inj h⟩⟩ @[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some | option.none := by simp [of_option, none] | (option.some a) := by simp [of_option] theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ := part.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl] instance : has_coe (option α) (part α) := ⟨of_option⟩ @[simp] theorem mem_coe {a : α} {o : option α} : a ∈ (o : part α) ↔ a ∈ o := mem_of_option @[simp] theorem coe_none : (@option.none α : part α) = none := rfl @[simp] theorem coe_some (a : α) : (option.some a : part α) = some a := rfl @[elab_as_eliminator] protected lemma induction_on {P : part α → Prop} (a : part α) (hnone : P none) (hsome : ∀ a : α, P (some a)) : P a := (classical.em a.dom).elim (λ h, part.some_get h ▸ hsome _) (λ h, (eq_none_iff'.2 h).symm ▸ hnone) instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom | option.none := part.none_decidable | (option.some a) := part.some_decidable a @[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o := by cases o; refl @[simp] theorem of_to_option (o : part α) [decidable o.dom] : of_option (to_option o) = o := ext $ λ a, mem_of_option.trans mem_to_option /-- `part α` is (classically) equivalent to `option α`. -/ noncomputable def equiv_option : part α ≃ option α := by haveI := classical.dec; exact ⟨λ o, to_option o, of_option, λ o, of_to_option o, λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩ /-- We give `part α` the order where everything is greater than `none`. -/ instance : order_bot (part α) := { le := λ x y, ∀ i, i ∈ x → i ∈ y, le_refl := λ x y, id, le_trans := λ x y z f g i, g _ ∘ f _, le_antisymm := λ x y f g, part.ext $ λ z, ⟨f _, g _⟩, bot := none, bot_le := by { introv x, rintro ⟨⟨_⟩,_⟩, } } instance : preorder (part α) := by apply_instance lemma le_total_of_le_of_le {x y : part α} (z : part α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := begin rcases part.eq_none_or_eq_some x with h | ⟨b, h₀⟩, { rw h, left, apply order_bot.bot_le _ }, right, intros b' h₁, rw part.eq_some_iff at h₀, replace hx := hx _ h₀, replace hy := hy _ h₁, replace hx := part.mem_unique hx hy, subst hx, exact h₀ end /-- `assert p f` is a bind-like operation which appends an additional condition `p` to the domain and uses `f` to produce the value. -/ def assert (p : Prop) (f : p → part α) : part α := ⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩ /-- The bind operation has value `g (f.get)`, and is defined when all the parts are defined. -/ protected def bind (f : part α) (g : α → part β) : part β := assert (dom f) (λb, g (f.get b)) /-- The map operation for `part` just maps the value and maintains the same domain. -/ def map (f : α → β) (o : part α) : part β := ⟨o.dom, f ∘ o.get⟩ theorem mem_map (f : α → β) {o : part α} : ∀ {a}, a ∈ o → f a ∈ map f o | _ ⟨h, rfl⟩ := ⟨_, rfl⟩ @[simp] theorem mem_map_iff (f : α → β) {o : part α} {b} : b ∈ map f o ↔ ∃ a ∈ o, f a = b := ⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end, λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩ @[simp] theorem map_none (f : α → β) : map f none = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) := eq_some_iff.2 $ mem_map f $ mem_some _ theorem mem_assert {p : Prop} {f : p → part α} : ∀ {a} (h : p), a ∈ f h → a ∈ assert p f | _ x ⟨h, rfl⟩ := ⟨⟨x, h⟩, rfl⟩ @[simp] theorem mem_assert_iff {p : Prop} {f : p → part α} {a} : a ∈ assert p f ↔ ∃ h : p, a ∈ f h := ⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end, λ ⟨a, h⟩, mem_assert _ h⟩ lemma assert_pos {p : Prop} {f : p → part α} (h : p) : assert p f = f h := begin dsimp [assert], cases h' : f h, simp only [h', h, true_and, iff_self, exists_prop_of_true, eq_iff_iff], apply function.hfunext, { simp only [h,h',exists_prop_of_true] }, { cc } end lemma assert_neg {p : Prop} {f : p → part α} (h : ¬ p) : assert p f = none := begin dsimp [assert,none], congr, { simp only [h, not_false_iff, exists_prop_of_false] }, { apply function.hfunext, { simp only [h, not_false_iff, exists_prop_of_false] }, cc }, end theorem mem_bind {f : part α} {g : α → part β} : ∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g | _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨h, h₂⟩, rfl⟩ @[simp] theorem mem_bind_iff {f : part α} {g : α → part β} {b} : b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a := ⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end, λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩ @[simp] theorem bind_none (f : α → part β) : none.bind f = none := eq_none_iff.2 $ λ a, by simp @[simp] theorem bind_some (a : α) (f : α → part β) : (some a).bind f = f a := ext $ by simp theorem bind_some_eq_map (f : α → β) (x : part α) : x.bind (some ∘ f) = map f x := ext $ by simp [eq_comm] theorem bind_assoc {γ} (f : part α) (g : α → part β) (k : β → part γ) : (f.bind g).bind k = f.bind (λ x, (g x).bind k) := ext $ λ a, by simp; exact ⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩, λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩ @[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → part γ) : (map f x).bind g = x.bind (λ y, g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp @[simp] theorem map_bind {γ} (f : α → part β) (x : part α) (g : β → γ) : map g (x.bind f) = x.bind (λ y, map g (f y)) := by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map] theorem map_map (g : β → γ) (f : α → β) (o : part α) : map g (map f o) = map (g ∘ f) o := by rw [← bind_some_eq_map, bind_map, bind_some_eq_map] instance : monad part := { pure := @some, map := @map, bind := @part.bind } instance : is_lawful_monad part := { bind_pure_comp_eq_map := @bind_some_eq_map, id_map := λ β f, by cases f; refl, pure_bind := @bind_some, bind_assoc := @bind_assoc } theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o := by rw [show f = id, from funext H]; exact id_map o @[simp] theorem bind_some_right (x : part α) : x.bind some = x := by rw [bind_some_eq_map]; simp [map_id'] @[simp] theorem pure_eq_some (a : α) : pure a = some a := rfl @[simp] theorem ret_eq_some (a : α) : return a = some a := rfl @[simp] theorem map_eq_map {α β} (f : α → β) (o : part α) : f <$> o = map f o := rfl @[simp] theorem bind_eq_bind {α β} (f : part α) (g : α → part β) : f >>= g = f.bind g := rfl lemma bind_le {α} (x : part α) (f : α → part β) (y : part β) : x >>= f ≤ y ↔ (∀ a, a ∈ x → f a ≤ y) := begin split; intro h, { intros a h' b, replace h := h b, simp only [and_imp, exists_prop, bind_eq_bind, mem_bind_iff, exists_imp_distrib] at h, apply h _ h' }, { intros b h', simp only [exists_prop, bind_eq_bind, mem_bind_iff] at h', rcases h' with ⟨a,h₀,h₁⟩, apply h _ h₀ _ h₁ }, end instance : monad_fail part := { fail := λ_ _, none, ..part.monad } /-- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when `p` implies `o` is defined. -/ def restrict (p : Prop) : ∀ (o : part α), (p → o.dom) → part α | ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩ @[simp] theorem mem_restrict (p : Prop) (o : part α) (h : p → o.dom) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := begin cases o, dsimp [restrict, mem_eq], split, { rintro ⟨h₀, h₁⟩, exact ⟨h₀, ⟨_, h₁⟩⟩ }, rintro ⟨h₀, h₁, h₂⟩, exact ⟨h₀, h₂⟩ end /-- `unwrap o` gets the value at `o`, ignoring the condition. This function is unsound. -/ meta def unwrap (o : part α) : α := o.get undefined theorem assert_defined {p : Prop} {f : p → part α} : ∀ (h : p), (f h).dom → (assert p f).dom := exists.intro theorem bind_defined {f : part α} {g : α → part β} : ∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined @[simp] theorem bind_dom {f : part α} {g : α → part β} : (f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl end part
80cac01349d6be216087899d0f3fe584ad6805b4
5e42295de7f5bcdf224b94603a8ec29b17c2d367
/rat_additions.lean
dc01f241e8032b1003866297851610bcc8092c02
[]
no_license
pnmadelaine/lean_polya
9369e0d87dce773f91383bb58ac6fde0a00a1a40
1c62b0b3fa71044b0225ce28030627d251b08ebc
refs/heads/master
1,590,161,172,243
1,515,010,019,000
1,515,010,019,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,956
lean
import data.rat data.nat.gcd tactic.finish algebra.group_power --meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-"++↑(k+1)++"")⟩ meta instance int.reflect : has_reflect int | (int.of_nat n) := if n = 0 then unchecked_cast `(0 : int) else if n = 1 then unchecked_cast `(1 : int) else if n % 2 = 0 then unchecked_cast $ `(λ n : int, bit0 n).subst (int.reflect ↑(n / 2)) else unchecked_cast $ `(λ n : int, bit1 n).subst (int.reflect ↑(n / 2)) | (int.neg_succ_of_nat n) := let rv := int.reflect (int.of_nat (n+1)) in unchecked_cast `(-%%rv : ℤ) /-meta def f (z : ℤ) : expr := `(z) set_option pp.all true run_cmd tactic.trace $ f (-10)-/ --def rat_of_int (i : ℤ) : ℚ := --⟦⟨i, 1, zero_lt_one⟩⟧ --{ num := i, denom := 1, /-meta def num_denum.to_expr : rat.num_denum → expr | (num, ⟨denum, _⟩) := `((rat.of_int %%(int.reflect num)) / (rat.of_int (%%(int.reflect denum)) : ℚ)) meta def num_denum_to_expr_wf : Π a b : rat.num_denum, rat.rel a b → num_denum.to_expr a = num_denum.to_expr b := sorry meta def rat.to_expr := quot.lift num_denum.to_expr num_denum_to_expr_wf meta instance rat.reflect : has_reflect rat := λ q, unchecked_cast $ q.to_expr -/ private meta def nat_to_rat_expr : nat → expr | n := if n = 0 then `(0 : ℚ) else if n = 1 then `(1 : ℚ) else if n % 2 = 0 then `(@bit0 ℚ _ %%(nat_to_rat_expr (n/2))) else `(@bit1 ℚ _ _ %%(nat_to_rat_expr (n/2))) private meta def int_to_rat_expr : int → expr | n := if n = 0 then `(0 : ℚ) else if n < 0 then `(-%%(int_to_rat_expr (-n)) : ℚ) else if n = 1 then `(1 : ℚ) else if n % 2 = 0 then `(@bit0 ℚ _ %%(int_to_rat_expr (n/2))) else `(@bit1 ℚ _ _ %%(int_to_rat_expr (n/2))) meta def rat.to_expr (q : ℚ) : expr := if q.denom = 1 then `(%%(int_to_rat_expr q.num) : ℚ) else `(%%(int_to_rat_expr q.num) / %%(nat_to_rat_expr q.denom) : ℚ) --`(rat.mk_nat %%(int.reflect q.num) %%(nat.reflect q.denom)) meta instance rat.reflect : has_reflect rat := λ q, unchecked_cast $ q.to_expr section open nat theorem gcd_ne_zero_right (a : ℕ) {b : ℕ} (hb : b ≠ 0) : gcd a b ≠ 0 := assume : gcd a b = 0, have gcd a b ∣ b, from gcd_dvd_right _ _, have 0 ∣ b, by cc, have b = 0, from eq_zero_of_zero_dvd this, by contradiction end def sign {α} [decidable_linear_ordered_comm_ring α] (a : α) : α := if a < 0 then (-1) else if a = 0 then 0 else 1 /- section open int def int.gcd : ℤ → ℤ → ℤ | (of_nat k1) (of_nat k2) := of_nat (nat.gcd k1 k2) | (of_nat k1) (neg_succ_of_nat k2) := of_nat (nat.gcd k1 (k2+1)) | (neg_succ_of_nat k1) (of_nat k2) := of_nat (nat.gcd (k1+1) k2) | (neg_succ_of_nat k1) (neg_succ_of_nat k2) := of_nat (nat.gcd (k1+1) (k2+1)) /-def int.sign : ℤ → ℤ --| (of_nat 0) := 0 | (of_nat k) := if k = 0 then 0 else 1 | (neg_succ_of_nat _) := -1-/ /-def int.div : ℤ → ℤ → ℤ | (of_nat k1) (of_nat k2) := of_nat (k1 / k2) | (of_nat k1) (neg_succ_of_nat k2) := neg_succ_of_nat (k1 / (k2+1)) | (neg_succ_of_nat k1) (of_nat k2) := neg_succ_of_nat ((k1) / k2) | (neg_succ_of_nat k1) (neg_succ_of_nat k2) := of_nat ((k1+1) / (k2+1))-/ def int.div (a b : ℤ) : ℤ := sign b * (match a with | of_nat m := of_nat (m / (nat_abs b)) | -[1+m] := -[1+ ((m:nat) / (nat_abs b))] end) instance : has_div int := ⟨int.div⟩ theorem int.of_nat_ne_zero_of_ne_zero {n : ℕ} (h : n ≠ 0) : of_nat n ≠ 0 := suppose of_nat n = of_nat 0, by cc @[ematch] theorem int_gcd_ne_zero_right : Π (a : ℤ) {b : ℤ} (h : b ≠ 0), int.gcd a b ≠ 0 := begin intros, induction a, all_goals {induction b; apply int.of_nat_ne_zero_of_ne_zero; apply gcd_ne_zero_right; finish} end theorem int.gcd_pos_of_ne_right (a : ℤ) {b : ℤ} (h : b ≠ 0) : int.gcd a b > 0 := begin induction a, all_goals {induction b; unfold int.gcd; apply of_nat_p}, end /- variable P : ℕ → Prop theorem f : Π (h : P 0) (h2 : ∀ n, P n → P (n+1)), Π (n : ℕ), P n | h h2 0 := sorry --begin try {do n ← decl_name, interactive.clear [n]}; finish end | h h2 (k+1) := begin apply h2, apply f, apply h, apply h2 end theorem int_gcd_ne_zero_right' : Π (a : ℤ) {b : ℤ} (h : b ≠ 0), int.gcd a b ≠ 0 := begin intros, cases a; cases b, safe [int_gcd_ne_zero_right], -/ /-| (of_nat k1) (of_nat k2) h := begin safe end | (of_nat k1) (neg_succ_of_nat k2) h := sorry | (neg_succ_of_nat k1) (of_nat k2) h := sorry | (neg_succ_of_nat k1) (neg_succ_of_nat k2) h := sorry -/ def num_denum.reduce : rat.num_denum → rat.num_denum | (num, ⟨denum, _⟩) := let g := int.gcd num denum in (num/g, ⟨denum/g, begin end⟩)-/ /-set_option pp.all true run_cmd tactic.trace $ (↑`(-5 : ℤ) : expr) meta example (z : ℤ) : reflected z := by apply_instance -/ /- | n := if n = 0 then unchecked_cast `(0 : nat) else if n % 2 = 0 then unchecked_cast $ `(λ n : nat, bit0 n).subst (nat.reflect (n / 2)) else unchecked_cast $ `(λ n : nat, bit1 n).subst (nat.reflect (n / 2)) -/ -- make this more efficient. Why did it disappear? --meta instance : has_to_pexpr ℕ := ⟨λ n, nat.rec_on n ``(0) (λ _ k, ``(%%k + 1))⟩ --meta instance : has_to_pexpr ℤ := --⟨λ z, int.rec_on z (λ k, ``(%%k)) (λ k, ``(-(%%(k)+1)))⟩ /-meta def num_denum_format : rat.num_denum → format | (num, ⟨denum, _⟩) := if num = 0 then "0" --else if denum = 1 then to_fmt num else to_fmt num ++ "/" ++ to_fmt denum -/ /-meta def num_denum_quote : rat.num_denum → pexpr | (num, ⟨denum, _⟩) := ``(%%(to_pexpr num)/%%(to_pexpr denum))-/ --meta def num_denum_format_wf : Π a b : rat.num_denum, rat.rel a b → num_denum_format a = num_denum_format b := sorry --meta def num_denum_quote_wf : Π a b : rat.num_denum, rat.rel a b → num_denum_quote a = num_denum_quote b := sorry meta def rat.to_string (q : ℚ) : string := if q.denom = 1 then to_string q.num else to_string q.num ++ " / " ++ to_string q.denom meta def rat.to_format (q : ℚ) : format := /-if q.denom = 1 then to_fmt q.num else to_fmt q.num ++ " / " ++ to_fmt q.denom-/ rat.to_string q meta instance : has_to_format ℚ := ⟨rat.to_format⟩ meta instance : has_repr ℚ := ⟨rat.to_string⟩ /-meta instance : has_to_pexpr ℚ := ⟨quot.lift num_denum_quote num_denum_quote_wf⟩ -/ def rat.pow (q : ℚ) : ℤ → ℚ | (int.of_nat n) := q^n | -[1+n] := 1/(q^(n+1)) --def rat.pow (q : ℚ) (z : ℤ) : ℚ := --if q = 1 then q else if z = 1 then q else rat.pow_aux q z lemma rat.mul_pow_neg_one {q : ℚ} (h : q ≠ 0) : q * (rat.pow q (-1)) = 1 := begin change (-1 : ℤ) with -[1+0], simp [rat.pow, mul_inv_cancel h] end lemma rat.pow_neg_one {q : ℚ} : rat.pow q (-1) = 1 / q := begin change (-1 : ℤ) with -[1+0], simp [rat.pow] end lemma rat.pow_one {q : ℚ} : rat.pow q 1 = q := begin change (1 : ℤ) with int.of_nat 1, simp [rat.pow] end lemma rat.pow_pow (a : ℚ) (z1 z2 : ℤ) : rat.pow (rat.pow a z1) z2 = rat.pow a (z1*z2) := sorry lemma rat.one_div_pow (q : ℚ) (z : ℤ) : rat.pow (1/q) z = rat.pow q (-z) := sorry namespace int open nat /-protected def div : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := of_nat (m / n) | (m : ℕ) -[1+ n] := -of_nat (m / succ n) | -[1+ m] 0 := 0 | -[1+ m] (n+1:ℕ) := -[1+ m / succ n] | -[1+ m] -[1+ n] := of_nat (succ (m / succ n)) instance : has_div int := ⟨int.div⟩ -/ theorem exists_eq_of_nat {z : ℤ} (h : z ≥ 0) : ∃ n : ℕ, z = n := match int.le.dest h with | ⟨n, pr⟩ := ⟨n, by clear _match; finish⟩ end end int @[simp] theorem nat.one_pow : Π n : ℕ, nat.pow 1 n = 1 | 0 := rfl | (k+1) := begin unfold nat.pow, rw mul_one, apply nat.one_pow end theorem nat.one_lt_pow_of_one_lt {x n : ℕ} (h : 1 < x) (hn : n > 0) : 1 < nat.pow x n := have h : nat.pow 1 n = 1, from nat.one_pow _, begin rw ←h, apply nat.pow_lt_pow_of_lt_left, repeat {assumption} end theorem rat.one_pow : Π (n : ℤ), rat.pow 1 n = 1 | (int.of_nat n) := by simp [rat.pow] | -[1+n] := by simp [rat.pow, one_inv_eq] theorem rat.mul_pow (q r : ℚ) : Π (z : ℤ), rat.pow (q*r) z = rat.pow q z * rat.pow r z | (int.of_nat n) := mul_pow _ _ _ | -[1+n] := begin unfold rat.pow, rw [mul_pow, div_mul_eq_div_mul_one_div] end theorem rat.mul_pow_rev (q r : ℚ) (z : ℤ) : rat.pow q z * rat.pow r z = rat.pow (q*r) z := by simp [rat.mul_pow] def rat.order : ℚ → ℚ → ordering := λ a b, if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt def int.order : ℤ → ℤ → ordering := λ a b, if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt instance : has_ordering ℚ := ⟨rat.order⟩ instance : has_ordering ℤ := ⟨int.order⟩
aa760fde8faa2daa1df6bd6e4708f5caa437b5b8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/multiset/locally_finite.lean
888f045dd029c569d72d8564941d9de0686e32d2
[ "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
8,516
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Intervals as multisets This file provides basic results about all the `multiset.Ixx`, which are defined in `order.locally_finite`. -/ variables {α : Type*} namespace multiset section preorder variables [preorder α] [locally_finite_order α] {a b c : α} lemma nodup_Icc : (Icc a b).nodup := finset.nodup _ lemma nodup_Ico : (Ico a b).nodup := finset.nodup _ lemma nodup_Ioc : (Ioc a b).nodup := finset.nodup _ lemma nodup_Ioo : (Ioo a b).nodup := finset.nodup _ @[simp] lemma Icc_eq_zero_iff : Icc a b = 0 ↔ ¬a ≤ b := by rw [Icc, finset.val_eq_zero, finset.Icc_eq_empty_iff] @[simp] lemma Ico_eq_zero_iff : Ico a b = 0 ↔ ¬a < b := by rw [Ico, finset.val_eq_zero, finset.Ico_eq_empty_iff] @[simp] lemma Ioc_eq_zero_iff : Ioc a b = 0 ↔ ¬a < b := by rw [Ioc, finset.val_eq_zero, finset.Ioc_eq_empty_iff] @[simp] lemma Ioo_eq_zero_iff [densely_ordered α] : Ioo a b = 0 ↔ ¬a < b := by rw [Ioo, finset.val_eq_zero, finset.Ioo_eq_empty_iff] alias Icc_eq_zero_iff ↔ _ multiset.Icc_eq_zero alias Ico_eq_zero_iff ↔ _ multiset.Ico_eq_zero alias Ioc_eq_zero_iff ↔ _ multiset.Ioc_eq_zero @[simp] lemma Ioo_eq_zero (h : ¬a < b) : Ioo a b = 0 := eq_zero_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2) @[simp] lemma Icc_eq_zero_of_lt (h : b < a) : Icc a b = 0 := Icc_eq_zero h.not_le @[simp] lemma Ico_eq_zero_of_le (h : b ≤ a) : Ico a b = 0 := Ico_eq_zero h.not_lt @[simp] lemma Ioc_eq_zero_of_le (h : b ≤ a) : Ioc a b = 0 := Ioc_eq_zero h.not_lt @[simp] lemma Ioo_eq_zero_of_le (h : b ≤ a) : Ioo a b = 0 := Ioo_eq_zero h.not_lt variables (a) @[simp] lemma Ico_self : Ico a a = 0 := by rw [Ico, finset.Ico_self, finset.empty_val] @[simp] lemma Ioc_self : Ioc a a = 0 := by rw [Ioc, finset.Ioc_self, finset.empty_val] @[simp] lemma Ioo_self : Ioo a a = 0 := by rw [Ioo, finset.Ioo_self, finset.empty_val] variables {a b c} lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := finset.left_mem_Icc lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := finset.left_mem_Ico lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := finset.right_mem_Icc lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := finset.right_mem_Ioc @[simp] lemma left_not_mem_Ioc : a ∉ Ioc a b := finset.left_not_mem_Ioc @[simp] lemma left_not_mem_Ioo : a ∉ Ioo a b := finset.left_not_mem_Ioo @[simp] lemma right_not_mem_Ico : b ∉ Ico a b := finset.right_not_mem_Ico @[simp] lemma right_not_mem_Ioo : b ∉ Ioo a b := finset.right_not_mem_Ioo lemma Ico_filter_lt_of_le_left [decidable_pred (< c)] (hca : c ≤ a) : (Ico a b).filter (λ x, x < c) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_left hca], refl } lemma Ico_filter_lt_of_right_le [decidable_pred (< c)] (hbc : b ≤ c) : (Ico a b).filter (λ x, x < c) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_right_le hbc] lemma Ico_filter_lt_of_le_right [decidable_pred (< c)] (hcb : c ≤ b) : (Ico a b).filter (λ x, x < c) = Ico a c := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_right hcb], refl } lemma Ico_filter_le_of_le_left [decidable_pred ((≤) c)] (hca : c ≤ a) : (Ico a b).filter (λ x, c ≤ x) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_le_left hca] lemma Ico_filter_le_of_right_le [decidable_pred ((≤) b)] : (Ico a b).filter (λ x, b ≤ x) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_right_le], refl } lemma Ico_filter_le_of_left_le [decidable_pred ((≤) c)] (hac : a ≤ c) : (Ico a b).filter (λ x, c ≤ x) = Ico c b := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_left_le hac], refl } end preorder section partial_order variables [partial_order α] [locally_finite_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [Icc, finset.Icc_self, finset.singleton_val] lemma Ico_cons_right (h : a ≤ b) : b ::ₘ (Ico a b) = Icc a b := by { classical, rw [Ico, ←finset.insert_val_of_not_mem right_not_mem_Ico, finset.Ico_insert_right h], refl } lemma Ioo_cons_left (h : a < b) : a ::ₘ (Ioo a b) = Ico a b := by { classical, rw [Ioo, ←finset.insert_val_of_not_mem left_not_mem_Ioo, finset.Ioo_insert_left h], refl } lemma Ico_disjoint_Ico {a b c d : α} (h : b ≤ c) : (Ico a b).disjoint (Ico c d) := λ x hab hbc, by { rw mem_Ico at hab hbc, exact hab.2.not_le (h.trans hbc.1) } @[simp] lemma Ico_inter_Ico_of_le [decidable_eq α] {a b c d : α} (h : b ≤ c) : Ico a b ∩ Ico c d = 0 := multiset.inter_eq_zero_iff_disjoint.2 $ Ico_disjoint_Ico h lemma Ico_filter_le_left {a b : α} [decidable_pred (≤ a)] (hab : a < b) : (Ico a b).filter (λ x, x ≤ a) = {a} := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_left hab], refl } lemma card_Ico_eq_card_Icc_sub_one (a b : α) : (Ico a b).card = (Icc a b).card - 1 := finset.card_Ico_eq_card_Icc_sub_one _ _ lemma card_Ioc_eq_card_Icc_sub_one (a b : α) : (Ioc a b).card = (Icc a b).card - 1 := finset.card_Ioc_eq_card_Icc_sub_one _ _ lemma card_Ioo_eq_card_Ico_sub_one (a b : α) : (Ioo a b).card = (Ico a b).card - 1 := finset.card_Ioo_eq_card_Ico_sub_one _ _ lemma card_Ioo_eq_card_Icc_sub_two (a b : α) : (Ioo a b).card = (Icc a b).card - 2 := finset.card_Ioo_eq_card_Icc_sub_two _ _ end partial_order section linear_order variables [linear_order α] [locally_finite_order α] {a b c d : α} lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := finset.Ico_subset_Ico_iff h lemma Ico_add_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : Ico a b + Ico b c = Ico a c := by rw [add_eq_union_iff_disjoint.2 (Ico_disjoint_Ico le_rfl), Ico, Ico, Ico, ←finset.union_val, finset.Ico_union_Ico_eq_Ico hab hbc] lemma Ico_inter_Ico : Ico a b ∩ Ico c d = Ico (max a c) (min b d) := by rw [Ico, Ico, Ico, ←finset.inter_val, finset.Ico_inter_Ico] @[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_lt] @[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_le] @[simp] lemma Ico_sub_Ico_left (a b c : α) : Ico a b - Ico a c = Ico (max a c) b := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_left] @[simp] lemma Ico_sub_Ico_right (a b c : α) : Ico a b - Ico c b = Ico a (min b c) := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_right] end linear_order section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [locally_finite_order α] lemma map_add_left_Icc (a b c : α) : (Icc a b).map ((+) c) = Icc (c + a) (c + b) := by { classical, rw [Icc, Icc, ←finset.image_add_left_Icc, finset.image_val, (multiset.nodup_map (add_right_injective c) $ finset.nodup _).erase_dup] } lemma map_add_left_Ico (a b c : α) : (Ico a b).map ((+) c) = Ico (c + a) (c + b) := by { classical, rw [Ico, Ico, ←finset.image_add_left_Ico, finset.image_val, (multiset.nodup_map (add_right_injective c) $ finset.nodup _).erase_dup] } lemma map_add_left_Ioc (a b c : α) : (Ioc a b).map ((+) c) = Ioc (c + a) (c + b) := by { classical, rw [Ioc, Ioc, ←finset.image_add_left_Ioc, finset.image_val, (multiset.nodup_map (add_right_injective c) $ finset.nodup _).erase_dup] } lemma map_add_left_Ioo (a b c : α) : (Ioo a b).map ((+) c) = Ioo (c + a) (c + b) := by { classical, rw [Ioo, Ioo, ←finset.image_add_left_Ioo, finset.image_val, (multiset.nodup_map (add_right_injective c) $ finset.nodup _).erase_dup] } lemma map_add_right_Icc (a b c : α) : (Icc a b).map (λ x, x + c) = Icc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Icc _ _ _ } lemma map_add_right_Ico (a b c : α) : (Ico a b).map (λ x, x + c) = Ico (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ico _ _ _ } lemma map_add_right_Ioc (a b c : α) : (Ioc a b).map (λ x, x + c) = Ioc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioc _ _ _ } lemma map_add_right_Ioo (a b c : α) : (Ioo a b).map (λ x, x + c) = Ioo (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioo _ _ _ } end ordered_cancel_add_comm_monoid end multiset
45469a46f2b96aaba40ac5917d54352599d8d6f4
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/category_theory/replete.lean
312e8323a5b60bc1c9a806a2ecfdba3d4e7f80b0
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
1,884
lean
import category_theory.base import category_theory.isomorphism open category_theory open category_theory.category local notation f ` ∘ `:80 g:80 := g ≫ f universes v u namespace category_theory variables (C : Type u) [category.{v} C] class wide_subcategory (D : Π {a b : C}, (a ⟶ b) → Prop) : Prop := (mem_id {} : ∀ (a : C), D (𝟙 a)) (mem_comp {} : ∀ {a b c : C} {f : a ⟶ b} {g : b ⟶ c}, D f → D g → D (g ∘ f)) export wide_subcategory (mem_id mem_comp) class replete_wide_subcategory D extends wide_subcategory.{v} C D : Prop := (mem_iso {} : ∀ {a b : C} (i : iso a b), D i.hom) export replete_wide_subcategory (mem_iso) variables {C} -- mem_id is redundant when we have mem_iso. lemma replete_wide_subcategory.mk' {D : Π ⦃a b : C⦄, (a ⟶ b) → Prop} (mem_iso : ∀ {a b : C} (i : iso a b), D i.hom) (mem_comp : ∀ {a b c : C} {f : a ⟶ b} {g : b ⟶ c}, D f → D g → D (g ∘ f)) : replete_wide_subcategory.{v} C D := { mem_id := λ a, mem_iso (iso.refl a), mem_comp := @mem_comp, mem_iso := @mem_iso } variables {D : Π ⦃a b : C⦄, (a ⟶ b) → Prop} [replete_wide_subcategory.{v} C D] lemma mem_of_mem_comp_left {a b c : C} {f : a ⟶ b} (i : iso b c) (h : D (i.hom ∘ f)) : D f := by convert mem_comp h (mem_iso i.symm); simp lemma mem_of_mem_comp_right {a b c : C} {f : b ⟶ c} (i : iso a b) (h : D (f ∘ i.hom)) : D f := by convert mem_comp (mem_iso i.symm) h; simp lemma mem_iff_mem_of_isomorphic {a b a' b' : C} {f : a ⟶ b} {f' : a' ⟶ b'} (i : iso a a') (j : iso b b') (e : j.hom ∘ f = f' ∘ i.hom) : D f ↔ D f' := iff.intro (assume h, have D (j.hom ∘ f), from mem_comp h (mem_iso j), by rw e at this; exact mem_of_mem_comp_right i this) (assume h, have D (f' ∘ i.hom), from mem_comp (mem_iso i) h, by rw ←e at this; exact mem_of_mem_comp_left j this) end category_theory
e09976b05c429d947f013ffd89a5fb17bf464d35
618003631150032a5676f229d13a079ac875ff77
/src/tactic/wlog.lean
b51c0960a5451fa1a0ea8f523080291bc7c0a1af
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
9,426
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 Without loss of generality tactic. -/ import tactic.tauto import data.list.perm open expr tactic lean lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic private meta def update_pp_name : expr → name → expr | (local_const n _ bi d) pp := local_const n pp bi d | e n := e private meta def elim_or : ℕ → expr → tactic (list expr) | 0 h := fail "zero cases" | 1 h := return [h] | (n + 1) h := do [(_, [hl], []), (_, [hr], [])] ← induction h, -- there should be no dependent terms [gl, gr] ← get_goals, set_goals [gr], hsr ← elim_or n hr, gsr ← get_goals, set_goals (gl :: gsr), return (hl :: hsr) private meta def dest_or : expr → tactic (list expr) | e := do `(%%a ∨ %%b) ← whnf e | return [e], lb ← dest_or b, return (a :: lb) private meta def match_perms (pat : pattern) : expr → tactic (list $ list expr) | t := (do m ← match_pattern pat t, guard (m.2.all expr.is_local_constant), return [m.2]) <|> (do `(%%l ∨ %%r) ← whnf t, m ← match_pattern pat l, rs ← match_perms r, return (m.2 :: rs)) private meta def update_type : expr → expr → expr | (local_const n pp bi d) t := local_const n pp bi t | e t := e private meta def intron' : ℕ → tactic (list expr) | 0 := return [] | (i + 1) := do n ← intro1, ls ← intron' i, return (n :: ls) meta def wlog (vars' : list expr) (h_cases fst_case : expr) (perms : list (list expr)) : tactic unit := do guard h_cases.is_local_constant, -- reorder s.t. context is Γ ⬝ vars ⬝ cases ⊢ ∀deps, … nr ← revert_lst (vars' ++ [h_cases]), vars ← intron' vars'.length, h_cases ← intro h_cases.local_pp_name, cases ← infer_type h_cases, h_fst_case ← mk_local_def h_cases.local_pp_name (fst_case.instantiate_locals $ (vars'.zip vars).map $ λ⟨o, n⟩, (o.local_uniq_name, n)), ((), pr) ← solve_aux cases (repeat $ exact h_fst_case <|> left >> skip), t ← target, fixed_vars ← vars.mmap (λv, do t ← infer_type v, return (update_type v t) ), let t' := (instantiate_local h_cases.local_uniq_name pr t).pis (fixed_vars ++ [h_fst_case]), (h, [g]) ← local_proof `this t' (do clear h_cases, vars.mmap clear, intron nr), h₀ :: hs ← elim_or perms.length h_cases, solve1 (do exact (h.mk_app $ vars ++ [h₀])), focus ((hs.zip perms.tail).map $ λ⟨h_case, perm⟩, do let p_v := (vars'.zip vars).map (λ⟨p, v⟩, (p.local_uniq_name, v)), let p := perm.map (λp, p.instantiate_locals p_v), note `this none (h.mk_app $ p ++ [h_case]), clear h, return ()), gs ← get_goals, set_goals (g :: gs) namespace interactive open interactive interactive.types expr private meta def parse_permutations : option (list (list name)) → tactic (list (list expr)) | none := return [] | (some []) := return [] | (some perms@(p₀ :: ps)) := do (guard p₀.nodup <|> fail "No permutation `xs_i` in `using [xs_1, …, xs_n]` should contain the same variable twice."), (guard (perms.all $ λp, p.perm p₀) <|> fail "The permutations `xs_i` in `using [xs_1, …, xs_n]` must be permutations of the same variables."), perms.mmap (λp, p.mmap get_local) /-- Without loss of generality: reduces to one goal under variables permutations. Given a goal of the form `g xs`, a predicate `p` over a set of variables, as well as variable permutations `xs_i`. Then `wlog` produces goals of the form The case goal, i.e. the permutation `xs_i` covers all possible cases: `⊢ p xs_0 ∨ ⋯ ∨ p xs_n` The main goal, i.e. the goal reduced to `xs_0`: `(h : p xs_0) ⊢ g xs_0` The invariant goals, i.e. `g` is invariant under `xs_i`: `(h : p xs_i) (this : g xs_0) ⊢ gs xs_i` Either the permutation is provided, or a proof of the disjunction is provided to compute the permutation. The disjunction need to be in assoc normal form, e.g. `p₀ ∨ (p₁ ∨ p₂)`. In many cases the invariant goals can be solved by AC rewriting using `cc` etc. Example: On a state `(n m : ℕ) ⊢ p n m` the tactic `wlog h : n ≤ m using [n m, m n]` produces the following states: `(n m : ℕ) ⊢ n ≤ m ∨ m ≤ n` `(n m : ℕ) (h : n ≤ m) ⊢ p n m` `(n m : ℕ) (h : m ≤ n) (this : p n m) ⊢ p m n` `wlog` supports different calling conventions. The name `h` is used to give a name to the introduced case hypothesis. If the name is avoided, the default will be `case`. (1) `wlog : p xs0 using [xs0, …, xsn]` Results in the case goal `p xs0 ∨ ⋯ ∨ ps xsn`, the main goal `(case : p xs0) ⊢ g xs0` and the invariance goals `(case : p xsi) (this : g xs0) ⊢ g xsi`. (2) `wlog : p xs0 := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. (3) `wlog := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. This is not as stable as (2), for example `p` cannot be a disjunction. (4) `wlog : R x y using x y` and `wlog : R x y` Produces the case `R x y ∨ R y x`. If `R` is ≤, then the disjunction discharged using linearity. If `using x y` is avoided then `x` and `y` are the last two variables appearing in the expression `R x y`. -/ meta def wlog (h : parse ident?) (pat : parse (tk ":" *> texpr)?) (cases : parse (tk ":=" *> texpr)?) (perms : parse (tk "using" *> (list_of (ident*) <|> (λx, [x]) <$> ident*))?) (discharger : tactic unit := (tactic.solve_by_elim <|> tactic.tautology tt <|> using_smt (smt_tactic.intros >> smt_tactic.solve_goals))) : tactic unit := do perms ← parse_permutations perms, (pat, cases_pr, cases_goal, vars, perms) ← (match cases with | some r := do vars::_ ← return perms | fail "At least one set of variables expected, i.e. `using x y` or `using [x y, y x]`.", cases_pr ← to_expr r, cases_pr ← (if cases_pr.is_local_constant then return $ match h with some n := update_pp_name cases_pr n | none := cases_pr end else do note (h.get_or_else `case) none cases_pr), cases ← infer_type cases_pr, (pat, perms') ← match pat with | some pat := do pat ← to_expr pat, let vars' := vars.filter $ λv, v.occurs pat, case_pat ← mk_pattern [] vars' pat [] vars', perms' ← match_perms case_pat cases, return (pat, perms') | none := do (p :: ps) ← dest_or cases, let vars' := vars.filter $ λv, v.occurs p, case_pat ← mk_pattern [] vars' p [] vars', perms' ← (p :: ps).mmap (λp, do m ← match_pattern case_pat p, return m.2), return (p, perms') end, let vars_name := vars.map local_uniq_name, guard (perms'.all $ λp, p.all $ λv, v.is_local_constant ∧ v.local_uniq_name ∈ vars_name) <|> fail "Cases contains variables not declared in `using x y z`", perms ← (if perms.length = 1 then do return (perms'.map $ λp, p ++ vars.filter (λv, p.all (λv', v'.local_uniq_name ≠ v.local_uniq_name))) else do guard (perms.length = perms'.length) <|> fail "The provided permutation list has a different length then the provided cases.", return perms), return (pat, cases_pr, @none expr, vars, perms) | none := do let name_h := h.get_or_else `case, some pat ← return pat | fail "Either specify cases or a pattern with permutations", pat ← to_expr pat, (do [x, y] ← match perms with | [] := return pat.list_local_consts | [l] := return l | _ := failed end, let cases := mk_or_lst [pat, pat.instantiate_locals [(x.local_uniq_name, y), (y.local_uniq_name, x)]], (do `(%%x' ≤ %%y') ← return pat, (cases_pr, []) ← local_proof name_h cases (exact ``(le_total %%x' %%y')), return (pat, cases_pr, none, [x, y], [[x, y], [y, x]])) <|> (do (cases_pr, [g]) ← local_proof name_h cases skip, return (pat, cases_pr, some g, [x, y], [[x, y], [y, x]]))) <|> (do guard (perms.length ≥ 2) <|> fail ("To generate cases at least two permutations are required, i.e. `using [x y, y x]`" ++ " or exactly 0 or 2 variables"), (vars :: perms') ← return perms, let names := vars.map local_uniq_name, let cases := mk_or_lst (pat :: perms'.map (λp, pat.instantiate_locals (names.zip p))), (cases_pr, [g]) ← local_proof name_h cases skip, return (pat, cases_pr, some g, vars, perms)) end), let name_fn := (if perms.length = 2 then λi, `invariant else λi, mk_simple_name ("invariant_" ++ to_string (i + 1))), with_enable_tags $ tactic.focus1 $ do t ← get_main_tag, tactic.wlog vars cases_pr pat perms, tactic.focus (set_main_tag (mk_num_name `_case 0 :: `main :: t) :: (list.range (perms.length - 1)).map (λi, do set_main_tag (mk_num_name `_case 0 :: name_fn i :: t), try discharger)), match cases_goal with | some g := do set_tag g (mk_num_name `_case 0 :: `cases :: t), gs ← get_goals, set_goals (g :: gs) | none := skip end add_tactic_doc { name := "wlog", category := doc_category.tactic, decl_names := [``wlog], tags := ["logic"] } end interactive end tactic
4802994c1f10512a739093cd8a39f7036064a273
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/category_theory/examples/topological_spaces.lean
00ce5dc816e99d74e59e7b845c8e0131971cdfae
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,119
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison, Mario Carneiro import category_theory.full_subcategory import category_theory.functor_category import category_theory.natural_isomorphism import analysis.topology.topological_space import analysis.topology.continuity import order.galois_connection open category_theory open category_theory.nat_iso open topological_space universe u namespace category_theory.examples /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space instance (x : Top) : topological_space x := x.str namespace Top instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩ -- local attribute [class] continuous -- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2 end Top variables {X : Top.{u}} instance : small_category (opens X) := by apply_instance def nbhd (x : X.α) := { U : opens X // x ∈ U } def nbhds (x : X.α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map {X Y : Top.{u}} (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f.val ⁻¹' U, f.property _ U.property ⟩, map := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }. @[simp] lemma map_id_obj (X : Top.{u}) (U : opens X) : (map (𝟙 X)).obj U = U := by tidy @[simp] def map_id (X : Top.{u}) : map (𝟙 X) ≅ functor.id (opens X) := { hom := { app := λ U, 𝟙 U }, inv := { app := λ U, 𝟙 U } } -- We could make f g implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso {X Y : Top.{u}} (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg _ (congr_arg _ h)) _) ) (by obviously) @[simp] def map_iso_id {X : Top.{u}} (h) : map_iso (𝟙 X) (𝟙 X) h = iso.refl (map _) := rfl end category_theory.examples
901125157e1de630b9fbf403abfb77ca99337c85
abd85493667895c57a7507870867b28124b3998f
/src/topology/instances/ennreal.lean
c4e66c879cf56a08833949cd0b134844399d68b9
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
38,698
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 -/ import topology.instances.nnreal /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} open_locale ennreal big_operators namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} section topological_space open topological_space /-- Topology on `ennreal`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ennreal := preorder.topology ennreal instance : order_topology ennreal := ⟨rfl⟩ instance : t2_space ennreal := by apply_instance -- short-circuit type class inference instance : second_countable_topology ennreal := ⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : nnreal → ennreal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ennreal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : nnreal | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : nnreal | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals nnreal _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma coe_range_mem_nhds : range (coe : nnreal → ennreal) ∈ 𝓝 (r : ennreal) := have {a : ennreal | a ≠ ⊤} = range (coe : nnreal → ennreal), from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe], this ▸ mem_nhds_sets is_open_ne_top coe_ne_top @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} : tendsto (λa, (m a : ennreal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe {α} [topological_space α] {f : α → nnreal} : continuous (λa, (f a : ennreal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : nnreal} : 𝓝 (r : ennreal) = (𝓝 r).map coe := by rw [embedding_coe.induced, map_nhds_induced_eq coe_range_mem_nhds] lemma nhds_coe_coe {r p : nnreal} : 𝓝 ((r : ennreal), (p : ennreal)) = (𝓝 (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) := begin rw [(embedding_coe.prod_mk embedding_coe).map_nhds_eq], rw [← prod_range_range_eq], exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds end lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_nnreal) (𝓝 a) (𝓝 a.to_nnreal) := begin cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)], exact tendsto_id end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := continuous_on_iff_continuous_restrict.2 $ continuous_iff_continuous_at.2 $ λ x, (tendsto_to_nnreal x.2).comp continuous_at_subtype_val lemma tendsto_to_real {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_real) (𝓝 a) (𝓝 a.to_real) := λ ha, tendsto.comp ((@nnreal.tendsto_coe _ (𝓝 a.to_nnreal) id (a.to_nnreal)).2 tendsto_id) (tendsto_to_nnreal ha) lemma tendsto_nhds_top {m : α → ennreal} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_generate_from $ assume s hs, match s, hs with | _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim | _, ⟨some r, or.inl rfl⟩, hr := let ⟨n, hrn⟩ := exists_nat_gt r in mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from lt_trans (show (r : ennreal) < n, from (coe_nat n) ▸ coe_lt_coe.2 hrn) hnma | _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim end lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ lemma nhds_top : 𝓝 ∞ = ⨅a ≠ ∞, principal (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_zero : 𝓝 (0 : ennreal) = ⨅a ≠ 0, principal (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] /-- The set of finite `ennreal` numbers is homeomorphic to `nnreal`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ nnreal := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe, continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ (continuous_coe.2 continuous_id) } /-- The set of finite `ennreal` numbers is homeomorphic to `nnreal`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ nnreal := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not @[nolint ge_or_gt] -- see Note [nolint_ge] lemma Icc_mem_nhds : x ≠ ⊤ → ε > 0 → Icc (x - ε) (x + ε) ∈ 𝓝 x := begin assume xt ε0, rw mem_nhds_sets_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, principal (Icc (x - ε) (x + ε)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases dense xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rw ha at *, rcases dense xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ennreal` numbers. See also `tendsto_order` for a version with strict inequalities. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] protected theorem tendsto_nhds {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] lemma tendsto_coe_nnreal_nhds_top {α} {l : filter α} {f : α → nnreal} (h : tendsto f l at_top) : tendsto (λa, (f a : ennreal)) l (𝓝 ∞) := tendsto_nhds_top $ assume n, have ∀ᶠ a in l, ↑(n+1) ≤ f a := h $ mem_at_top _, mem_sets_of_superset this $ assume a (ha : ↑(n+1) ≤ f a), begin rw [← coe_nat], dsimp, exact coe_lt_coe.2 (lt_of_lt_of_le (nat.cast_lt.2 (nat.lt_succ_self _)) ha) end instance : topological_add_monoid ennreal := ⟨ continuous_iff_continuous_at.2 $ have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (𝓝 (⊤, a)) (𝓝 ⊤), from assume a, tendsto_nhds_top $ assume n, have set.prod {a | ↑n < a } univ ∈ 𝓝 ((⊤:ennreal), a), from prod_mem_nhds_sets (lt_mem_nhds $ coe_nat n ▸ coe_lt_top) univ_mem_sets, show {a : ennreal × ennreal | ↑n < a.fst + a.snd} ∈ 𝓝 (⊤, a), begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end, begin rintro ⟨a₁, a₂⟩, cases a₁, { simp [continuous_at, none_eq_top, hl a₂], }, cases a₂, { simp [continuous_at, none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤, tendsto_map'_iff, (∘)], convert hl a₁, simp [add_comm] }, simp [continuous_at, some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_add.symm, tendsto_coe, tendsto_add] end ⟩ protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (𝓝 ((⊤:ennreal), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top $ assume n, _, rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩, rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩, rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩, have hε : ε > 0, from coe_lt_coe.1 hε', refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _, rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) : begin simp [nnreal.div_def], rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, ← coe_nat, mul_one], exact zero_lt_iff_ne_zero.1 hε end ... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _) ... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul (le_of_lt h₁) (le_of_lt h₂) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha protected lemma continuous_const_mul {a : ennreal} (ha : a < ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, tendsto.const_mul tendsto_id $ or.inr $ ne_of_lt ha protected lemma continuous_mul_const {a : ennreal} (ha : a < ⊤) : continuous (λ x, x * a) := by simpa only [mul_comm] using ennreal.continuous_const_mul ha protected lemma continuous_inv : continuous (has_inv.inv : ennreal → ennreal) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ennreal} {a : ennreal} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ennreal)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma Sup_add {s : set ennreal} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := have Sup ((λb, b + a) '' s) = Sup s + a, from is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, add_le_add' h (le_refl _)) (is_lub_Sup s) hs (tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds)), by simp [Sup_image, -add_comm] at this; exact this.symm lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by simp [Sup_range] ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ennreal, (⨆i, f i) = 0 := assume f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add' (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀a, monotone (f a)) : s.sum (λa, supr (f a)) = (⨆ n, s.sum (λa, f a n)) := begin refine finset.induction_on s _ _, { simp, exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ennreal), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) (is_lub_Sup _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end end priority lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact nnreal.tendsto.sub tendsto_const_nhds tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨i⟩ := hι in let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_glb_of_is_lub_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) is_lub_supr ⟨_, i, rfl⟩ (tendsto.comp ennreal.tendsto_coe_sub (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ennreal} @[norm_cast] protected lemma has_sum_coe {f : α → nnreal} {r : nnreal} : has_sum (λa, (f a : ennreal)) ↑r ↔ has_sum f r := have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → nnreal} (h : has_sum f r) : (∑'a, (f a : ennreal)) = r := tsum_eq_has_sum $ ennreal.has_sum_coe.2 $ h protected lemma coe_tsum {f : α → nnreal} : summable f → ↑(tsum f) = (∑'a, (f a : ennreal)) | ⟨r, hr⟩ := by rw [tsum_eq_has_sum hr, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, s.sum f) := tendsto_order.2 ⟨assume a' ha', let ⟨s, hs⟩ := lt_supr_iff.mp ha' in mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩, assume a' ha', univ_mem_sets' $ assume s, have s.sum f ≤ ⨆(s : finset α), s.sum f, from le_supr (λ(s : finset α), s.sum f) s, lt_of_le_of_lt this ha'⟩ @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → nnreal} : (∑' b, (f b:ennreal)) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ennreal)) to nnreal using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : (∑'a, f a) = (⨆s:finset α, s.sum f) := tsum_eq_has_sum ennreal.has_sum protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : (∑' a, f a) = ⨆ i, (s i).sum f := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, t.sum f) (s i)) = ⨆s:finset α, s.sum f, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) : (∑'p:Σa, β a, f p.1 p.2) = (∑'a b, f a b) := tsum_sigma (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ennreal) : (∑'p:(Σa, β a), f p) = (∑'a b, f ⟨a, b⟩) := tsum_sigma (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ennreal} : (∑'p:α×β, f p.1 p.2) = (∑'a, ∑'b, f a b) := let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in calc (∑'p:α×β, f' (j p)) = (∑'p:Σa:α, β, f p.1 p.2) : tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl) ... = (∑'a, ∑'b, f a b) : ennreal.tsum_sigma f protected lemma tsum_comm {f : α → β → ennreal} : (∑'a, ∑'b, f a b) = (∑'b, ∑'a, f a b) := let f' : α×β → ennreal := λp, f p.1 p.2 in calc (∑'a, ∑'b, f a b) = (∑'p:α×β, f' p) : ennreal.tsum_prod.symm ... = (∑'p:β×α, f' (prod.swap p)) : (tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm ... = (∑'b, ∑'a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a))) protected lemma tsum_add : (∑'a, f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑'a, f a) ≤ (∑'a, g a) := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} : (∑'i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma le_tsum (a : α) : f a ≤ (∑'a, f a) := calc f a = ({a} : finset α).sum f : by simp ... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _ ... = (∑'a, f a) : by rw [ennreal.tsum_eq_supr_sum] protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → (∑' a, f a) = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a protected lemma ne_top_of_tsum_ne_top (h : (∑' a, f a) ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : (∑'i, a * f i) = a * (∑'i, f i) := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in have sum_ne_0 : (∑'i, f i) ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ (∑'i, f i) : ennreal.le_tsum _, have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (𝓝 (a * (∑'i, f i))), by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f), from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), tsum_eq_has_sum this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} : (∑'b:α, ⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end end tsum end ennreal namespace nnreal lemma exists_le_has_sum_of_le {f g : β → nnreal} {r : nnreal} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have (∑'b, (g b : ennreal)) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ lemma summable_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable lemma has_sum_iff_tendsto_nat {f : ℕ → nnreal} (r : nnreal) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → nnreal} (hf : summable f) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf end nnreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin let g : α → nnreal := λ a, ⟨f a, hn a⟩, have hg : summable g, by rwa ← nnreal.summable_coe, convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi); { rw nnreal.coe_tsum, congr } end lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : β) : nnreal := ⟨g b, hg b⟩ in have summable f', from nnreal.summable_coe.1 hf, have summable g', from nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this, show summable (λb, g' b : β → ℝ), from nnreal.summable_coe.2 this lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (𝓝 r) := ⟨has_sum.tendsto_sum_nat, assume hfr, have 0 ≤ r := ge_of_tendsto at_top_ne_bot hfr $ univ_mem_sets' $ assume i, show 0 ≤ (finset.range i).sum f, from finset.sum_nonneg $ assume i _, hf i, let f' (n : ℕ) : nnreal := ⟨f n, hf n⟩, r' : nnreal := ⟨r, this⟩ in have f_eq : f = (λi:ℕ, (f' i : ℝ)) := rfl, have r_eq : r = r' := rfl, begin rw [f_eq, r_eq, nnreal.has_sum_coe, nnreal.has_sum_iff_tendsto_nat, ← nnreal.tendsto_coe], simp only [nnreal.coe_sum], exact hfr end⟩ lemma infi_real_pos_eq_infi_nnreal_pos {α : Type*} [complete_lattice α] {f : ℝ → α} : (⨅(n:ℝ) (h : 0 < n), f n) = (⨅(n:nnreal) (h : 0 < n), f n) := le_antisymm (le_infi $ assume n, le_infi $ assume hn, infi_le_of_le n $ infi_le _ (nnreal.coe_pos.2 hn)) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, le_of_lt hr⟩ $ infi_le _ hr) section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_val_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm end section variable [emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ennreal β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩), show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y, { assume e he, let ε := min (f x - e) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left' (min_le_left _ _) ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≤ f x + (e - f x) : add_le_add_left' (min_le_left _ _) ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by simp), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto at_top_ne_bot (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
755f9b6507375e82c384c3b8ae13f943ffe0b377
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/ref2.lean
cfee291ac82833decb23fdc87cbc112c8e1e32da
[ "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
278
lean
def initX : IO (IO.Ref Nat) := IO.mkRef 0 @[init initX] constant x : IO.Ref Nat := default _ def inc : IO Unit := do v ← x.get, x.set (v+1), IO.println (">> " ++ toString v) def main (xs : List String) : IO Unit := do let n := xs.head.toNat, n.mrepeat (λ _, inc)
dc42ff7d8d15a312858c24caf503684dfb7fd21a
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/sheaves/sheaf_condition/opens_le_cover.lean
081f85a57a0bd29ac6b2c0d1349856933f5acaef
[ "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
13,493
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf import category_theory.limits.final import topology.sheaves.sheaf_condition.pairwise_intersections /-! # Another version of the sheaf condition. Given a family of open sets `U : ι → opens X` we can form the subcategory `{ V : opens X // ∃ i, V ≤ U i }`, which has `supr U` as a cocone. The sheaf condition on a presheaf `F` is equivalent to `F` sending the opposite of this cocone to a limit cone in `C`, for every `U`. This condition is particularly nice when checking the sheaf condition because we don't need to do any case bashing (depending on whether we're looking at single or double intersections, or equivalently whether we're looking at the first or second object in an equalizer diagram). ## References * This is the definition Lurie uses in [Spectral Algebraic Geometry][LurieSAG]. -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf namespace sheaf_condition /-- The category of open sets contained in some element of the cover. -/ @[derive category] def opens_le_cover : Type v := full_subcategory (λ (V : opens X), ∃ i, V ≤ U i) instance [inhabited ι] : inhabited (opens_le_cover U) := ⟨⟨⊥, default, bot_le⟩⟩ namespace opens_le_cover variables {U} /-- An arbitrarily chosen index such that `V ≤ U i`. -/ def index (V : opens_le_cover U) : ι := V.property.some /-- The morphism from `V` to `U i` for some `i`. -/ def hom_to_index (V : opens_le_cover U) : V.obj ⟶ U (index V) := (V.property.some_spec).hom end opens_le_cover /-- `supr U` as a cocone over the opens sets contained in some element of the cover. (In fact this is a colimit cocone.) -/ def opens_le_cover_cocone : cocone (full_subcategory_inclusion _ : opens_le_cover U ⥤ opens X) := { X := supr U, ι := { app := λ V : opens_le_cover U, V.hom_to_index ≫ opens.le_supr U _, } } end sheaf_condition open sheaf_condition /-- An equivalent formulation of the sheaf condition (which we prove equivalent to the usual one below as `is_sheaf_iff_is_sheaf_opens_le_cover`). A presheaf is a sheaf if `F` sends the cone `(opens_le_cover_cocone U).op` to a limit cone. (Recall `opens_le_cover_cocone U`, has cone point `supr U`, mapping down to any `V` which is contained in some `U i`.) -/ def is_sheaf_opens_le_cover : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (is_limit (F.map_cone (opens_le_cover_cocone U).op)) namespace sheaf_condition open category_theory.pairwise /-- Implementation detail: the object level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U` -/ @[simp] def pairwise_to_opens_le_cover_obj : pairwise ι → opens_le_cover U | (single i) := ⟨U i, ⟨i, le_rfl⟩⟩ | (pair i j) := ⟨U i ⊓ U j, ⟨i, inf_le_left⟩⟩ open category_theory.pairwise.hom /-- Implementation detail: the morphism level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U` -/ def pairwise_to_opens_le_cover_map : Π {V W : pairwise ι}, (V ⟶ W) → (pairwise_to_opens_le_cover_obj U V ⟶ pairwise_to_opens_le_cover_obj U W) | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := hom_of_le inf_le_left | _ _ (right i j) := hom_of_le inf_le_right /-- The category of single and double intersections of the `U i` maps into the category of open sets below some `U i`. -/ @[simps] def pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U := { obj := pairwise_to_opens_le_cover_obj U, map := λ V W i, pairwise_to_opens_le_cover_map U i, } instance (V : opens_le_cover U) : nonempty (structured_arrow V (pairwise_to_opens_le_cover U)) := ⟨{ right := single (V.index), hom := V.hom_to_index }⟩ /-- The diagram consisting of the `U i` and `U i ⊓ U j` is cofinal in the diagram of all opens contained in some `U i`. -/ -- This is a case bash: for each pair of types of objects in `pairwise ι`, -- we have to explicitly construct a zigzag. instance : functor.final (pairwise_to_opens_le_cover U) := ⟨λ V, is_connected_of_zigzag $ λ A B, begin rcases A with ⟨⟨⟨⟩⟩, ⟨i⟩|⟨i,j⟩, a⟩; rcases B with ⟨⟨⟨⟩⟩, ⟨i'⟩|⟨i',j'⟩, b⟩; dsimp at *, { refine ⟨[ { left := ⟨⟨⟩⟩, right := pair i i', hom := (le_inf a.le b.le).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil) }, { refine ⟨[ { left := ⟨⟨⟩⟩, right := pair i' i, hom := (le_inf (b.le.trans inf_le_left) a.le).hom, }, { left := ⟨⟨⟩⟩, right := single i', hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := right i' i, }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i' i, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil)) }, { refine ⟨[ { left := ⟨⟨⟩⟩, right := single i, hom := (a.le.trans inf_le_left).hom, }, { left := ⟨⟨⟩⟩, right := pair i i', hom := (le_inf (a.le.trans inf_le_left) b.le).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil)) }, { refine ⟨[ { left := ⟨⟨⟩⟩, right := single i, hom := (a.le.trans inf_le_left).hom, }, { left := ⟨⟨⟩⟩, right := pair i i', hom := (le_inf (a.le.trans inf_le_left) (b.le.trans inf_le_left)).hom, }, { left := ⟨⟨⟩⟩, right := single i', hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil))), }, end⟩ /-- The diagram in `opens X` indexed by pairwise intersections from `U` is isomorphic (in fact, equal) to the diagram factored through `opens_le_cover U`. -/ def pairwise_diagram_iso : pairwise.diagram U ≅ pairwise_to_opens_le_cover U ⋙ full_subcategory_inclusion _ := { hom := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, }, inv := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, }, } /-- The cocone `pairwise.cocone U` with cocone point `supr U` over `pairwise.diagram U` is isomorphic to the cocone `opens_le_cover_cocone U` (with the same cocone point) after appropriate whiskering and postcomposition. -/ def pairwise_cocone_iso : (pairwise.cocone U).op ≅ (cones.postcompose_equivalence (nat_iso.op (pairwise_diagram_iso U : _) : _)).functor.obj ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op) := cones.ext (iso.refl _) (by tidy) end sheaf_condition open sheaf_condition /-- The sheaf condition in terms of a limit diagram over all `{ V : opens X // ∃ i, V ≤ U i }` is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_opens_le_cover_iff_is_sheaf_pairwise_intersections (F : presheaf C X) : F.is_sheaf_opens_le_cover ↔ F.is_sheaf_pairwise_intersections := forall₂_congr $ λ ι U, equiv.nonempty_congr $ calc is_limit (F.map_cone (opens_le_cover_cocone U).op) ≃ is_limit ((F.map_cone (opens_le_cover_cocone U).op).whisker (pairwise_to_opens_le_cover U).op) : (functor.initial.is_limit_whisker_equiv (pairwise_to_opens_le_cover U).op _).symm ... ≃ is_limit (F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op)) : is_limit.equiv_iso_limit F.map_cone_whisker.symm ... ≃ is_limit ((cones.postcompose_equivalence _).functor.obj (F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op))) : (is_limit.postcompose_hom_equiv _ _).symm ... ≃ is_limit (F.map_cone ((cones.postcompose_equivalence _).functor.obj ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op))) : is_limit.equiv_iso_limit (functor.map_cone_postcompose_equivalence_functor _).symm ... ≃ is_limit (F.map_cone (pairwise.cocone U).op) : is_limit.equiv_iso_limit ((cones.functoriality _ _).map_iso (pairwise_cocone_iso U : _).symm) section variables {Y : opens X} (hY : Y = supr U) /-- Given a family of opens `U` and an open `Y` equal to the union of opens in `U`, we may take the presieve on `Y` associated to `U` and the sieve generated by it, and form the full subcategory (subposet) of opens contained in `Y` (`over Y`) consisting of arrows in the sieve. This full subcategory is equivalent to `opens_le_cover U`, the (poset) category of opens contained in some `U i`. -/ @[simps] def generate_equivalence_opens_le : full_subcategory (λ (f : over Y), (sieve.generate (presieve_of_covering_aux U Y)).arrows f.hom) ≌ opens_le_cover U := { functor := { obj := λ f, ⟨f.1.left, let ⟨_,h,_,⟨i,hY⟩,_⟩ := f.2 in ⟨i, hY ▸ h.le⟩⟩, map := λ _ _ g, g.left }, inverse := { obj := λ V, ⟨over.mk (hY.substr (let ⟨i,h⟩ := V.2 in h.trans (le_supr U i))).hom, let ⟨i,h⟩ := V.2 in ⟨U i, h.hom, (hY.substr (le_supr U i)).hom, ⟨i, rfl⟩, rfl⟩⟩, map := λ _ _ g, over.hom_mk g }, unit_iso := eq_to_iso $ category_theory.functor.ext (by {rintro ⟨⟨_,_⟩,_⟩, dsimp, congr; ext}) (by {intros, ext}), counit_iso := eq_to_iso $ category_theory.functor.hext (by {intro, ext, refl}) (by {intros, refl}) } /-- Given a family of opens `opens_le_cover_cocone U` is essentially the natural cocone associated to the sieve generated by the presieve associated to `U` with indexing category changed using the above equivalence. -/ @[simps] def whisker_iso_map_generate_cocone : cone.whisker (generate_equivalence_opens_le U hY).op.functor (F.map_cone (opens_le_cover_cocone U).op) ≅ F.map_cone (sieve.generate (presieve_of_covering_aux U Y)).arrows.cocone.op := { hom := { hom := F.map (eq_to_hom (congr_arg op hY.symm)), w' := λ j, by { erw ← F.map_comp, congr } }, inv := { hom := F.map (eq_to_hom (congr_arg op hY)), w' := λ j, by { erw ← F.map_comp, congr } }, hom_inv_id' := by { ext, simp [eq_to_hom_map], }, inv_hom_id' := by { ext, simp [eq_to_hom_map], } } /-- Given a presheaf `F` on the topological space `X` and a family of opens `U` of `X`, the natural cone associated to `F` and `U` used in the definition of `F.is_sheaf_opens_le_cover` is a limit cone iff the natural cone associated to `F` and the sieve generated by the presieve associated to `U` is a limit cone. -/ def is_limit_opens_le_equiv_generate₁ : is_limit (F.map_cone (opens_le_cover_cocone U).op) ≃ is_limit (F.map_cone (sieve.generate (presieve_of_covering_aux U Y)).arrows.cocone.op) := (is_limit.whisker_equivalence_equiv (generate_equivalence_opens_le U hY).op).trans (is_limit.equiv_iso_limit (whisker_iso_map_generate_cocone F U hY)) /-- Given a presheaf `F` on the topological space `X` and a presieve `R` whose generated sieve is covering for the associated Grothendieck topology (equivalently, the presieve is covering for the associated pretopology), the natural cone associated to `F` and the family of opens associated to `R` is a limit cone iff the natural cone associated to `F` and the generated sieve is a limit cone. Since only the existence of a 1-1 correspondence will be used, the exact definition does not matter, so tactics are used liberally. -/ def is_limit_opens_le_equiv_generate₂ (R : presieve Y) (hR : sieve.generate R ∈ opens.grothendieck_topology X Y) : is_limit (F.map_cone (opens_le_cover_cocone (covering_of_presieve Y R)).op) ≃ is_limit (F.map_cone (sieve.generate R).arrows.cocone.op) := begin convert is_limit_opens_le_equiv_generate₁ F (covering_of_presieve Y R) (covering_of_presieve.supr_eq_of_mem_grothendieck Y R hR).symm using 2; rw covering_presieve_eq_self R, end /-- A presheaf `(opens X)ᵒᵖ ⥤ C` on a topological space `X` is a sheaf on the site `opens X` iff it satisfies the `is_sheaf_opens_le_cover` sheaf condition. The latter is not the official definition of sheaves on spaces, but has the advantage that it does not require `has_products C`. -/ lemma is_sheaf_iff_is_sheaf_opens_le_cover : F.is_sheaf ↔ F.is_sheaf_opens_le_cover := begin refine (presheaf.is_sheaf_iff_is_limit _ _).trans _, split, { intros h ι U, rw (is_limit_opens_le_equiv_generate₁ F U rfl).nonempty_congr, apply h, apply presieve_of_covering.mem_grothendieck_topology }, { intros h Y S, rw ← sieve.generate_sieve S, intro hS, rw ← (is_limit_opens_le_equiv_generate₂ F S hS).nonempty_congr, apply h }, end end end presheaf end Top
ba98f49ff75f86986a3830d19916239b38c3d53e
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/wilson.lean
3a6463cd1b53d9e62449b53a7bd50ec2de8627d9
[ "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
1,675
lean
/- Copyright (c) 2022 John Nicol. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: John Nicol -/ import number_theory.legendre_symbol.gauss_eisenstein_lemmas /-! # Wilson's theorem. This file contains a proof of Wilson's theorem. The heavy lifting is mostly done by the previous `wilsons_lemma`, but here we also prove the other logical direction. This could be generalized to similar results about finite abelian groups. ## References * [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) ## TODO * Move `wilsons_lemma` into this file, and give it a descriptive name. -/ open_locale nat namespace nat variable {n : ℕ} /-- For `n ≠ 1`, `(n-1)!` is congruent to `-1` modulo `n` only if n is prime. --/ lemma prime_of_fac_equiv_neg_one (h : ((n - 1)! : zmod n) = -1) (h1 : n ≠ 1) : prime n := begin rcases eq_or_ne n 0 with rfl | h0, { norm_num at h }, replace h1 : 1 < n := n.two_le_iff.mpr ⟨h0, h1⟩, by_contradiction h2, obtain ⟨m, hm1, hm2 : 1 < m, hm3⟩ := exists_dvd_of_not_prime2 h1 h2, have hm : m ∣ (n - 1)! := nat.dvd_factorial (pos_of_gt hm2) (le_pred_of_lt hm3), refine hm2.ne' (nat.dvd_one.mp ((nat.dvd_add_right hm).mp (hm1.trans _))), rw [←zmod.nat_coe_zmod_eq_zero_iff_dvd, cast_add, cast_one, h, add_left_neg], end /-- **Wilson's Theorem**: For `n ≠ 1`, `(n-1)!` is congruent to `-1` modulo `n` iff n is prime. --/ theorem prime_iff_fac_equiv_neg_one (h : n ≠ 1) : prime n ↔ ((n - 1)! : zmod n) = -1 := begin refine ⟨λ h1, _, λ h2, prime_of_fac_equiv_neg_one h2 h⟩, haveI := fact.mk h1, exact zmod.wilsons_lemma n, end end nat
ef356173911e05dc32b8180b95f6661cf091bf97
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/data/fin.lean
34c158b28928c687873b5521cb1ded55bfdafafa
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
50,584
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast import tactic.localized import order.rel_iso /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`; * `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add i h` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `insert_nth` : insert an element to a tuple at a given position. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universes u v open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 lemma fact.succ.pos {n} : fact (0 < succ n) := zero_lt_succ _ lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) := nat.zero_lt_bit0 $ ne_of_gt h lemma fact.bit1.pos {n} : fact (0 < bit1 n) := nat.zero_lt_bit1 _ lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) := pow_pos h _ localized "attribute [instance] fact.succ.pos" in fin_fact localized "attribute [instance] fact.bit0.pos" in fin_fact localized "attribute [instance] fact.bit1.pos" in fin_fact localized "attribute [instance] fact.pow.pos" in fin_fact namespace fin variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩ lemma is_lt (i : fin n) : (i : ℕ) < n := i.2 /-- convert a `ℕ` to `fin n`, provided `n` is positive -/ def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h⟩ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := ⟨subtype.mk.inj, λ h, by subst h⟩ lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.is_lt⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl attribute [simp] val_zero @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl @[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) : (⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)).val) = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Type*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { induction h, simp [ext_iff] } instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ instance {n : ℕ} : linear_order (fin n) := { le := (≤), lt := (<), decidable_le := fin.decidable_le, decidable_lt := fin.decidable_lt, decidable_eq := fin.decidable_eq _, ..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ @[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt instance : bounded_lattice (fin (n + 1)) := { top := last n, le_top := le_last, bot := 0, bot_le := zero_le, .. fin.linear_order, .. lattice_of_linear_order } /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h @[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := (succ_embedding n).apply_le_apply @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := (succ_embedding n).apply_lt_apply lemma succ_injective (n : ℕ) : injective (@fin.succ n) := (succ_embedding n).injective @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := (succ_injective n).eq_iff lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq @[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := begin cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } end lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel] @[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha ≤ b.pred hb ↔ a ≤ b := by rw [←succ_le_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha < b.pred hb ↔ a < b := by rw [←succ_lt_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The inclusion map `fin n → ℕ` is a relation embedding. -/ def coe_embedding (n) : (fin n) ↪o ℕ := ⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The ordering on `fin n` is a well order. -/ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (coe_embedding n).is_well_order /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ @[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) : fin n ↪o fin m := order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h @[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n ≃o fin m := { to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl @[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} : cast h' (cast h i) = cast (eq.trans h h') i := rfl @[simp] lemma cast_refl {i : fin n} : cast rfl i = i := by { ext, refl } /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ le_add_right n m @[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n ↪o fin (n + 1) := cast_add 1 @[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self] lemma succ_above_aux (p : fin (n + 1)) : strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) := (cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono (λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).apply_lt_apply.2 hij) hj) (λ i, (cast_succ_lt_succ i).le) /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono _ p.succ_above_aux /-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩ @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl /-- `add_nat i h` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat (m) : fin n ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _ @[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl /-- `nat_add i h` adds `n` to `i` "on the left". -/ def nat_add (n) {m} : fin m ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _ @[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/ @[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i := begin rcases i with ⟨i, hi⟩, rw [subtype.coe_mk], induction i using nat.strong_induction_on with i h, refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _), { have := e.symm.apply_lt_apply.2 (mk_lt_of_lt_coe hj), rw e.symm_apply_apply at this, convert this, simpa using h _ this (e.symm _).is_lt }, { rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.apply_lt_apply] } end section variables {α : Type*} [preorder α] open set instance order_iso_subsingleton : subsingleton (fin n ≃o α) := ⟨λ e e', by { ext i, rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff, coe_order_iso_apply] }⟩ instance order_iso_subsingleton' : subsingleton (α ≃o fin n) := order_iso.symm_injective.subsingleton instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _ /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g) (h : range f = range g) : f = g := have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g, from subsingleton.elim _ _, congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this) /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g := rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h end @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := (cast_succ : fin n ↪o _).injective lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := (cast_succ_injective n).eq_iff lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos (i : fin (n + 1)) (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos @[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 := begin split, { cases n; intro h, { refl }, { have := zero_ne_one, contradiction } }, { rintro rfl, refl } end @[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 := by rw [eq_comm, zero_eq_one_iff] lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by { simp [fin.ext_iff], } @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin ext, exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel], exact add_lt_add_right h 1, end lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding := by { ext, apply zero_add } /-- `min n m` as an element of `fin (m + 1)`. -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above_below, cast_succ_lt_last] } lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ := by rw succ_above_last /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by simp [succ_above, h.not_lt] /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) : p.succ_above i < p ↔ i.cast_succ < p := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { exact H }, { rw succ_above_above _ _ H at h, exact lt_trans (cast_succ_lt_succ i) h } }, { intro h, rw succ_above_below _ _ h, exact h } end /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { rw succ_above_below _ _ H at h, exact le_of_lt h }, { exact H } }, { intro h, rw succ_above_above _ _ h, exact lt_of_le_of_lt h (cast_succ_lt_succ i) }, end /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos _ h }, { simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ }, end /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := (succ_above x).injective /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := succ_above_right_injective.eq_iff /-- Embedding a `fin (n + 1)` into `fin n` and embedding it back around the same hole gives the starting `fin (n + 1)` -/ @[simp] lemma succ_above_pred_above (p i : fin (n + 1)) (h : i ≠ p) : p.succ_above (p.pred_above i h) = i := begin rw pred_above, cases lt_or_le i p with H H, { simp only [succ_above_below, cast_succ_cast_lt, H, dif_pos]}, { rw le_iff_coe_le_coe at H, rw succ_above_above, { simp only [le_iff_coe_le_coe, H, not_lt, dif_neg, succ_pred] }, { simp only [le_iff_coe_le_coe, H, coe_pred, not_lt, dif_neg, coe_cast_succ], exact le_pred_of_lt (lt_of_le_of_ne H (vne_of_ne h.symm)) } } end /-- Embedding a `fin n` into `fin (n + 1)` and embedding it back around the same hole gives the starting `fin n` -/ @[simp] lemma pred_above_succ_above (p : fin (n + 1)) (i : fin n) : p.pred_above (p.succ_above i) (succ_above_ne _ _) = i := by rw [← succ_above_right_inj, succ_above_pred_above] @[simp] theorem pred_above_zero {i : fin (n + 1)} (hi : i ≠ 0) : pred_above 0 i hi = i.pred hi := rfl lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) := ⟨λ h, ⟨h _, λ j, h _⟩, λ h j, if hj : j = i then (hj.symm ▸ h.1) else (i.succ_above_pred_above j hj ▸ h.2 _)⟩ /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ x y, begin contrapose!, intros H h, have key : succ_above x (y.pred_above x H) = succ_above y (y.pred_above x H), by rw h, rw [succ_above_pred_above] at key, exact absurd key (succ_above_ne x _) end /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := succ_above_left_injective.eq_iff /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] } end section rec /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ @[elab_as_eliminator] def induction {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : Π (i : fin (n + 1)), C i := begin rintro ⟨i, hi⟩, induction i with i IH, { rwa [fin.mk_zero] }, { refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _, exact IH (lt_of_succ_lt hi) } end /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ @[elab_as_eliminator] def induction_on (i : fin (n + 1)) {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i := induction h0 hs i /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i := induction H0 (λ i _, Hs i) @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl @[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) : @fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ instance tuple0_unique (α : fin 0 → Type u) : unique (Π i : fin 0, α i) := { default := fin_zero_elim, uniq := λ x, funext fin_zero_elim } @[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g := fin_zero_elim variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail] lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (λ i, order_dual (α i)) _ x q p /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (nat.sub_lt_left_iff_lt_add (le_of_not_lt h)).2 (ho ▸ i.property)⟩ end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_eq_mp (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_eq_mp C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section insert_nth variables {α : fin (n+1) → Type u} {β : Type v} /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. -/ def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := if h : j = i then _root_.cast (congr_arg α h.symm) x else _root_.cast (congr_arg α $ succ_above_pred_above i _ h) (p $ i.pred_above j h) @[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) : insert_nth i x p i = x := by simp [insert_nth] @[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) (j : fin n) : insert_nth i x p (i.succ_above j) = p j := begin simp only [insert_nth, dif_neg (succ_above_ne _ _)], refine eq_of_heq ((cast_heq _ _).trans _), rw [pred_above_succ_above] end @[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) : insert_nth i x p ∘ i.succ_above = p := funext $ insert_nth_apply_succ_above i x p lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := by simp [funext_iff, forall_iff_succ_above i, eq_comm] lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := eq_comm.trans insert_nth_eq_iff lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) : insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, convert (cons_succ _ _ _).symm end @[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) 0 x p = cons x p := by simp [insert_nth_zero] lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) : insert_nth (last n) x p = snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, apply eq_of_heq, transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ, { rw [snoc_cast_succ], exact (cast_heq _ _).symm }, { apply congr_arg_heq, rw [succ_above_last] } end @[simp] lemma insert_nth_last' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) (last n) x p = snoc p x := by simp [insert_nth_last] variables [Π i, preorder (α i)] lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) := by simp [pi.le_def, forall_iff_succ_above i] lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p := by simp [pi.le_def, forall_iff_succ_above i] open set lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q₁ q₂ : Π j, α j} : i.insert_nth x p ∈ Icc q₁ q₂ ↔ x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm] lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∈ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and] lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∉ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq] end insert_nth section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) : ((n : fin (succ m)) : ℕ) = n % succ m := by rw [← of_nat_eq_coe]; refl @[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] : (@fin.of_nat' _ I n : ℕ) = n % m := rfl end fin
b177dbd15e56cada5964363d46fc67d57c4ba876
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/fintype/basic.lean
2b04ef2da74dd346b902a1f7e3bafa675b08af72
[ "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
51,877
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import tactic.wlog import data.finset.powerset import data.finset.lattice import data.finset.pi import data.array.lemmas import order.well_founded open_locale nat universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α := by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty] lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty := univ_nonempty_iff.2 ‹_› lemma univ_eq_empty : (univ : finset α) = ∅ ↔ ¬nonempty α := by rw [← univ_nonempty_iff, nonempty_iff_ne_empty, ne.def, not_not] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : boolean_algebra (finset α) := { compl := λ s, univ \ s, sdiff_eq := λ s t, by simp [ext_iff], inf_compl_le_bot := λ s x hx, by simpa using hx, top_le_sup_compl := λ s x hx, by simp, ..finset.distrib_lattice, ..finset.semilattice_inf_bot, ..finset.order_top, ..finset.has_sdiff } lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl @[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s := by simp [compl_eq_univ_sdiff] @[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ := set.ext $ λ x, mem_compl theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ /-- Given a predicate that can be represented by a finset, the subtype associated to the predicate is a fintype. -/ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by { rw ← subtype_card s H, congr } /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ /-- Given an injective function to a fintype, the domain is also a fintype. This is noncomputable because injectivity alone cannot be used to construct preimages. -/ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ /-- Subsingleton types are fintypes (with zero or one terms). -/ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) : s = univ := eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ] lemma finset.card_le_univ [fintype α] (s : finset α) : s.card ≤ fintype.card α := card_le_of_subset (subset_univ s) lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) : sᶜ.card = fintype.card α - s.card := finset.card_univ_diff s instance (n : ℕ) : fintype (fin n) := ⟨finset.fin_range n, finset.mem_fin_range⟩ lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n := ⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩ /-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/ lemma fin.univ_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end /-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Embed `fin n` into `fin (n + 1)` by inserting around a specified pivot `p : fin (n + 1)` into the `univ` -/ lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) : (univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) := begin rcases lt_or_eq_of_le (fin.le_last p) with hl|rfl, { ext m, simp only [finset.mem_univ, finset.mem_insert, true_iff, finset.mem_image, exists_prop], refine or_iff_not_imp_left.mpr _, { intro h, use p.pred_above m h, simp only [eq_self_iff_true, fin.succ_above_descend, and_self] } }, { rw fin.succ_above_last, exact fin.univ_cast_succ n } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl /-- Given a finset on `α`, lift it to being a finset on `option α` using `option.some` and then insert `option.none`. -/ def finset.insert_none (s : finset α) : finset (option α) := ⟨none ::ₘ s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] : (univ : finset α).product (univ : finset β) = univ := rfl @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ /-- Given that `α × β` is a fintype, `α` is also a fintype. -/ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ /-- Given that `α × β` is a fintype, `β` is also a fintype. -/ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) namespace fintype variables [fintype α] [fintype β] lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β := finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) /-- The pigeonhole principle for finitely many pigeons and pigeonholes. This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`. -/ lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) : ∃ x y, x ≠ y ∧ f x = f y := let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x)) in ⟨x, y, h⟩ lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff : card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [card_congr e]⟩ /-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/ def card_eq_zero_equiv_equiv_pempty : card α = 0 ≃ (α ≃ pempty.{v+1}) := { to_fun := λ h, { to_fun := λ a, false.elim (card_eq_zero_iff.1 h a), inv_fun := λ a, pempty.elim a, left_inv := λ a, false.elim (card_eq_zero_iff.1 h a), right_inv := λ a, pempty.elim a, }, inv_fun := λ e, by { simp only [←of_equiv_card e], convert card_pempty, }, left_inv := λ h, rfl, right_inv := λ e, by { ext x, cases e x, } } lemma card_pos_iff : 0 < card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩ lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α := iff.trans card_le_one_iff subsingleton_iff.symm lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α := begin classical, rw ← not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton] end lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f := by simp [bijective, injective_iff_surjective] lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma nonempty_equiv_of_card_eq (h : card α = card β) : nonempty (α ≃ β) := begin obtain ⟨m, ⟨f⟩⟩ := exists_equiv_fin α, obtain ⟨n, ⟨g⟩⟩ := exists_equiv_fin β, suffices : m = n, { subst this, exact ⟨f.trans g.symm⟩ }, calc m = card (fin m) : (card_fin m).symm ... = card α : card_congr f.symm ... = card β : h ... = card (fin n) : card_congr g ... = n : card_fin n end lemma bijective_iff_injective_and_card (f : α → β) : bijective f ↔ injective f ∧ card α = card β := begin split, { intro h, exact ⟨h.1, card_congr (equiv.of_bijective f h)⟩ }, { rintro ⟨hf, h⟩, refine ⟨hf, _⟩, obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h, rwa ← injective_iff_surjective_of_equiv e } end lemma bijective_iff_surjective_and_card (f : α → β) : bijective f ↔ surjective f ∧ card α = card β := begin split, { intro h, exact ⟨h.2, card_congr (equiv.of_bijective f h)⟩, }, { rintro ⟨hf, h⟩, refine ⟨_, hf⟩, obtain ⟨e⟩ : nonempty (α ≃ β) := nonempty_equiv_of_card_eq h, rwa injective_iff_surjective_of_equiv e } end end fintype lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma finset.card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := fintype.subtype (univ.filter p) (by simp) /-- A set on a fintype, when coerced to a type, is a fintype. -/ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := subtype.fintype (λ x, x ∈ s) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype variables [decidable_eq α] [fintype α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_empty [fintype α] : (∅ : set α).to_finset = ∅ := by { ext, simp only [set.mem_empty_eq, set.mem_to_finset, not_mem_empty] } theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, not_forall.2 ⟨x, by simp [hx]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ @[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ := by { ext, simp } lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp lemma card_lt_card_of_injective_of_not_mem {α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β := begin classical, calc fintype.card α = (univ : finset α).card : rfl ... = (image f univ).card : (card_image_of_injective univ h).symm ... < (insert b (image f univ)).card : card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w)) ... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _) ... = fintype.card β : rfl end /-- An auxiliary function for `quotient.fin_choice`. Given a collection of setoids indexed by a type `ι`, a (finite) list `l` of indices, and a function that for each `i ∈ l` gives a term of the corresponding quotient type, then there is a corresponding term in the quotient of the product of the setoids indexed by `l`. -/ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end /-- Given a collection of setoids indexed by a fintype `ι` and a function that for each `i : ι` gives a term of the corresponding quotient type, then there is corresponding term in the quotient of the product of the setoids. -/ def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, { have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { by_cases hffa : f (f a) = a, { exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) }, { apply this, simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq], split_ifs; cc } }, { rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul] } } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin apply symm, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] (p : α → Prop) [decidable_pred p] /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ /-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of `α` satisfying `p` this unique element, as an element of `α`. -/ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] variables [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype /-- A type is said to be infinite if it has no fintype instance. -/ class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) := begin obtain ⟨c, hcs : c ∈ s⟩ := h, have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _, obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩, exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩, end lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) : ∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) := @finset.exists_minimal (order_dual α) _ s h namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance (α : Type*) [H : infinite α] : nontrivial α := ⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in ⟨y, x, by simpa only [mem_singleton] using hy⟩⟩ lemma nonempty (α : Type*) [infinite α] : nonempty α := by apply_instance lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end /-- Embedding of `ℕ` into an infinite type. -/ noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) : ∃ s : finset α, s.card = n := ⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H /-- The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the same pigeonhole. See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`. -/ lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) : ∃ x y : α, x ≠ y ∧ f x = f y := begin classical, by_contra hf, push_neg at hf, apply not_injective_infinite_fintype f, intros x y, contrapose, apply hf, end /-- The strong pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are infinitely many pigeons in finitely many pigeonholes, then there is a pigeonhole with infinitely many pigeons. See also: `fintype.exists_ne_map_eq_of_infinite` -/ lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) : ∃ y : β, infinite (f ⁻¹' {y}) := begin classical, by_contra hf, push_neg at hf, haveI h' : ∀ (y : β), fintype (f ⁻¹' {y}) := begin intro y, specialize hf y, rw [←not_nonempty_fintype, not_not] at hf, exact classical.choice hf, end, let key : fintype α := { elems := univ.bind (λ (y : β), (f ⁻¹' {y}).to_finset), complete := by simp }, exact infinite.not_fintype key, end lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc
59d5e7be1b1314174968d8fa83ab486c5c56adb5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Hashable.lean
0b4e65bf067605685e95387ae303f854a1747e3c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,561
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.UInt.Basic import Init.Data.String universe u instance : Hashable Nat where hash n := UInt64.ofNat n instance : Hashable String.Pos where hash p := UInt64.ofNat p.byteIdx instance [Hashable α] [Hashable β] : Hashable (α × β) where hash | (a, b) => mixHash (hash a) (hash b) instance : Hashable Bool where hash | true => 11 | false => 13 instance [Hashable α] : Hashable (Option α) where hash | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (List α) where hash as := as.foldl (fun r a => mixHash r (hash a)) 7 instance [Hashable α] : Hashable (Array α) where hash as := as.foldl (fun r a => mixHash r (hash a)) 7 instance : Hashable UInt8 where hash n := n.toUInt64 instance : Hashable UInt16 where hash n := n.toUInt64 instance : Hashable UInt32 where hash n := n.toUInt64 instance : Hashable UInt64 where hash n := n instance : Hashable USize where hash n := n.toUInt64 instance : Hashable (Fin n) where hash v := v.val.toUInt64 instance : Hashable Int where hash | Int.ofNat n => UInt64.ofNat (2 * n) | Int.negSucc n => UInt64.ofNat (2 * n + 1) instance (P : Prop) : Hashable P where hash _ := 0 /-- An opaque (low-level) hash operation used to implement hashing for pointers. -/ @[always_inline, inline] def hash64 (u : UInt64) : UInt64 := mixHash u 11
b9ef8adbdc48c00d048023e836911c626772a2ea
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Elab/Tactic/Basic.lean
8b3b9fc7d025358f9ca2a7bec07da57a37d9a37d
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,028
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.CollectMVars import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean.Elab open Meta def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) m!"\n\n" def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := do throwError! "unsolved goals\n{goalsToMessageData goals}" namespace Tactic structure Context where main : MVarId structure State where goals : List MVarId deriving Inhabited structure BacktrackableState where env : Environment mctx : MetavarContext term : Term.State goals : List MVarId abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit def saveBacktrackableState : TacticM BacktrackableState := do pure { env := (← getEnv), mctx := (← getMCtx), term := (← getThe Term.State), goals := (← get).goals } def BacktrackableState.restore (b : BacktrackableState) : TacticM Unit := do setEnv b.env setMCtx b.mctx let msgLog ← Term.getMessageLog -- we do not backtrack the message log set b.term Term.setMessageLog msgLog modify fun s => { s with goals := b.goals } @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveBacktrackableState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM where throw := throw tryCatch := Tactic.tryCatch @[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do try x catch _ => y instance {α} : OrElse (TacticM α) where orElse := Tactic.orElse structure SavedState where core : Core.State meta : Meta.State term : Term.State tactic : State deriving Inhabited def saveAllState : TacticM SavedState := do pure { core := (← getThe Core.State), meta := (← getThe Meta.State), term := (← getThe Term.State), tactic := (← get) } def SavedState.restore (s : SavedState) : TacticM Unit := do set s.core; set s.meta; set s.term; set s.tactic @[inline] def liftTermElabM {α} (x : TermElabM α) : TacticM α := liftM x @[inline] def liftMetaM {α} (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM x def ensureHasType (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType expectedType? e def reportUnsolvedGoals (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals goals protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List Tactic) : TacticM Unit := do let rec loop : List Tactic → TacticM Unit | [] => throwErrorAt! stx "unexpected syntax {indentD stx}" | evalFn::evalFns => do try evalFn stx catch | ex@(Exception.error _ _) => match evalFns with | [] => throw ex | evalFns => s.restore; loop evalFns | ex@(Exception.internal id _) => if id == unsupportedSyntaxExceptionId then s.restore; loop evalFns else throw ex loop tactics /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x mutual partial def expandTacticMacroFns (stx : Syntax) (macros : List Macro) : TacticM Unit := let rec loop : List Macro → TacticM Unit | [] => throwErrorAt! stx "tactic '{stx.getKind}' has not been implemented" | m::ms => do let scp ← getCurrMacroScope try let stx' ← adaptMacro m stx evalTactic stx' catch ex => if ms.isEmpty then throw ex loop ms loop macros partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do let k := stx.getKind let table := (macroAttribute.ext.getState (← getEnv)).table let macroFns := (table.find? k).getD [] expandTacticMacroFns stx macroFns partial def evalTactic : Syntax → TacticM Unit | stx => withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => 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 fun _ => stx let env ← getEnv let s ← saveAllState let table := (tacticElabAttribute.ext.getState env).table let k := stx.getKind match table.find? k with | some evalFns => evalTacticUsing s stx evalFns | none => expandTacticMacro stx | _ => throwError "unexpected command" end /-- 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' def getGoals : TacticM (List MVarId) := do pure (← get).goals def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := gs } def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := s.goals ++ gs } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals def getMainGoal : TacticM (MVarId × List MVarId) := do let (g::gs) ← getUnsolvedGoals | throwError "no goals to be solved"; pure (g, gs) def getMainTag : TacticM Name := do let (g, _) ← getMainGoal pure (← getMVarDecl g).userName 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}" def withMainMVarContext {α} (x : TacticM α) : TacticM α := do let (mvarId, _) ← getMainGoal withMVarContext mvarId x @[inline] def liftMetaMAtMain {α} (x : MVarId → MetaM α) : TacticM α := do let (g, _) ← getMainGoal withMVarContext g $ liftMetaM $ x g @[inline] def liftMetaTacticAux {α} (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do let (g, gs) ← getMainGoal withMVarContext g do let (a, gs') ← tactic g setGoals (gs' ++ gs) pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) def done : TacticM Unit := do let gs ← getUnsolvedGoals; unless gs.isEmpty do reportUnsolvedGoals gs @[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ => done def focus {α} (tactic : TacticM α) : TacticM α := do let (g, gs) ← getMainGoal setGoals [g] let a ← tactic let gs' ← getGoals setGoals (gs' ++ gs) 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 : Syntax) : TacticM Unit := do let (mvarId, rest) ← getMainGoal try evalTactic tac done catch ex => logException ex let mvarType ← inferType (mkMVar mvarId) assignExprMVar mvarId (← mkSorry mvarType (synthetic := true)) setGoals rest def try? {α} (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none -- TODO: rename? def «try» {α} (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 => 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.renameMVar g parentTag else mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx @[builtinTactic seq1] def evalSeq1 : Tactic := fun stx => stx[0].getSepArgs.forM evalTactic @[builtinTactic paren] def evalParen : Tactic := fun stx => evalTactic stx[1] @[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx => stx[0].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => withRef stx[2] $ focusAndDone $ stx[1].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => focus $ evalTactic stx[1] @[builtinTactic Parser.Tactic.allGoals] def evalAllGoals : Tactic := fun stx => do let gs ← getUnsolvedGoals let mut gsNew := [] for g in gs do setGoals [g] evalTactic stx[1] gsNew := gsNew ++ (← getUnsolvedGoals) setGoals gsNew @[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx => evalTactic stx[0] partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit := if h : i < tactics.size then let tactic := tactics.get ⟨i, h⟩ catchInternalId unsupportedSyntaxExceptionId (evalTactic tactic) (fun _ => evalChoiceAux tactics (i+1)) else throwUnsupportedSyntax @[builtinTactic choice] def evalChoice : Tactic := fun stx => evalChoiceAux stx.getArgs 0 @[builtinTactic skip] def evalSkip : Tactic := fun stx => pure () @[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => do let tactic := stx[1] if (← try evalTactic tactic; pure true catch _ => pure false) then throwError "tactic succeeded" @[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do let gs ← getUnsolvedGoals logInfo (goalsToMessageData gs) @[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx => liftMetaTactic fun mvarId => do Meta.assumption mvarId; pure [] private def introStep (n : Name) : TacticM Unit := liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.intro mvarId n pure [mvarId] @[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => match stx with | `(tactic| intro) => liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.intro1 mvarId; pure [mvarId] | `(tactic| intro $h:ident) => introStep h.getId | `(tactic| intro _) => introStep `_ | `(tactic| intro $pat:term) => do let stxNew ← `(tactic| intro h; match h with | $pat:term => _; clear h) withMacroExpansion stx stxNew $ evalTactic stxNew | `(tactic| intro $hs:term*) => do let h0 := hs.get! 0 let hs := hs.extract 1 hs.size let stxNew ← `(tactic| intro $h0:term; intro $hs:term*) withMacroExpansion stx stxNew $ evalTactic stxNew | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do let matchAlts := stx[1] let stxNew ← liftMacroM $ Term.expandMatchAltsIntoMatchTactic stx matchAlts withMacroExpansion stx stxNew $ evalTactic stxNew private def getIntrosSize : Expr → Nat | Expr.forallE _ _ b _ => getIntrosSize b + 1 | Expr.letE _ _ _ b _ => getIntrosSize b + 1 | _ => 0 /- Recall that `ident' := ident <|> Term.hole` -/ def getNameOfIdent' (id : Syntax) : Name := if id.isIdent then id.getId else `_ @[builtinTactic «intros»] def evalIntros : Tactic := fun stx => match stx with | `(tactic| intros) => liftMetaTactic fun mvarId => do let type ← Meta.getMVarType mvarId let type ← instantiateMVars type let n := getIntrosSize type let (_, mvarId) ← Meta.introN mvarId n pure [mvarId] | `(tactic| intros $ids*) => liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.introN mvarId ids.size (ids.map getNameOfIdent').toList pure [mvarId] | _ => throwUnsupportedSyntax def getFVarId (id : Syntax) : TacticM FVarId := withRef id do let fvar? ← liftTermElabM $ Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError! "unknown variable '{id.getId}'" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainMVarContext $ ids.mapM getFVarId @[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx => match stx with | `(tactic| revert $hs*) => do let (g, gs) ← getMainGoal let fvarIds ← getFVarIds hs let (_, g) ← Meta.revert g fvarIds setGoals (g :: gs) | _ => throwUnsupportedSyntax /- Sort free variables using an order `x < y` iff `x` was defined after `y` -/ private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) := withMainMVarContext do let lctx ← getLCtx pure $ fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index > d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁ fvarId₂ @[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx => match stx with | `(tactic| clear $hs*) => do let fvarIds ← getFVarIds hs let fvarIds ← sortFVarIds fvarIds for fvarId in fvarIds do let (g, gs) ← getMainGoal withMVarContext g do let g ← clear g fvarId setGoals (g :: gs) | _ => throwUnsupportedSyntax def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do for h in hs do let (g, gs) ← getMainGoal; withMVarContext g do let fvarId ← getFVarId h let g ← tac g fvarId setGoals (g :: gs) @[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx => match stx with | `(tactic| subst $hs*) => forEachVar hs Meta.subst | _ => throwUnsupportedSyntax /-- First method searches for a metavariable `g` s.t. `tag` is a suffix of its name. If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/ private def findTag? (gs : List MVarId) (tag : Name) : TacticM (Option MVarId) := do let g? ← gs.findM? (fun g => do pure $ tag.isSuffixOf (← getMVarDecl g).userName); match g? with | some g => pure g | none => gs.findM? (fun g => do pure $ tag.isPrefixOf (← getMVarDecl g).userName) @[builtinTactic «case»] def evalCase : Tactic := fun stx => match stx with | `(tactic| case $tag => $tac:tacticSeq) => do let tag := tag.getId let gs ← getUnsolvedGoals let some g ← findTag? gs tag | throwError "tag not found" let gs := gs.erase g setGoals [g] let savedTag ← liftM $ getMVarTag g liftM $ setMVarTag g Name.anonymous try closeUsingOrAdmit tac finally liftM $ setMVarTag g savedTag done setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «first»] partial def evalFirst : Tactic := fun stx => do let tacs := stx[2].getSepArgs if tacs.isEmpty then throwUnsupportedSyntax loop tacs 0 where loop (tacs : Array Syntax) (i : Nat) := if i == tacs.size - 1 then evalTactic tacs[i] else evalTactic tacs[i] <|> loop tacs (i+1) builtin_initialize registerTraceClass `Elab.tactic @[inline] def TacticM.run {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] def TacticM.run' {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.run ctx s end Lean.Elab.Tactic
34e6d904e2fe9c5985b20504444f963984317223
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/cardinal/ordinal.lean
655c3a267b92c2b59a6694c64a5a93894943b8ac
[ "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
49,719
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import data.finsupp.multiset import order.bounded import set_theory.ordinal.principal import tactic.linarith /-! # Cardinals and ordinals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions * The function `cardinal.aleph'` gives the cardinals listed by their ordinal index, and is the inverse of `cardinal.aleph_idx`. `aleph' n = n`, `aleph' ω = ℵ₀`, `aleph' (ω + 1) = succ ℵ₀`, etc. It is an order isomorphism between ordinals and cardinals. * The function `cardinal.aleph` gives the infinite cardinals listed by their ordinal index. `aleph 0 = ℵ₀`, `aleph 1 = succ ℵ₀` is the first uncountable cardinal, and so on. * The function `cardinal.beth` enumerates the Beth cardinals. `beth 0 = ℵ₀`, `beth (succ o) = 2 ^ beth o`, and for a limit ordinal `o`, `beth o` is the supremum of `beth a` for `a < o`. ## Main Statements * `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp` able to prove inequalities about numeral cardinals. ## Tags cardinal arithmetic (for infinite cardinals) -/ noncomputable theory open function cardinal set equiv order open_locale classical cardinal ordinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : ℵ₀ ≤ c) : (ord c).is_limit := begin refine ⟨λ h, aleph_0_ne_zero _, λ a, lt_imp_lt_of_le_imp_le (λ h, _)⟩, { rw [←ordinal.le_zero, ord_le] at h, simpa only [card_zero, nonpos_iff_eq_zero] using co.trans h }, { rw ord_le at h ⊢, rwa [←@add_one_of_aleph_0_le (card a), ←card_succ], rw [←ord_le, ←le_succ_of_is_limit, ord_le], { exact co.trans h }, { rw ord_aleph_0, exact omega_is_limit } } end /-! ### Aleph cardinals -/ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ℵ₀ = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := ⨆ a, inv_fun aleph_idx (ordinal.typein r a), apply (lt_succ s).not_le, have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_csupr (cardinal.bdd_above_range.{u u} (λ a : α, inv_fun aleph_idx (ordinal.typein r a))) (ordinal.enum r _ (h (succ s))) end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : #cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = succ ℵ₀`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = succ ℵ₀`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by { rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le], apply ordinal.zero_le } @[simp] theorem aleph'_succ {o : ordinal} : aleph' (succ o) = succ (aleph' o) := begin apply (succ_le_of_lt $ aleph'_lt.2 $ lt_succ o).antisymm' (cardinal.aleph_idx_le.1 $ _), rw [aleph_idx_aleph', succ_le_iff, ← aleph'_lt, aleph'_aleph_idx], apply lt_succ end @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', (aleph'_le.2 $ h'.le).trans h, λ h, begin rw [←aleph'_aleph_idx c, aleph'_le, limit_le l], intros x h', rw [←aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ theorem aleph'_limit {o : ordinal} (ho : o.is_limit) : aleph' o = ⨆ a : Iio o, aleph' a := begin refine le_antisymm _ (csupr_le' (λ i, aleph'_le.2 (le_of_lt i.2))), rw aleph'_le_of_limit ho, exact λ a ha, le_csupr (bdd_above_of_small _) (⟨a, ha⟩ : Iio o) end @[simp] theorem aleph'_omega : aleph' ω = ℵ₀ := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, lt_omega, exists_imp_distrib, aleph_0_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ℵ₀`, `aleph 1 = succ ℵ₀` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ω + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem max_aleph_eq (o₁ o₂ : ordinal) : max (aleph o₁) (aleph o₂) = aleph (max o₁ o₂) := begin cases le_total (aleph o₁) (aleph o₂) with h h, { rw [max_eq_right h, max_eq_right (aleph_le.1 h)] }, { rw [max_eq_left h, max_eq_left (aleph_le.1 h)] } end @[simp] theorem aleph_succ {o : ordinal} : aleph (succ o) = succ (aleph o) := by rw [aleph, add_succ, aleph'_succ, aleph] @[simp] theorem aleph_zero : aleph 0 = ℵ₀ := by rw [aleph, add_zero, aleph'_omega] theorem aleph_limit {o : ordinal} (ho : o.is_limit) : aleph o = ⨆ a : Iio o, aleph a := begin apply le_antisymm _ (csupr_le' _), { rw [aleph, aleph'_limit (ho.add _)], refine csupr_mono' (bdd_above_of_small _) _, rintro ⟨i, hi⟩, cases lt_or_le i ω, { rcases lt_omega.1 h with ⟨n, rfl⟩, use ⟨0, ho.pos⟩, simpa using (nat_lt_aleph_0 n).le }, { exact ⟨⟨_, (sub_lt_of_le h).2 hi⟩, aleph'_le.2 (le_add_sub _ _)⟩ } }, { exact λ i, aleph_le.2 (le_of_lt i.2) } end theorem aleph_0_le_aleph' {o : ordinal} : ℵ₀ ≤ aleph' o ↔ ω ≤ o := by rw [← aleph'_omega, aleph'_le] theorem aleph_0_le_aleph (o : ordinal) : ℵ₀ ≤ aleph o := by { rw [aleph, aleph_0_le_aleph'], apply ordinal.le_add_right } theorem aleph'_pos {o : ordinal} (ho : 0 < o) : 0 < aleph' o := by rwa [←aleph'_zero, aleph'_lt] theorem aleph_pos (o : ordinal) : 0 < aleph o := aleph_0_pos.trans_le (aleph_0_le_aleph o) @[simp] theorem aleph_to_nat (o : ordinal) : (aleph o).to_nat = 0 := to_nat_apply_of_aleph_0_le $ aleph_0_le_aleph o @[simp] theorem aleph_to_part_enat (o : ordinal) : (aleph o).to_part_enat = ⊤ := to_part_enat_apply_of_aleph_0_le $ aleph_0_le_aleph o instance nonempty_out_aleph (o : ordinal) : nonempty (aleph o).ord.out.α := begin rw [out_nonempty_iff_ne_zero, ←ord_zero], exact λ h, (ord_injective h).not_gt (aleph_pos o) end theorem ord_aleph_is_limit (o : ordinal) : (aleph o).ord.is_limit := ord_is_limit $ aleph_0_le_aleph _ instance (o : ordinal) : no_max_order (aleph o).ord.out.α := out_no_max_of_succ_lt (ord_aleph_is_limit o).2 theorem exists_aleph {c : cardinal} : ℵ₀ ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ω, by { rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx], rwa [← aleph_0_le_aleph', aleph'_aleph_idx] }⟩, λ ⟨o, e⟩, e.symm ▸ aleph_0_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ lt_succ o, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ω theorem succ_aleph_0 : succ ℵ₀ = aleph 1 := by rw [←aleph_zero, ←aleph_succ, ordinal.succ_zero] lemma aleph_0_lt_aleph_one : ℵ₀ < aleph 1 := by { rw ←succ_aleph_0, apply lt_succ } lemma countable_iff_lt_aleph_one {α : Type*} (s : set α) : s.countable ↔ #s < aleph 1 := by rw [←succ_aleph_0, lt_succ_iff, le_aleph_0_iff_set_countable] /-- Ordinals that are cardinals are unbounded. -/ theorem ord_card_unbounded : unbounded (<) {b : ordinal | b.card.ord = b} := unbounded_lt_iff.2 $ λ a, ⟨_, ⟨(by { dsimp, rw card_ord }), (lt_ord_succ_card a).le⟩⟩ theorem eq_aleph'_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) : ∃ a, (aleph' a).ord = o := ⟨cardinal.aleph_idx.rel_iso o.card, by simpa using ho⟩ /-- `ord ∘ aleph'` enumerates the ordinals that are cardinals. -/ theorem ord_aleph'_eq_enum_card : ord ∘ aleph' = enum_ord {b : ordinal | b.card.ord = b} := begin rw [←eq_enum_ord _ ord_card_unbounded, range_eq_iff], exact ⟨aleph'_is_normal.strict_mono, ⟨(λ a, (by { dsimp, rw card_ord })), λ b hb, eq_aleph'_of_eq_card_ord hb⟩⟩ end /-- Infinite ordinals that are cardinals are unbounded. -/ theorem ord_card_unbounded' : unbounded (<) {b : ordinal | b.card.ord = b ∧ ω ≤ b} := (unbounded_lt_inter_le ω).2 ord_card_unbounded theorem eq_aleph_of_eq_card_ord {o : ordinal} (ho : o.card.ord = o) (ho' : ω ≤ o) : ∃ a, (aleph a).ord = o := begin cases eq_aleph'_of_eq_card_ord ho with a ha, use a - ω, unfold aleph, rwa ordinal.add_sub_cancel_of_le, rwa [←aleph_0_le_aleph', ←ord_le_ord, ha, ord_aleph_0] end /-- `ord ∘ aleph` enumerates the infinite ordinals that are cardinals. -/ theorem ord_aleph_eq_enum_card : ord ∘ aleph = enum_ord {b : ordinal | b.card.ord = b ∧ ω ≤ b} := begin rw ←eq_enum_ord _ ord_card_unbounded', use aleph_is_normal.strict_mono, rw range_eq_iff, refine ⟨(λ a, ⟨_, _⟩), λ b hb, eq_aleph_of_eq_card_ord hb.1 hb.2⟩, { rw card_ord }, { rw [←ord_aleph_0, ord_le_ord], exact aleph_0_le_aleph _ } end /-! ### Beth cardinals -/ /-- Beth numbers are defined so that `beth 0 = ℵ₀`, `beth (succ o) = 2 ^ (beth o)`, and when `o` is a limit ordinal, `beth o` is the supremum of `beth o'` for `o' < o`. Assuming the generalized continuum hypothesis, which is undecidable in ZFC, `beth o = aleph o` for every `o`. -/ def beth (o : ordinal.{u}) : cardinal.{u} := limit_rec_on o aleph_0 (λ _ x, 2 ^ x) (λ a ha IH, ⨆ b : Iio a, IH b.1 b.2) @[simp] theorem beth_zero : beth 0 = aleph_0 := limit_rec_on_zero _ _ _ @[simp] theorem beth_succ (o : ordinal) : beth (succ o) = 2 ^ beth o := limit_rec_on_succ _ _ _ _ theorem beth_limit {o : ordinal} : o.is_limit → beth o = ⨆ a : Iio o, beth a := limit_rec_on_limit _ _ _ _ theorem beth_strict_mono : strict_mono beth := begin intros a b, induction b using ordinal.induction with b IH generalizing a, intro h, rcases zero_or_succ_or_limit b with rfl | ⟨c, rfl⟩ | hb, { exact (ordinal.not_lt_zero a h).elim }, { rw lt_succ_iff at h, rw beth_succ, apply lt_of_le_of_lt _ (cantor _), rcases eq_or_lt_of_le h with rfl | h, { refl }, exact (IH c (lt_succ c) h).le }, { apply (cantor _).trans_le, rw [beth_limit hb, ←beth_succ], exact le_csupr (bdd_above_of_small _) (⟨_, hb.succ_lt h⟩ : Iio b) } end lemma beth_mono : monotone beth := beth_strict_mono.monotone @[simp] theorem beth_lt {o₁ o₂ : ordinal} : beth o₁ < beth o₂ ↔ o₁ < o₂ := beth_strict_mono.lt_iff_lt @[simp] theorem beth_le {o₁ o₂ : ordinal} : beth o₁ ≤ beth o₂ ↔ o₁ ≤ o₂ := beth_strict_mono.le_iff_le theorem aleph_le_beth (o : ordinal) : aleph o ≤ beth o := begin apply limit_rec_on o, { simp }, { intros o h, rw [aleph_succ, beth_succ, succ_le_iff], exact (cantor _).trans_le (power_le_power_left two_ne_zero h) }, { intros o ho IH, rw [aleph_limit ho, beth_limit ho], exact csupr_mono (bdd_above_of_small _) (λ x, IH x.1 x.2) } end theorem aleph_0_le_beth (o : ordinal) : ℵ₀ ≤ beth o := (aleph_0_le_aleph o).trans $ aleph_le_beth o theorem beth_pos (o : ordinal) : 0 < beth o := aleph_0_pos.trans_le $ aleph_0_le_beth o theorem beth_ne_zero (o : ordinal) : beth o ≠ 0 := (beth_pos o).ne' lemma beth_normal : is_normal.{u} (λ o, (beth o).ord) := (is_normal_iff_strict_mono_limit _).2 ⟨ord_strict_mono.comp beth_strict_mono, λ o ho a ha, by { rw [beth_limit ho, ord_le], exact csupr_le' (λ b, ord_le.1 (ha _ b.2)) }⟩ /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using mul_le_mul_left' (one_le_aleph_0.trans h) c), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.lt_wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (succ (typein (<) (g p))) * card (succ (typein (<) (g p)))) _, { have : {q | s q p} ⊆ insert (g p) {x | x < g p} ×ˢ insert (g p) {x | x < g p}, { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_le (card (succ (typein (<) (g p)))) ℵ₀ with qo qo, { exact (mul_lt_aleph_0 qo qo).trans_le ol }, { suffices, {exact (IH _ this qo).trans_lt this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : ℵ₀ ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (ha.trans (le_max_left a b)) ▸ mul_le_mul' (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using mul_le_mul_left' (one_le_aleph_0.trans hb) a) (by simpa only [one_mul] using mul_le_mul_right' (one_le_aleph_0.trans ha) b) @[simp] theorem mul_mk_eq_max {α β : Type*} [infinite α] [infinite β] : #α * #β = max (#α) (#β) := mul_eq_max (aleph_0_le_mk α) (aleph_0_le_mk β) @[simp] theorem aleph_mul_aleph (o₁ o₂ : ordinal) : aleph o₁ * aleph o₂ = aleph (max o₁ o₂) := by rw [cardinal.mul_eq_max (aleph_0_le_aleph o₁) (aleph_0_le_aleph o₂), max_aleph_eq] @[simp] theorem aleph_0_mul_eq {a : cardinal} (ha : ℵ₀ ≤ a) : ℵ₀ * a = a := (mul_eq_max le_rfl ha).trans (max_eq_right ha) @[simp] theorem mul_aleph_0_eq {a : cardinal} (ha : ℵ₀ ≤ a) : a * ℵ₀ = a := (mul_eq_max ha le_rfl).trans (max_eq_left ha) @[simp] theorem aleph_0_mul_mk_eq {α : Type*} [infinite α] : ℵ₀ * #α = #α := aleph_0_mul_eq (aleph_0_le_mk α) @[simp] theorem mk_mul_aleph_0_eq {α : Type*} [infinite α] : #α * ℵ₀ = #α := mul_aleph_0_eq (aleph_0_le_mk α) @[simp] theorem aleph_0_mul_aleph (o : ordinal) : ℵ₀ * aleph o = aleph o := aleph_0_mul_eq (aleph_0_le_aleph o) @[simp] theorem aleph_mul_aleph_0 (o : ordinal) : aleph o * ℵ₀ = aleph o := mul_aleph_0_eq (aleph_0_le_aleph o) theorem mul_lt_of_lt {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := (mul_le_mul' (le_max_left a b) (le_max_right a b)).trans_lt $ (lt_or_le (max a b) ℵ₀).elim (λ h, (mul_lt_aleph_0 h h).trans_le hc) (λ h, by { rw mul_eq_self h, exact max_lt h1 h2 }) lemma mul_le_max_of_aleph_0_le_left {a b : cardinal} (h : ℵ₀ ≤ a) : a * b ≤ max a b := begin convert mul_le_mul' (le_max_left a b) (le_max_right a b), rw mul_eq_self, refine h.trans (le_max_left a b) end lemma mul_eq_max_of_aleph_0_le_left {a b : cardinal} (h : ℵ₀ ≤ a) (h' : b ≠ 0) : a * b = max a b := begin cases le_or_lt ℵ₀ b with hb hb, { exact mul_eq_max h hb }, refine (mul_le_max_of_aleph_0_le_left h).antisymm _, have : b ≤ a, from hb.le.trans h, rw [max_eq_left this], convert mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one], end lemma mul_le_max_of_aleph_0_le_right {a b : cardinal} (h : ℵ₀ ≤ b) : a * b ≤ max a b := by simpa only [mul_comm, max_comm] using mul_le_max_of_aleph_0_le_left h lemma mul_eq_max_of_aleph_0_le_right {a b : cardinal} (h' : a ≠ 0) (h : ℵ₀ ≤ b) : a * b = max a b := begin rw [mul_comm, max_comm], exact mul_eq_max_of_aleph_0_le_left h h' end lemma mul_eq_max' {a b : cardinal} (h : ℵ₀ ≤ a * b) : a * b = max a b := begin rcases aleph_0_le_mul_iff.mp h with ⟨ha, hb, ha' | hb'⟩, { exact mul_eq_max_of_aleph_0_le_left ha' hb }, { exact mul_eq_max_of_aleph_0_le_right ha hb' } end theorem mul_le_max (a b : cardinal) : a * b ≤ max (max a b) ℵ₀ := begin rcases eq_or_ne a 0 with rfl | ha0, { simp }, rcases eq_or_ne b 0 with rfl | hb0, { simp }, cases le_or_lt ℵ₀ a with ha ha, { rw [mul_eq_max_of_aleph_0_le_left ha hb0], exact le_max_left _ _ }, { cases le_or_lt ℵ₀ b with hb hb, { rw [mul_comm, mul_eq_max_of_aleph_0_le_left hb ha0, max_comm], exact le_max_left _ _ }, { exact le_max_of_le_right (mul_lt_aleph_0 ha hb).le } } end lemma mul_eq_left {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_aleph_0_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : ℵ₀ ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _, rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max ℵ₀ b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw max_le_iff, refine ⟨λ h, _, _⟩, { cases le_or_lt ℵ₀ a with ha ha, { have : a ≠ 0, { rintro rfl, exact ha.not_lt aleph_0_pos }, left, use ha, { rw ←not_lt, exact λ hb, ne_of_gt (hb.trans_le (le_mul_left this)) h }, { rintro rfl, apply this, rw mul_zero at h, exact h.symm }}, right, by_cases h2a : a = 0, { exact or.inr h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw mul_zero at h, exact h.symm }, left, rw [←h, mul_lt_aleph_0_iff, lt_aleph_0, lt_aleph_0] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw ←ne at h2a, rw ←one_le_iff_ne_zero at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw ←not_lt, apply λ h2b, ne_of_gt _ h, conv_lhs { rw ←mul_one n }, rwa mul_lt_mul_left, apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_aleph_0_le_left ha hb, max_eq_left hab] }, all_goals { simp }} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using mul_le_mul_right' ((nat_lt_aleph_0 2).le.trans h) c) (self_le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : ℵ₀ ≤ a) : a + b = max a b := le_antisymm (add_eq_self (ha.trans (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (self_le_add_right _ _) (self_le_add_left _ _) theorem add_eq_max' {a b : cardinal} (ha : ℵ₀ ≤ b) : a + b = max a b := by rw [add_comm, max_comm, add_eq_max ha] @[simp] theorem add_mk_eq_max {α β : Type*} [infinite α] : #α + #β = max (#α) (#β) := add_eq_max (aleph_0_le_mk α) @[simp] theorem add_mk_eq_max' {α β : Type*} [infinite β] : #α + #β = max (#α) (#β) := add_eq_max' (aleph_0_le_mk β) theorem add_le_max (a b : cardinal) : a + b ≤ max (max a b) ℵ₀ := begin cases le_or_lt ℵ₀ a with ha ha, { rw [add_eq_max ha], exact le_max_left _ _ }, { cases le_or_lt ℵ₀ b with hb hb, { rw [add_comm, add_eq_max hb, max_comm], exact le_max_left _ _ }, { exact le_max_of_le_right (add_lt_aleph_0 ha hb).le } } end theorem add_le_of_le {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a ≤ c) (h2 : b ≤ c) : a + b ≤ c := (add_le_add h1 h2).trans $ le_of_eq $ add_eq_self hc theorem add_lt_of_lt {a b c : cardinal} (hc : ℵ₀ ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := (add_le_add (le_max_left a b) (le_max_right a b)).trans_lt $ (lt_or_le (max a b) ℵ₀).elim (λ h, (add_lt_aleph_0 h h).trans_le hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_aleph_0_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : ℵ₀ ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply self_le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : ℵ₀ ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : ℵ₀ ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max ℵ₀ b ≤ a ∨ b = 0) := begin rw max_le_iff, refine ⟨λ h, _, _⟩, { cases (le_or_lt ℵ₀ a) with ha ha, { left, use ha, rw ←not_lt, apply λ hb, ne_of_gt _ h, exact hb.trans_le (self_le_add_left b a) }, right, rw [←h, add_lt_aleph_0_iff, lt_aleph_0, lt_aleph_0] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [←add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), { rw [add_eq_max h1, max_eq_left h2] }, { rw [h3, add_zero] } } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max ℵ₀ a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_nat_eq {a : cardinal} (n : ℕ) (ha : ℵ₀ ≤ a) : a + n = a := add_eq_left ha ((nat_lt_aleph_0 _).le.trans ha) lemma add_one_eq {a : cardinal} (ha : ℵ₀ ≤ a) : a + 1 = a := add_eq_left ha (one_le_aleph_0.trans ha) @[simp] lemma mk_add_one_eq {α : Type*} [infinite α] : #α + 1 = #α := add_one_eq (aleph_0_le_mk α) protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < ℵ₀) : b = c := begin cases le_or_lt ℵ₀ b with hb hb, { have : a < b := ha.trans_le hb, rw [add_eq_right hb this.le, eq_comm] at h, rw [eq_of_add_eq_of_aleph_0_le h this hb] }, { have hc : c < ℵ₀, { rw ←not_le, intro hc, apply lt_irrefl ℵ₀, apply (hc.trans (self_le_add_left _ a)).trans_lt, rw ←h, apply add_lt_aleph_0 ha hb }, rw lt_aleph_0 at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < ℵ₀) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } @[simp] theorem aleph_add_aleph (o₁ o₂ : ordinal) : aleph o₁ + aleph o₂ = aleph (max o₁ o₂) := by rw [cardinal.add_eq_max (aleph_0_le_aleph o₁), max_aleph_eq] theorem principal_add_ord {c : cardinal} (hc : ℵ₀ ≤ c) : ordinal.principal (+) c.ord := λ a b ha hb, by { rw [lt_ord, ordinal.card_add] at *, exact add_lt_of_lt hc ha hb } theorem principal_add_aleph (o : ordinal) : ordinal.principal (+) (aleph o).ord := principal_add_ord $ aleph_0_le_aleph o lemma add_right_inj_of_lt_aleph_0 {α β γ : cardinal} (γ₀ : γ < aleph_0) : α + γ = β + γ ↔ α = β := ⟨λ h, cardinal.eq_of_add_eq_add_right h γ₀, λ h, congr_fun (congr_arg (+) h) γ⟩ @[simp] lemma add_nat_inj {α β : cardinal} (n : ℕ) : α + n = β + n ↔ α = β := add_right_inj_of_lt_aleph_0 (nat_lt_aleph_0 _) @[simp] lemma add_one_inj {α β : cardinal} : α + 1 = β + 1 ↔ α = β := add_right_inj_of_lt_aleph_0 one_lt_aleph_0 lemma add_le_add_iff_of_lt_aleph_0 {α β γ : cardinal} (γ₀ : γ < cardinal.aleph_0) : α + γ ≤ β + γ ↔ α ≤ β := begin refine ⟨λ h, _, λ h, add_le_add_right h γ⟩, contrapose h, rw [not_le, lt_iff_le_and_ne, ne] at h ⊢, exact ⟨add_le_add_right h.1 γ, mt (add_right_inj_of_lt_aleph_0 γ₀).1 h.2⟩, end @[simp] lemma add_nat_le_add_nat_iff_of_lt_aleph_0 {α β : cardinal} (n : ℕ) : α + n ≤ β + n ↔ α ≤ β := add_le_add_iff_of_lt_aleph_0 (nat_lt_aleph_0 n) @[simp] lemma add_one_le_add_one_iff_of_lt_aleph_0 {α β : cardinal} : α + 1 ≤ β + 1 ↔ α ≤ β := add_le_add_iff_of_lt_aleph_0 one_lt_aleph_0 /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : ℵ₀ ≤ κ) (H2 : μ < ℵ₀) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_aleph_0.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (lt_of_lt_of_le (by { rw [nat.cast_zero, power_zero], exact one_lt_aleph_0 }) H1).le (λ n ih, trans_rel_left _ (by { rw [nat.cast_succ, power_add, power_one], exact mul_le_mul_right' ih _ }) (mul_eq_self H1))) H1) theorem pow_eq {κ μ : cardinal.{u}} (H1 : ℵ₀ ≤ κ) (H2 : 1 ≤ μ) (H3 : μ < ℵ₀) : κ ^ μ = κ := (pow_le H1 H3).antisymm $ self_le_power κ H2 lemma power_self_eq {c : cardinal} (h : ℵ₀ ≤ c) : c ^ c = 2 ^ c := begin apply ((power_le_power_right $ (cantor c).le).trans _).antisymm, { convert power_le_power_right ((nat_lt_aleph_0 2).le.trans h), apply nat.cast_two.symm }, { rw [←power_mul, mul_eq_self h] } end lemma prod_eq_two_power {ι : Type u} [infinite ι] {c : ι → cardinal.{v}} (h₁ : ∀ i, 2 ≤ c i) (h₂ : ∀ i, lift.{u} (c i) ≤ lift.{v} (#ι)) : prod c = 2 ^ lift.{v} (#ι) := begin rw [← lift_id' (prod c), lift_prod, ← lift_two_power], apply le_antisymm, { refine (prod_le_prod _ _ h₂).trans_eq _, rw [prod_const, lift_lift, ← lift_power, power_self_eq (aleph_0_le_mk ι), lift_umax.{u v}] }, { rw [← prod_const', lift_prod], refine prod_le_prod _ _ (λ i, _), rw [lift_two, ← lift_two.{u v}, lift_le], exact h₁ i } end lemma power_eq_two_power {c₁ c₂ : cardinal} (h₁ : ℵ₀ ≤ c₁) (h₂ : 2 ≤ c₂) (h₂' : c₂ ≤ c₁) : c₂ ^ c₁ = 2 ^ c₁ := le_antisymm (power_self_eq h₁ ▸ power_le_power_right h₂') (power_le_power_right h₂) lemma nat_power_eq {c : cardinal.{u}} (h : ℵ₀ ≤ c) {n : ℕ} (hn : 2 ≤ n) : (n : cardinal.{u}) ^ c = 2 ^ c := power_eq_two_power h (by assumption_mod_cast) ((nat_lt_aleph_0 n).le.trans h) lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : ℵ₀ ≤ c) : c ^ n ≤ c := pow_le h (nat_lt_aleph_0 n) lemma power_nat_eq {c : cardinal.{u}} {n : ℕ} (h1 : ℵ₀ ≤ c) (h2 : 1 ≤ n) : c ^ n = c := pow_eq h1 (by exact_mod_cast h2) (nat_lt_aleph_0 n) lemma power_nat_le_max {c : cardinal.{u}} {n : ℕ} : c ^ (n : cardinal.{u}) ≤ max c ℵ₀ := begin cases le_or_lt ℵ₀ c with hc hc, { exact le_max_of_le_left (power_nat_le hc) }, { exact le_max_of_le_right ((power_lt_aleph_0 hc (nat_lt_aleph_0 _)).le) } end lemma powerlt_aleph_0 {c : cardinal} (h : ℵ₀ ≤ c) : c ^< ℵ₀ = c := begin apply le_antisymm, { rw powerlt_le, intro c', rw lt_aleph_0, rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt c one_lt_aleph_0, rw power_one end lemma powerlt_aleph_0_le (c : cardinal) : c ^< ℵ₀ ≤ max c ℵ₀ := begin cases le_or_lt ℵ₀ c, { rw powerlt_aleph_0 h, apply le_max_left }, rw powerlt_le, exact λ c' hc', (power_lt_aleph_0 h hc').le.trans (le_max_right _ _) end /-! ### Computing cardinality of various types -/ @[simp] theorem mk_list_eq_mk (α : Type u) [infinite α] : #(list α) = #α := have H1 : ℵ₀ ≤ #α := aleph_0_le_mk α, eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc #(list α) = sum (λ n : ℕ, #α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, #α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_aleph_0 n ... = #α : by simp [H1] theorem mk_list_eq_aleph_0 (α : Type u) [countable α] [nonempty α] : #(list α) = ℵ₀ := mk_le_aleph_0.antisymm (aleph_0_le_mk _) theorem mk_list_eq_max_mk_aleph_0 (α : Type u) [nonempty α] : #(list α) = max (#α) ℵ₀ := begin casesI finite_or_infinite α, { rw [mk_list_eq_aleph_0, eq_comm, max_eq_right], exact mk_le_aleph_0 }, { rw [mk_list_eq_mk, eq_comm, max_eq_left], exact aleph_0_le_mk α } end theorem mk_list_le_max (α : Type u) : #(list α) ≤ max ℵ₀ (#α) := begin casesI finite_or_infinite α, { exact mk_le_aleph_0.trans (le_max_left _ _) }, { rw mk_list_eq_mk, apply le_max_right } end @[simp] theorem mk_finset_of_infinite (α : Type u) [infinite α] : #(finset α) = #α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc #(finset α) ≤ #(list α) : mk_le_of_surjective list.to_finset_surjective ... = #α : mk_list_eq_mk α @[simp] lemma mk_finsupp_lift_of_infinite (α : Type u) (β : Type v) [infinite α] [has_zero β] [nontrivial β] : #(α →₀ β) = max (lift.{v} (#α)) (lift.{u} (#β)) := begin apply le_antisymm, { calc #(α →₀ β) ≤ # (finset (α × β)) : mk_le_of_injective (finsupp.graph_injective α β) ... = #(α × β) : mk_finset_of_infinite _ ... = max (lift.{v} (#α)) (lift.{u} (#β)) : by rw [mk_prod, mul_eq_max_of_aleph_0_le_left]; simp }, { apply max_le; rw [←lift_id (# (α →₀ β)), ←lift_umax], { cases exists_ne (0 : β) with b hb, exact lift_mk_le.{u (max u v) v}.2 ⟨⟨_, finsupp.single_left_injective hb⟩⟩ }, { inhabit α, exact lift_mk_le.{v (max u v) u}.2 ⟨⟨_, finsupp.single_injective default⟩⟩ } } end lemma mk_finsupp_of_infinite (α β : Type u) [infinite α] [has_zero β] [nontrivial β] : #(α →₀ β) = max (#α) (#β) := by simp @[simp] lemma mk_finsupp_lift_of_infinite' (α : Type u) (β : Type v) [nonempty α] [has_zero β] [infinite β] : #(α →₀ β) = max (lift.{v} (#α)) (lift.{u} (#β)) := begin casesI fintype_or_infinite α, { rw mk_finsupp_lift_of_fintype, have : ℵ₀ ≤ (#β).lift := aleph_0_le_lift.2 (aleph_0_le_mk β), rw [max_eq_right (le_trans _ this), power_nat_eq this], exacts [fintype.card_pos, lift_le_aleph_0.2 (lt_aleph_0_of_finite _).le] }, { apply mk_finsupp_lift_of_infinite }, end lemma mk_finsupp_of_infinite' (α β : Type u) [nonempty α] [has_zero β] [infinite β] : #(α →₀ β) = max (#α) (#β) := by simp lemma mk_finsupp_nat (α : Type u) [nonempty α] : #(α →₀ ℕ) = max (#α) ℵ₀ := by simp @[simp] lemma mk_multiset_of_nonempty (α : Type u) [nonempty α] : #(multiset α) = max (#α) ℵ₀ := multiset.to_finsupp.to_equiv.cardinal_eq.trans (mk_finsupp_nat α) lemma mk_multiset_of_infinite (α : Type u) [infinite α] : #(multiset α) = #α := by simp @[simp] lemma mk_multiset_of_is_empty (α : Type u) [is_empty α] : #(multiset α) = 1 := multiset.to_finsupp.to_equiv.cardinal_eq.trans (by simp) lemma mk_multiset_of_countable (α : Type u) [countable α] [nonempty α] : #(multiset α) = ℵ₀ := multiset.to_finsupp.to_equiv.cardinal_eq.trans (by simp) lemma mk_bounded_set_le_of_infinite (α : Type u) [infinite α] (c : cardinal) : #{t : set α // #t ≤ c} ≤ #α ^ c := begin refine le_trans _ (by rw [←add_one_eq (aleph_0_le_mk α)]), induction c using cardinal.induction_on with β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : #{t : set α // #t ≤ c} ≤ max (#α) ℵ₀ ^ c := begin transitivity #{t : set (ulift.{u} ℕ ⊕ α) // #t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact mk_image_le.trans hs }, apply (mk_bounded_set_le_of_infinite (ulift.{u} ℕ ⊕ α) c).trans, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : #{t : set α // t ⊆ s ∧ #t ≤ c} ≤ max (#s) ℵ₀ ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact (mk_preimage_of_injective _ _ subtype.val_injective).trans h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_infinite {α : Type*} [infinite α] (s : set α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_aleph_0_le _ h2 (aleph_0_le_mk α), exact mk_sum_compl s } lemma mk_compl_finset_of_infinite {α : Type*} [infinite α] (s : finset α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_infinite, exact (finset_card_lt_aleph_0 s).trans_le (aleph_0_le_mk α) } lemma mk_compl_eq_mk_compl_infinite {α : Type*} [infinite α] {s t : set α} (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_infinite s hs, mk_compl_of_infinite t ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} [finite α] {s : set α} {t : set β} (h1 : lift.{max v w} (#α) = lift.{max u w} (#β)) (h2 : lift.{max v w} (#s) = lift.{max u w} (#t)) : lift.{max v w} (#(sᶜ : set α)) = lift.{max u w} (#(tᶜ : set β)) := begin casesI nonempty_fintype α, rcases lift_mk_eq.1 h1 with ⟨e⟩, letI : fintype β := fintype.of_equiv α e, replace h1 : fintype.card α = fintype.card β := (fintype.of_equiv_card _).symm, classical, lift s to finset α using s.to_finite, lift t to finset β using t.to_finite, simp only [finset.coe_sort_coe, mk_coe_finset, lift_nat_cast, nat.cast_inj] at h2, simp only [← finset.coe_compl, finset.coe_sort_coe, mk_coe_finset, finset.card_compl, lift_nat_cast, nat.cast_inj, h1, h2] end lemma mk_compl_eq_mk_compl_finite {α β : Type u} [finite α] {s : set α} {t : set β} (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw ← lift_inj, apply mk_compl_eq_mk_compl_finite_lift; rwa [lift_inj] } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} [finite α] {s t : set α} (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.of_injective f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} [finite α] {s : set α} (f : s ↪ β) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, cases id h with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin casesI fintype_or_infinite α, { exact extend_function_finite f h }, { apply extend_function f, cases id h with g, haveI := infinite.of_injective _ g.injective, rw [← lift_mk_eq'] at h ⊢, rwa [mk_compl_of_infinite s hs, mk_compl_of_infinite], rwa [← lift_lt, mk_range_eq_of_injective f.injective, ← h, lift_lt] }, end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := zero_lt_one.trans_le (self_le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (zero_lt_one.trans_le h), λ h, (one_le_iff_pos.mpr h).trans (self_le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : ℵ₀ ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_aleph_0 {c : cardinal} : bit0 c < ℵ₀ ↔ c < ℵ₀ := by simp [bit0, add_lt_aleph_0_iff] @[simp] theorem aleph_0_le_bit0 {c : cardinal} : ℵ₀ ≤ bit0 c ↔ ℵ₀ ≤ c := by { rw ←not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ ℵ₀ ≤ c := begin by_cases h : ℵ₀ ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_aleph_0_le] }, { refine iff_of_false (ne_of_gt _) h, rcases lt_aleph_0.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], linarith } end @[simp] theorem bit1_lt_aleph_0 {c : cardinal} : bit1 c < ℵ₀ ↔ c < ℵ₀ := by simp [bit1, bit0, add_lt_aleph_0_iff, one_lt_aleph_0] @[simp] theorem aleph_0_le_bit1 {c : cardinal} : ℵ₀ ≤ bit1 c ↔ ℵ₀ ≤ c := by { rw ←not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.trans_le ha).not_le, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).le.trans hb) (ha.le.trans hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit0_le_bit0 } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.trans_le ha).not_le, have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { rw bit1_eq_self_iff.2 hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).le.trans hb) (ha.le.trans hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact nat.bit0_le_bit1_iff } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := ⟨λ h, bit0_le_bit1.1 ((self_le_add_right (bit0 a) 1).trans h), λ h, (add_le_add_right (add_le_add_left h a) 1).trans (add_le_add_right (add_le_add_right h b) 1)⟩ @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ ℵ₀ ≤ a)) := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (λ h, _), { have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans_le h) }, { exact not_le_of_lt (hb.trans_le ha) (h.elim le_of_lt and.left) } }, { rw bit0_eq_self hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).le.trans hb) (or.inl $ ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha] } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit0_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit0_lt_bit0 } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb] }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit0 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit0_eq_self hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact nat.bit1_lt_bit0_iff } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb] }, { rw bit1_eq_self_iff.2 ha, refine iff_of_false (λ h, _) (hb.le.trans ha).not_lt, have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { rw bit1_eq_self_iff.2 hb, exact iff_of_true ((bit1_lt_aleph_0.2 ha).trans_le hb) (ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, exact bit1_lt_bit1 } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < ℵ₀)) := begin cases le_or_lt ℵ₀ a with ha ha; cases le_or_lt ℵ₀ b with hb hb, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, refine iff_of_false (λ h, _) (λ h, _), { have A : bit1 b < ℵ₀, by simpa using hb, exact lt_irrefl _ ((A.trans_le ha).trans h) }, { exact (hb.trans_le ha).not_le (h.elim le_of_lt and.left) } }, { rw [bit1_eq_self_iff.2 hb], exact iff_of_true ((bit0_lt_aleph_0.2 ha).trans_le hb) (or.inl $ ha.trans_le hb) }, { rcases lt_aleph_0.1 ha with ⟨m, rfl⟩, rcases lt_aleph_0.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff, or_iff_right_of_imp le_of_lt] } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [←bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [←bit1_zero] end bit end cardinal
6ee7ed10519a6bf02f5ddb8debcd869ad1dc772d
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Eval.lean
508d9c52a645e5f17ea9a9632a075bf4c5745899
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,155
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.Reader import Init.System.IO import Init.Lean.Environment namespace Lean universe u /-- `HasEval` extension that gives access to the current environment & options. The basic `HasEval` class is in the prelude and should not depend on these types. -/ class MetaHasEval (α : Type u) := (eval : Environment → Options → α → forall (hideUnit : optParam Bool true), IO Unit) instance metaHasEvalOfHasEval {α : Type u} [HasEval α] : MetaHasEval α := ⟨fun env opts a hideUnit => HasEval.eval a hideUnit⟩ abbrev MetaIO := ReaderT (Environment × Options) IO def MetaIO.getEnv : MetaIO Environment := do ctx ← read; pure ctx.1 def MetaIO.getOptions : MetaIO Options := do ctx ← read; pure ctx.2 instance MetaIO.metaHasEval {α} [MetaHasEval α] : MetaHasEval (MetaIO α) := ⟨fun env opts x _ => x (env, opts) >>= MetaHasEval.eval env opts⟩ instance MetaIO.monadIO : MonadIO MetaIO := ⟨fun _ x _ => x⟩ end Lean
0ef8ea267b647c2aa806cfbf668fae828892b4dd
fddcf4b659baa121761c71be606b3f74b86fa695
/Formalization/test_lean.lean
65d35078bb870d1112dbaeb208f34702aaaf9e70
[]
no_license
swarnpriya/Lean
4218df9392f396cd7e5e745de35a917536ebd2bb
a0a9978fd058041eb1a09aec0e2dd7d19a7436a7
refs/heads/master
1,595,831,634,399
1,568,673,127,000
1,568,673,127,000
208,903,604
0
0
null
null
null
null
UTF-8
Lean
false
false
688
lean
universe u constant α : Type u #check α def foo : (ℕ → ℕ) → ℕ := λ f, f 0 #check foo #print foo def double (x : ℕ) : ℕ := x + x #print double #check double 3 #reduce double 3 def square (x : ℕ) : ℕ := x * x #check square #reduce square 3 constants p q : Prop theorem t1 : p → q → p := λ hp : p, λ hq : q, hp #print t1 #check ¬p → p ↔ false #reduce true ∧ false theorem test (p q : Prop) (hp : p) (hq : q) : p ∧ q ∧ p := begin apply and.intro, exact hp, apply and.intro, exact hq, exact hp end example : ∀ a b c : ℕ, a = b → a = c → c = b := begin intros, transitivity a, symmetry, assumption, assumption end
1b94526dd8e90d63fa648d427c00c9d63fb51e03
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/set/intervals/basic.lean
0b568e212fa5310a72417b943c64a7bdd920379d
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
28,591
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov -/ import order.lattice algebra.order_functions algebra.ordered_field tactic.tauto /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). This file also contains statements on lower and upper bounds of intervals. TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} := set.ext $ λ x, begin simp [not_and'], split, { rintro ⟨⟨ax, xb⟩, hne⟩, exact (eq_or_lt_of_le ax).elim eq.symm (λ h', absurd h' (hne xb)) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, λ _, lt_irrefl x⟩ } end lemma Ioc_diff_Ioo_eq_singleton (h : a < b) : Ioc a b \ Ioo a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, hne⟩, exact (eq_or_lt_of_le xb).elim id (λ h', absurd h' (hne ax)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ ne, h ax (lt_of_le_of_ne xb ne)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end lemma Icc_diff_Ioc_eq_singleton (h : a ≤ b) : Icc a b \ Ioc a b = {a} := set.ext $ λ x, begin simp [not_and'], split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ hne, h xb (lt_of_le_of_ne ax (ne.symm hne))) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, λ _, lt_irrefl x⟩ } end end partial_order section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma compl_Iic : -(Iic a) = Ioi a := ext $ λ _, not_le lemma compl_Ici : -(Ici a) = Iio a := ext $ λ _, not_le lemma compl_Iio : -(Iio a) = Ici a := ext $ λ _, not_lt lemma compl_Ioi : -(Ioi a) = Iic a := ext $ λ _, not_lt lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iic h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le bc (h ca)) end /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_lt_of_le h), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Icc_union_Ici_eq_Ioi (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (le_trans h), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_lt_of_le h), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ico_union_Ici_eq_Ioi (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (le_trans h), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := ext $ λ x, ⟨λ hx, hx.elim and.left (lt_of_le_of_lt h), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ @[simp] lemma Icc_union_Ioi_eq_Ioi (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := ext $ λ x, ⟨λ hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx)), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb)⟩ /-! #### An infinite and a finite interval -/ @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans hx h) and.right, λ hx, (le_total x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right, λ hx, (le_total x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right, λ hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right, λ hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, le_trans hx h) and.right, λ hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := ext $ λ x, ⟨λ hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right, λ hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩)⟩ /-! #### Two finite intervals with a common point -/ @[simp] lemma Ioc_union_Ico_eq_Ioo {c} (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ico_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Icc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioc_union_Icc_eq_Ioc {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (le_total x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ /-! #### Two finite intervals, `I?o` and `Ic?` -/ @[simp] lemma Ioo_union_Ico_eq_Ioo {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ico_union_Ico_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ico_union_Icc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioo_union_Icc_eq_Ioc {c} (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩), λ hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ /-! #### Two finite intervals, `I?c` and `Io?` -/ @[simp] lemma Ioc_union_Ioo_eq_Ioo {c} (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ioo_eq_Ico {c} (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Icc_union_Ioc_eq_Icc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ @[simp] lemma Ioc_union_Ioc_eq_Ioc {c} (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := ext $ λ x, ⟨λ hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩), λ hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩)⟩ end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := begin rw [Icc_inter_Icc], convert Icc_self b, exact sup_of_le_right hab, exact inf_of_le_left hbc end include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section decidable_linear_order variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} end decidable_linear_order section ordered_comm_group variables {α : Type u} [ordered_comm_group α] lemma image_add_left_Icc (a b c : α) : ((+) a) '' Icc b c = Icc (a + b) (a + c) := begin ext x, split, { rintros ⟨x, hx, rfl⟩, exact ⟨add_le_add_left hx.1 a, add_le_add_left hx.2 a⟩}, { intro hx, refine ⟨-a + x, _, add_neg_cancel_left _ _⟩, exact ⟨le_neg_add_iff_add_le.2 hx.1, neg_add_le_iff_le_add.2 hx.2⟩ } end lemma image_add_right_Icc (a b c : α) : (λ x, x + c) '' Icc a b = Icc (a + c) (b + c) := by convert image_add_left_Icc c a b using 1; simp only [add_comm _ c] lemma image_neg_Iio (r : α) : image (λz, -z) (Iio r) = Ioi (-r) := begin ext z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [mem_Ioi, neg_lt_neg_iff], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iio], use -z, simp [hz], exact neg_lt.1 hz } end lemma image_neg_Iic (r : α) : image (λz, -z) (Iic r) = Ici (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [neg_le_neg_iff, mem_Ici], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iic], use -z, simp [hz], exact neg_le.1 hz } end end ordered_comm_group section decidable_linear_ordered_comm_group variables {α : Type u} [decidable_linear_ordered_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp* }, { use max x (x + dy), simp [*, le_refl] } end end decidable_linear_ordered_comm_group section linear_ordered_field variables {α : Type u} [linear_ordered_field α] lemma image_mul_right_Icc' (a b : α) {c : α} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin ext x, split, { rintros ⟨x, hx, rfl⟩, exact ⟨mul_le_mul_of_nonneg_right hx.1 (le_of_lt h), mul_le_mul_of_nonneg_right hx.2 (le_of_lt h)⟩ }, { intro hx, refine ⟨x / c, _, div_mul_cancel x (ne_of_gt h)⟩, exact ⟨le_div_of_mul_le h hx.1, div_le_of_le_mul h (mul_comm b c ▸ hx.2)⟩ } end lemma image_mul_right_Icc {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : α} (h : 0 < a) (b c : α) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } end linear_ordered_field end set
41826592a11c88c554a423e3ec5e86d8fb77660e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category/bifunctor.lean
91e103616b982ef11dd7eb5f54fbd21d5028f9b8
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
4,354
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Functors with two arguments -/ import logic.function data.sum category.basic category.functor tactic.basic universes u₀ u₁ u₂ v₀ v₁ v₂ open function class bifunctor (F : Type u₀ → Type u₁ → Type u₂) := (bimap : Π {α α' β β'}, (α → α') → (β → β') → F α β → F α' β') export bifunctor ( bimap ) class is_lawful_bifunctor (F : Type u₀ → Type u₁ → Type u₂) [bifunctor F] := (id_bimap : Π {α β} (x : F α β), bimap id id x = x) (bimap_bimap : Π {α₀ α₁ α₂ β₀ β₁ β₂} (f : α₀ → α₁) (f' : α₁ → α₂) (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α₀ β₀), bimap f' g' (bimap f g x) = bimap (f' ∘ f) (g' ∘ g) x) export is_lawful_bifunctor (id_bimap bimap_bimap) attribute [higher_order bimap_id_id] id_bimap attribute [higher_order bimap_comp_bimap] bimap_bimap export is_lawful_bifunctor (bimap_id_id bimap_comp_bimap) variables {F : Type u₀ → Type u₁ → Type u₂} [bifunctor F] namespace bifunctor @[reducible] def fst {α α' β} (f : α → α') : F α β → F α' β := bimap f id @[reducible] def snd {α β β'} (f : β → β') : F α β → F α β' := bimap id f variable [is_lawful_bifunctor F] @[higher_order fst_id] lemma id_fst : Π {α β} (x : F α β), fst id x = x := @id_bimap _ _ _ @[higher_order snd_id] lemma id_snd : Π {α β} (x : F α β), snd id x = x := @id_bimap _ _ _ @[higher_order fst_comp_fst] lemma comp_fst {α₀ α₁ α₂ β} (f : α₀ → α₁) (f' : α₁ → α₂) (x : F α₀ β) : fst f' (fst f x) = fst (f' ∘ f) x := by simp [fst,bimap_bimap] @[higher_order fst_comp_snd] lemma fst_snd {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : fst f (snd f' x) = bimap f f' x := by simp [fst,bimap_bimap] @[higher_order snd_comp_fst] lemma snd_fst {α₀ α₁ β₀ β₁} (f : α₀ → α₁) (f' : β₀ → β₁) (x : F α₀ β₀) : snd f' (fst f x) = bimap f f' x := by simp [snd,bimap_bimap] @[higher_order snd_comp_snd] lemma comp_snd {α β₀ β₁ β₂} (g : β₀ → β₁) (g' : β₁ → β₂) (x : F α β₀) : snd g' (snd g x) = snd (g' ∘ g) x := by simp [snd,bimap_bimap] attribute [functor_norm] bimap_bimap comp_snd comp_fst snd_comp_snd snd_comp_fst fst_comp_snd fst_comp_fst bimap_comp_bimap bimap_id_id fst_id snd_id end bifunctor open functor instance : bifunctor prod := { bimap := @prod.map } instance : is_lawful_bifunctor prod := by refine { .. }; intros; cases x; refl instance bifunctor.const : bifunctor const := { bimap := (λ α α' β β f _, f) } instance is_lawful_bifunctor.const : is_lawful_bifunctor const := by refine { .. }; intros; refl instance bifunctor.flip : bifunctor (flip F) := { bimap := (λ α α' β β' f f' x, (bimap f' f x : F β' α')) } instance is_lawful_bifunctor.flip [is_lawful_bifunctor F] : is_lawful_bifunctor (flip F) := by refine { .. }; intros; simp [bimap] with functor_norm instance : bifunctor sum := { bimap := @sum.map } instance : is_lawful_bifunctor sum := by refine { .. }; intros; cases x; refl open bifunctor functor @[priority 10] instance bifunctor.functor {α} : functor (F α) := { map := λ _ _, snd } @[priority 10] instance bifunctor.is_lawful_functor [is_lawful_bifunctor F] {α} : is_lawful_functor (F α) := by refine {..}; intros; simp [functor.map] with functor_norm section bicompl variables (G : Type* → Type u₀) (H : Type* → Type u₁) [functor G] [functor H] instance : bifunctor (bicompl F G H) := { bimap := λ α α' β β' f f' x, (bimap (map f) (map f') x : F (G α') (H β')) } instance [is_lawful_functor G] [is_lawful_functor H] [is_lawful_bifunctor F] : is_lawful_bifunctor (bicompl F G H) := by constructor; intros; simp [bimap,map_id,map_comp_map] with functor_norm end bicompl section bicompr variables (G : Type u₂ → Type*) [functor G] instance : bifunctor (bicompr G F) := { bimap := λ α α' β β' f f' x, (map (bimap f f') x : G (F α' β')) } instance [is_lawful_functor G] [is_lawful_bifunctor F] : is_lawful_bifunctor (bicompr G F) := by constructor; intros; simp [bimap] with functor_norm end bicompr
9ab9350f183984060508abc199b43eb84f1b82bf
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/linear_algebra/affine_space/affine_subspace.lean
23cc0f3b1123067597c6b7474ff285b0ffba2519
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,973
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 linear_algebra.affine_space.basic import linear_algebra.tensor_product import data.set.intervals.unordered_interval /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_vadd], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { rw sub_eq_add_neg, apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [set_like.mem_coe, ←submodule.neg_mem_iff, ←set_like.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end @[simp] lemma ext_iff (s₁ s₂ : affine_subspace k P) : (s₁ : set P) = s₂ ↔ s₁ = s₂ := ⟨ext, by tidy⟩ /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s := { vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩, zero_vadd := by simp, add_vadd := λ a b c, by { ext, apply add_vadd }, vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩, nonempty := by apply_instance, vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' }, vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } } @[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) : ↑(a -ᵥ b) = (a:P) -ᵥ (b:P) := rfl @[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) : ↑(a +ᵥ b) = (a:V) +ᵥ (b:P) := rfl /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_vadd] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw set_like.le_def at hs, rw ←set_like.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, set_like.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl lemma bot_ne_top : (⊥ : affine_subspace k P) ≠ ⊤ := begin intros contra, rw [← ext_iff, bot_coe, top_coe] at contra, exact set.empty_ne_univ contra, end lemma nonempty_of_affine_span_eq_top {s : set P} (h : affine_span k s = ⊤) : s.nonempty := begin rw ← set.ne_empty_iff_nonempty, rintros rfl, rw affine_subspace.span_empty at h, exact bot_ne_top k V P h, end variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw set_like.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw set_like.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_finset_right_ne {s : finset P} {p : P} (hp : p ∈ s) : vector_span k (s : set P) = submodule.span k ((s.erase p).image (-ᵥ p)) := by simp [vector_span_eq_span_vsub_set_right_ne _ (finset.mem_coe.mpr hp)] /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s /-- The affine span of a nonempty set is nonempty. -/ instance {s : set P} [nonempty s] : nonempty (affine_span k s) := ((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_vadd] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace
0c1145096a2924538c1f03a029ed7747e9efc5b2
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/metric_space/cau_seq_filter.lean
1ecaab4fd90129c1e11f078cbe663c0c07dbaca5
[ "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
19,717
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, Sébastien Gouëzel Characterize completeness of metric spaces in terms of Cauchy sequences. In particular, reconcile the filter notion of Cauchy-ness with the cau_seq notion on normed spaces. -/ import topology.uniform_space.basic analysis.normed_space.basic data.real.cau_seq analysis.specific_limits import tactic.linarith universes u v open set filter classical emetric open_locale topological_space variable {β : Type v} /- We show that a metric space in which all Cauchy sequences converge is complete, i.e., all Cauchy filters converge. For this, we approximate any Cauchy filter by a Cauchy sequence, taking advantage of the fact that there is a sequence tending to `0` in ℝ. The proof also gives a more precise result, that to get completeness it is enough to have the convergence of all sequence that are Cauchy in a fixed quantitative sense, for instance satisfying `dist (u n) (u m) < 2^{- min m n}`. The classical argument to obtain this criterion is to start from a Cauchy sequence, extract a subsequence that satisfies this property, deduce the convergence of the subsequence, and then the convergence of the original sequence. All this argument is completely bypassed by the following proof, which avoids any use of subsequences and is written partly in terms of filters. -/ namespace ennreal /-In this paragraph, we prove useful properties of the sequence `half_pow n := 2^{-n}` in ennreal. Some of them are instrumental in this file to get Cauchy sequences, but others are proved here only for use in further applications of the completeness criterion `emetric.complete_of_convergent_controlled_sequences` below. -/ /-- An auxiliary positive sequence that tends to `0` in `ennreal`, with good behavior. -/ noncomputable def half_pow (n : ℕ) : ennreal := ennreal.of_real ((1 / 2) ^ n) lemma half_pow_pos (n : ℕ) : 0 < half_pow n := begin have : (0 : real) < (1/2)^n := pow_pos (by norm_num) _, simpa [half_pow] using this end lemma half_pow_tendsto_zero : tendsto (λn, half_pow n) at_top (𝓝 0) := begin unfold half_pow, rw ← ennreal.of_real_zero, apply ennreal.tendsto_of_real, exact _root_.tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) end lemma half_pow_add_succ (n : ℕ) : half_pow (n+1) + half_pow (n+1) = half_pow n := begin have : (0 : real) ≤ (1/2)^(n+1) := (le_of_lt (pow_pos (by norm_num) _)), simp only [half_pow, eq.symm (ennreal.of_real_add this this)], apply congr_arg, simp only [pow_add, one_div_eq_inv, pow_one], ring, end lemma half_pow_mono (m k : ℕ) (h : m ≤ k) : half_pow k ≤ half_pow m := ennreal.of_real_le_of_real (pow_le_pow_of_le_one (by norm_num) (by norm_num) h) lemma edist_le_two_mul_half_pow [emetric_space β] {k l N : ℕ} (hk : N ≤ k) (hl : N ≤ l) {u : ℕ → β} (h : ∀n, edist (u n) (u (n+1)) ≤ half_pow n) : edist (u k) (u l) ≤ 2 * half_pow N := begin have ineq_rec : ∀m, ∀k≥m, half_pow k + edist (u m) (u (k+1)) ≤ 2 * half_pow m, { assume m, refine nat.le_induction _ (λk km hk, _), { calc half_pow m + edist (u m) (u (m+1)) ≤ half_pow m + half_pow m : add_le_add_left' (h m) ... = 2 * half_pow m : by simp [(mul_two _).symm, mul_comm] }, { calc half_pow (k + 1) + edist (u m) (u (k + 1 + 1)) ≤ half_pow (k+1) + (edist (u m) (u (k+1)) + edist (u (k+1)) (u (k+2))) : add_le_add_left' (edist_triangle _ _ _) ... ≤ half_pow (k+1) + (edist (u m) (u (k+1)) + half_pow (k+1)) : add_le_add_left' (add_le_add_left' (h (k+1))) ... = (half_pow(k+1) + half_pow(k+1)) + edist (u m) (u (k+1)) : by simp [add_comm] ... = half_pow k + edist (u m) (u (k+1)) : by rw half_pow_add_succ ... ≤ 2 * half_pow m : hk }}, have Imk : ∀m, ∀k≥m, edist (u m) (u k) ≤ 2 * half_pow m, { assume m k hk, by_cases h : m = k, { simp [h, le_of_lt (half_pow_pos k)] }, { have I : m < k := lt_of_le_of_ne hk h, have : 0 < k := lt_of_le_of_lt (nat.zero_le _) ‹m < k›, let l := nat.pred k, have : k = l+1 := (nat.succ_pred_eq_of_pos ‹0 < k›).symm, rw this, have : m ≤ l := begin rw this at I, apply nat.le_of_lt_succ I end, calc edist (u m) (u (l+1)) ≤ half_pow l + edist (u m) (u (l+1)) : le_add_left (le_refl _) ... ≤ 2 * half_pow m : ineq_rec m l ‹m ≤ l› }}, by_cases h : k ≤ l, { calc edist (u k) (u l) ≤ 2 * half_pow k : Imk k l h ... ≤ 2 * half_pow N : canonically_ordered_semiring.mul_le_mul (le_refl _) (half_pow_mono N k hk) }, { simp at h, calc edist (u k) (u l) = edist (u l) (u k) : edist_comm _ _ ... ≤ 2 * half_pow l : Imk l k (le_of_lt h) ... ≤ 2 * half_pow N : canonically_ordered_semiring.mul_le_mul (le_refl _) (half_pow_mono N l hl) } end lemma cauchy_seq_of_edist_le_half_pow [emetric_space β] {u : ℕ → β} (h : ∀n, edist (u n) (u (n+1)) ≤ half_pow n) : cauchy_seq u := begin refine emetric.cauchy_seq_iff_le_tendsto_0.2 ⟨λn:ℕ, 2 * half_pow n, ⟨_, _⟩⟩, { exact λk l N hk hl, edist_le_two_mul_half_pow hk hl h }, { have : tendsto (λn, 2 * half_pow n) at_top (𝓝 (2 * 0)) := ennreal.tendsto.mul_right half_pow_tendsto_zero (by simp), simpa using this } end end ennreal namespace sequentially_complete section /- We fix a cauchy filter `f`, and a bounding sequence `B` made of positive numbers. We will prove that, if all sequences satisfying `dist (u n) (u m) < B (min n m)` converge, then the cauchy filter `f` is converging. The idea is to construct from `f` a Cauchy sequence that satisfies this property, therefore converges, and then to deduce the convergence of `f` from this. We give the argument in the more general setting of emetric spaces, and specialize it to metric spaces at the end. -/ variables [emetric_space β] {f : filter β} (hf : cauchy f) (B : ℕ → ennreal) (hB : ∀n, 0 < B n) open ennreal /--Auxiliary sequence, which is bounded by `B`, positive, and tends to `0`.-/ noncomputable def B2 (B : ℕ → ennreal) (n : ℕ) := (half_pow n) ⊓ (B n) lemma B2_pos (hB : ∀n, 0 < B n) (n : ℕ) : 0 < B2 B n := by unfold B2; simp [half_pow_pos n, hB n] lemma B2_lim : tendsto (λn, B2 B n) at_top (𝓝 0) := begin have : ∀n, B2 B n ≤ half_pow n := λn, lattice.inf_le_left, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds half_pow_tendsto_zero (by simp) (by simp [this]) end /-- Define a decreasing sequence of sets in the filter `f`, of diameter bounded by `B2 n`. -/ def set_seq_of_cau_filter : ℕ → set β | 0 := some ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0)) | (n+1) := (set_seq_of_cau_filter n) ∩ some ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n + 1))) /-- These sets are in the filter. -/ lemma set_seq_of_cau_filter_mem_sets : ∀ n, set_seq_of_cau_filter hf B hB n ∈ f | 0 := some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0))) | (n+1) := inter_mem_sets (set_seq_of_cau_filter_mem_sets n) (some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n + 1))))) /-- These sets are nonempty. -/ lemma set_seq_of_cau_filter_inhabited (n : ℕ) : ∃ x, x ∈ set_seq_of_cau_filter hf B hB n := inhabited_of_mem_sets (emetric.cauchy_iff.1 hf).1 (set_seq_of_cau_filter_mem_sets hf B hB n) /-- By construction, their diameter is controlled by `B2 n`. -/ lemma set_seq_of_cau_filter_spec : ∀ n, ∀ {x y}, x ∈ set_seq_of_cau_filter hf B hB n → y ∈ set_seq_of_cau_filter hf B hB n → edist x y < B2 B n | 0 := some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB 0))) | (n+1) := λ x y hx hy, some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (B2_pos B hB (n+1)))) x y (mem_of_mem_inter_right hx) (mem_of_mem_inter_right hy) -- this must exist somewhere, no? private lemma mono_of_mono_succ_aux {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) (m : ℕ) : ∀ n, f (m + n) ≤ f m | 0 := le_refl _ | (k+1) := le_trans (h _) (mono_of_mono_succ_aux _) lemma mono_of_mono_succ {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) {m n : ℕ} (hmn : m ≤ n) : f n ≤ f m := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in by simpa [hk] using mono_of_mono_succ_aux f h m k lemma set_seq_of_cau_filter_monotone' (n : ℕ) : set_seq_of_cau_filter hf B hB (n+1) ⊆ set_seq_of_cau_filter hf B hB n := inter_subset_left _ _ /-- These sets are nested. -/ lemma set_seq_of_cau_filter_monotone {n k : ℕ} (hle : n ≤ k) : set_seq_of_cau_filter hf B hB k ⊆ set_seq_of_cau_filter hf B hB n := mono_of_mono_succ (set_seq_of_cau_filter hf B hB) (set_seq_of_cau_filter_monotone' hf B hB) hle /-- Define the approximating Cauchy sequence for the Cauchy filter `f`, obtained by taking a point in each set. -/ noncomputable def seq_of_cau_filter (n : ℕ) : β := some (set_seq_of_cau_filter_inhabited hf B hB n) /-- The approximating sequence indeed belong to our good sets. -/ lemma seq_of_cau_filter_mem_set_seq (n : ℕ) : seq_of_cau_filter hf B hB n ∈ set_seq_of_cau_filter hf B hB n := some_spec (set_seq_of_cau_filter_inhabited hf B hB n) /-- The distance between points in the sequence is bounded by `B2 N`. -/ lemma seq_of_cau_filter_bound {N n k : ℕ} (hn : N ≤ n) (hk : N ≤ k) : edist (seq_of_cau_filter hf B hB n) (seq_of_cau_filter hf B hB k) < B2 B N := set_seq_of_cau_filter_spec hf B hB N (set_seq_of_cau_filter_monotone hf B hB hn (seq_of_cau_filter_mem_set_seq hf B hB n)) (set_seq_of_cau_filter_monotone hf B hB hk (seq_of_cau_filter_mem_set_seq hf B hB k)) /-- The approximating sequence is indeed Cauchy as `B2 n` tends to `0` with `n`. -/ lemma seq_of_cau_filter_is_cauchy : cauchy_seq (seq_of_cau_filter hf B hB) := emetric.cauchy_seq_iff_le_tendsto_0.2 ⟨B2 B, λ n m N hn hm, le_of_lt (seq_of_cau_filter_bound hf B hB hn hm), B2_lim B⟩ /-- If the approximating Cauchy sequence is converging, to a limit `y`, then the original Cauchy filter `f` is also converging, to the same limit. Given `t1` in the filter `f` and `t2` a neighborhood of `y`, it suffices to show that `t1 ∩ t2` is nonempty. Pick `ε` so that the ε-eball around `y` is contained in `t2`. Pick `n` with `B2 n < ε/2`, and `n2` such that `dist(seq n2, y) < ε/2`. Let `N = max(n, n2)`. We defined `seq` by looking at a decreasing sequence of sets of `f` with shrinking radius. The Nth one has radius `< B2 N < ε/2`. This set is in `f`, so we can find an element `x` that's also in `t1`. `dist(x, seq N) < ε/2` since `seq N` is in this set, and `dist (seq N, y) < ε/2`, so `x` is in the ε-ball around `y`, and thus in `t2`. -/ lemma le_nhds_cau_filter_lim {y : β} (H : tendsto (seq_of_cau_filter hf B hB) at_top (𝓝 y)) : f ≤ 𝓝 y := begin refine (le_nhds_iff_adhp_of_cauchy hf).2 _, refine forall_sets_neq_empty_iff_neq_bot.1 (λs hs, _), rcases filter.mem_inf_sets.2 hs with ⟨t1, ht1, t2, ht2, ht1t2⟩, rcases emetric.mem_nhds_iff.1 ht2 with ⟨ε, hε, ht2'⟩, cases emetric.cauchy_iff.1 hf with hfb _, have : ε / 2 > 0 := ennreal.half_pos hε, rcases inhabited_of_mem_sets (by simp) ((tendsto_orderable.1 (B2_lim B)).2 _ this) with ⟨n, hnε⟩, simp only [set.mem_set_of_eq] at hnε, -- hnε : ε / 2 > B2 B hB n cases (emetric.tendsto_at_top _).1 H _ this with n2 hn2, let N := max n n2, have ht1sn : t1 ∩ set_seq_of_cau_filter hf B hB N ∈ f, from inter_mem_sets ht1 (set_seq_of_cau_filter_mem_sets hf B hB _), have hts1n_ne : t1 ∩ set_seq_of_cau_filter hf B hB N ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.2 hfb _ ht1sn, cases exists_mem_of_ne_empty hts1n_ne with x hx, -- x : β, hx : x ∈ t1 ∩ set_seq_of_cau_filter hf B hB N -- we still have to show that x ∈ t2, i.e., edist x y < ε have I1 : seq_of_cau_filter hf B hB N ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) (seq_of_cau_filter_mem_set_seq hf B hB N), have I2 : x ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) hx.2, have hdist1 : edist x (seq_of_cau_filter hf B hB N) < B2 B n := set_seq_of_cau_filter_spec hf B hB _ I2 I1, have hdist2 : edist (seq_of_cau_filter hf B hB N) y < ε / 2 := hn2 N (le_max_right _ _), have hdist : edist x y < ε := calc edist x y ≤ edist x (seq_of_cau_filter hf B hB N) + edist (seq_of_cau_filter hf B hB N) y : edist_triangle _ _ _ ... < B2 B n + ε/2 : ennreal.add_lt_add hdist1 hdist2 ... ≤ ε/2 + ε/2 : add_le_add_right' (le_of_lt hnε) ... = ε : ennreal.add_halves _, have hxt2 : x ∈ t2, from ht2' hdist, exact ne_empty_iff_exists_mem.2 ⟨x, ht1t2 (mem_inter hx.left hxt2)⟩ end end end sequentially_complete /-- An emetric space in which every Cauchy sequence converges is complete. -/ theorem complete_of_cauchy_seq_tendsto {α : Type u} [emetric_space α] (H : ∀u : ℕ → α, cauchy_seq u → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f` intros f hf, -- Introduce a sequence `u` approximating the filter `f`. We don't need the bound `B`, -- so take for instance `B n = 1` for all `n`. let u := sequentially_complete.seq_of_cau_filter hf (λn, 1) (λn, ennreal.zero_lt_one), -- It is Cauchy. have : cauchy_seq u := sequentially_complete.seq_of_cau_filter_is_cauchy hf (λn, 1) (λn, ennreal.zero_lt_one), -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf (λn, 1) (λn, ennreal.zero_lt_one) hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem emetric.complete_of_convergent_controlled_sequences {α : Type u} [emetric_space α] (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f`. intros f hf, -- Introduce a sequence `u` approximating the filter `f`. let u := sequentially_complete.seq_of_cau_filter hf B hB, -- It satisfies the required bound. have : ∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N := λN n m hn hm, calc edist (u n) (u m) < sequentially_complete.B2 B N : sequentially_complete.seq_of_cau_filter_bound hf B hB hn hm ... ≤ B N : lattice.inf_le_right, -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf B hB hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences {α : Type u} [metric_space α] (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, have Z := Hu N n m hn hm, rw [edist_dist, ennreal.of_real_lt_of_real_iff] at Z, exact Z, exact hB N } end section /- Now, we will apply these results to `cau_seq`, i.e., "Cauchy sequences" defined by a multiplicative absolute value on normed fields. -/ lemma tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)] (f : cau_seq β norm) [cau_seq.is_complete β norm] : tendsto f at_top (𝓝 f.lim) := _root_.tendsto_nhds.mpr begin intros s os lfs, suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this, rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩, cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN, existsi N, intros b hb, apply hεs, dsimp [metric.ball], rw [dist_comm, dist_eq_norm], solve_by_elim end variables [normed_field β] /- This section shows that if we have a uniform space generated by an absolute value, topological completeness and Cauchy sequence completeness coincide. The problem is that there isn't a good notion of "uniform space generated by an absolute value", so right now this is specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_field. This needs to be fixed, since it prevents showing that ℤ_[hp] is complete -/ instance normed_field.is_absolute_value : is_absolute_value (norm : β → ℝ) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_add_le, abv_mul := normed_field.norm_mul } open metric lemma cauchy_of_filter_cauchy (f : ℕ → β) (hf : cauchy_seq f) : is_cau_seq norm f := begin cases cauchy_iff.1 hf with hf1 hf2, intros ε hε, rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩, simp at ht, cases ht with N hN, existsi N, intros j hj, rw ←dist_eq_norm, apply @htsub (f j, f N), apply set.mk_mem_prod; solve_by_elim [le_refl] end lemma filter_cauchy_of_cauchy (f : cau_seq β norm) : cauchy_seq f := begin apply cauchy_iff.2, split, { exact map_ne_bot at_top_ne_bot }, { intros s hs, rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩, cases cau_seq.cauchy₂ f hε with N hN, existsi {n | n ≥ N}.image f, simp, split, { existsi N, intros b hb, existsi b, simp [hb] }, { rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩, dsimp at ha'1 ha'2 hb'1 hb'2, rw [←ha'2, ←hb'2], apply hεs, rw dist_eq_norm, apply hN; assumption }}, end /-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/ lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} : is_cau_seq norm u ↔ cauchy_seq u := ⟨λh, filter_cauchy_of_cauchy ⟨u, h⟩, λh, cauchy_of_filter_cauchy u h⟩ /-- A complete normed field is complete as a metric space, as Cauchy sequences converge by assumption and this suffices to characterize completeness. -/ @[priority 100] -- see Note [lower instance priority] instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β := begin apply complete_of_cauchy_seq_tendsto, assume u hu, have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu, existsi cau_seq.lim ⟨u, C⟩, rw metric.tendsto_at_top, assume ε εpos, cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN, existsi N, simpa [dist_eq_norm] using hN end end
47b10a3735a32e1087b4992824c03f8a304be05a
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/set/comm_semiring.lean
7d4e5fc3117fa08ae27f63c7955023f2e28f1450
[ "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
856
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura (set A) is an instance of a commutative semiring -/ import data.set.basic algebra.ring open set definition set_comm_semiring [instance] (A : Type) : comm_semiring (set A) := ⦃ comm_semiring, add := union, mul := inter, zero := empty, one := univ, add_assoc := union_assoc, add_comm := union_comm, zero_add := empty_union, add_zero := union_empty, mul_assoc := inter_assoc, mul_comm := inter_comm, zero_mul := empty_inter, mul_zero := inter_empty, one_mul := univ_inter, mul_one := inter_univ, left_distrib := inter_distrib_left, right_distrib := inter_distrib_right ⦄
d64d3b4fc6b22377c9cdcb7ba1c91979cdd08076
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level16.lean
9fe86658c4e638f937cfdb075b3ad83620e3d820
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
232
lean
lemma lt_aux_two (a b : mynat) : succ a ≤ b → a ≤ b ∧ ¬ (b ≤ a) := begin intro h, split, apply le_trans _ (succ a), exact le_succ_self a, exact h, intro h2, apply not_succ_le_self a, exact le_trans (succ a) b a h h2, end
10f6d7415859868a4a31497df14da2c84b3bd9b4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/shapes/constructions/preserve_binary_products.lean
84912f69bac7eab36a33ff91181ed7f2bba0077c
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
3,445
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.limits import category_theory.limits.preserves import category_theory.limits.shapes.binary_products /-! Show that a functor `F : C ⥤ D` preserves binary products if and only if `⟨Fπ₁, Fπ₂⟩ : F (A ⨯ B) ⟶ F A ⨯ F B` (that is, `prod_comparison`) is an isomorphism for all `A, B`. -/ open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables [has_binary_products D] (F : C ⥤ D) /-- (Implementation). Construct a cone for `pair A B ⋙ F` which we will show is limiting. -/ @[simps] def alternative_cone (A B : C) : cone (pair A B ⋙ F) := { X := F.obj A ⨯ F.obj B, π := discrete.nat_trans (λ j, walking_pair.cases_on j limits.prod.fst limits.prod.snd)} /-- (Implementation). Show that we have a limit for the shape `pair A B ⋙ F`. -/ def alternative_cone_is_limit (A B : C) : is_limit (alternative_cone F A B) := { lift := λ s, prod.lift (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := λ s j, walking_pair.cases_on j (prod.lift_fst _ _) (prod.lift_snd _ _), uniq' := λ s m w, prod.hom_ext (by { rw prod.lift_fst, apply w walking_pair.left }) (by { rw prod.lift_snd, apply w walking_pair.right }) } variable [has_binary_products C] /-- If `prod_comparison F A B` is an iso, then `F` preserves the limit `A ⨯ B`. -/ def preserves_binary_prod_of_prod_comparison_iso (A B : C) [is_iso (prod_comparison F A B)] : preserves_limit (pair A B) F := preserves_limit_of_preserves_limit_cone (limit.is_limit (pair A B)) begin apply is_limit.of_iso_limit (alternative_cone_is_limit F A B) _, apply cones.ext _ _, { apply (as_iso (prod_comparison F A B)).symm }, { rintro ⟨j⟩, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_fst _ _) }, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_snd _ _) } }, end /-- If `prod_comparison F A B` is an iso for all `A, B` , then `F` preserves binary products. -/ instance preserves_binary_prods_of_prod_comparison_iso [∀ A B, is_iso (prod_comparison F A B)] : preserves_limits_of_shape (discrete walking_pair) F := { preserves_limit := λ K, begin haveI := preserves_binary_prod_of_prod_comparison_iso F (K.obj walking_pair.left) (K.obj walking_pair.right), apply preserves_limit_of_iso F (diagram_iso_pair K).symm, end } variables [preserves_limits_of_shape (discrete walking_pair) F] /-- The product comparison isomorphism. Technically a special case of `preserves_limit_iso`, but this version is convenient to have. -/ instance prod_comparison_iso_of_preserves_binary_prods (A B : C) : is_iso (prod_comparison F A B) := let t : is_limit (F.map_cone _) := preserves_limit.preserves (limit.is_limit (pair A B)) in { inv := t.lift (alternative_cone F A B), hom_inv_id' := begin apply is_limit.hom_ext t, rintro ⟨j⟩, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_fst }, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_snd }, end, inv_hom_id' := by ext ⟨j⟩; { simpa [prod_comparison] using t.fac _ _ } } end category_theory.limits
f711bb748711d5c61ce4399afbd46ece6a960a53
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_310.lean
da35669870a0b65ed021225bcffb9882c8faa3a9
[]
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
202
lean
import data.set.basic variable {α : Type*} variables (s t u : set α) -- BEGIN example : s ∩ t = t ∩ s := set.ext $ λ x, ⟨λ ⟨xs, xt⟩, ⟨xt, xs⟩, λ ⟨xt, xs⟩, ⟨xs, xt⟩⟩ -- END
e2dbee065db4353ab0ddc58519c9e4ffd064a2bd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/metric_space/gromov_hausdorff.lean
4b71c30b5d6f000b8b91d9ce154c11253ddbf9c4
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,214
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.closeds import Mathlib.set_theory.cardinal import Mathlib.topology.metric_space.gromov_hausdorff_realized import Mathlib.topology.metric_space.completion import Mathlib.PostPort universes u v w l namespace Mathlib /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ namespace Gromov_Hausdorff /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ /-- This is indeed an equivalence relation -/ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ protected instance isometry_rel.setoid : setoid (topological_space.nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ def GH_space := quotient isometry_rel.setoid /-- Map any nonempty compact type to `GH_space` -/ def to_GH_space (α : Type u) [metric_space α] [compact_space α] [Nonempty α] : GH_space := quotient.mk (nonempty_compacts.Kuratowski_embedding α) protected instance GH_space.inhabited : Inhabited GH_space := { default := Quot.mk setoid.r { val := singleton 0, property := sorry } } /-- A metric space representative of any abstract point in `GH_space` -/ def GH_space.rep (p : GH_space) := ↥(subtype.val (quot.out p)) theorem eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [Nonempty α] {p : topological_space.nonempty_compacts ℓ_infty_ℝ} : quotient.mk p = to_GH_space α ↔ ∃ (Ψ : α → ℓ_infty_ℝ), isometry Ψ ∧ set.range Ψ = subtype.val p := sorry theorem eq_to_GH_space {p : topological_space.nonempty_compacts ℓ_infty_ℝ} : quotient.mk p = to_GH_space ↥(subtype.val p) := iff.mpr eq_to_GH_space_iff (Exists.intro (fun (x : ↥(subtype.val p)) => ↑x) { left := isometry_subtype_coe, right := subtype.range_coe }) protected instance rep_GH_space_metric_space {p : GH_space} : metric_space (GH_space.rep p) := subtype.metric_space protected instance rep_GH_space_compact_space {p : GH_space} : compact_space (GH_space.rep p) := topological_space.nonempty_compacts.to_compact_space protected instance rep_GH_space_nonempty {p : GH_space} : Nonempty (GH_space.rep p) := topological_space.nonempty_compacts.to_nonempty theorem GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (GH_space.rep p) = p := id (eq.mpr (id (Eq._oldrec (Eq.refl (to_GH_space ↥(subtype.val (quot.out p)) = p)) (Eq.symm eq_to_GH_space))) (quot.out_eq p)) /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ theorem to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [Nonempty α] {β : Type u} [metric_space β] [compact_space β] [Nonempty β] : to_GH_space α = to_GH_space β ↔ Nonempty (α ≃ᵢ β) := sorry /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ protected instance GH_space.has_dist : has_dist GH_space := has_dist.mk fun (x y : GH_space) => Inf ((fun (p : topological_space.nonempty_compacts ℓ_infty_ℝ × topological_space.nonempty_compacts ℓ_infty_ℝ) => metric.Hausdorff_dist (subtype.val (prod.fst p)) (subtype.val (prod.snd p))) '' set.prod (set_of fun (a : topological_space.nonempty_compacts ℓ_infty_ℝ) => quotient.mk a = x) (set_of fun (b : topological_space.nonempty_compacts ℓ_infty_ℝ) => quotient.mk b = y)) /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (α : Type u) (β : Type v) [metric_space α] [Nonempty α] [compact_space α] [metric_space β] [Nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β) theorem dist_GH_dist (p : GH_space) (q : GH_space) : dist p q = GH_dist (GH_space.rep p) (GH_space.rep q) := sorry /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [Nonempty α] {β : Type v} [metric_space β] [compact_space β] [Nonempty β] {γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist α β ≤ metric.Hausdorff_dist (set.range Φ) (set.range Ψ) := sorry /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ theorem Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [Nonempty α] {β : Type v} [metric_space β] [compact_space β] [Nonempty β] : metric.Hausdorff_dist (set.range (optimal_GH_injl α β)) (set.range (optimal_GH_injr α β)) = GH_dist α β := sorry /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [Nonempty α] (β : Type v) [metric_space β] [compact_space β] [Nonempty β] : ∃ (Φ : α → ℓ_infty_ℝ), ∃ (Ψ : β → ℓ_infty_ℝ), isometry Φ ∧ isometry Ψ ∧ GH_dist α β = metric.Hausdorff_dist (set.range Φ) (set.range Ψ) := sorry -- without the next two lines, `{ exact hΦ.is_closed }` in the next -- proof is very slow, as the `t2_space` instance is very hard to find /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ protected instance GH_space_metric_space : metric_space GH_space := sorry end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ def topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α] (p : topological_spa
411ac44edf1a3db933cbb715f59fc325acceef49
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ind4.lean
6933539063f43a3a3fc5e1d3e656f8602e76dea8
[ "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
378
lean
section variable A : Type inductive list : Type := | nil : list | cons : A → list → list end check list.{1} check list.cons.{1} section variable A : Type inductive tree : Type := | node : A → forest → tree with forest : Type := | fnil : forest | fcons : tree → forest → forest check tree check forest end check tree.{1} check forest.{1}