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
89e37ca04902eb2b91af07b88cb25bcb51936829
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/data/rat/cast.lean
660945dccffb73e5dcc9a845dc3220f3ccddfb62
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
12,284
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem mul_cast_comm (a : α) : ∀ (n : ℚ), a * n = n * a | ⟨n, d, h, c⟩ := show a * (n * d⁻¹) = n * d⁻¹ * a, by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc, ← show (d:α)⁻¹ * a = a * d⁻¹, from inv_comm_of_comm' (int.mul_cast_comm a d).symm] @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, ← nat.mul_cast_comm], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [inv_comm_of_comm'], exact (nat.mul_cast_comm _ _).symm end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, inv_comm_of_comm', ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h, exact (nat.mul_cast_comm _ _) end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv @[simp, norm_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div @[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, norm_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by conv_lhs { rw [← @num_denom r, mk_eq_div, int.cast_coe_nat] } ... = (f.comp $ int.cast_ring_hom ℚ) r.1 / (f.comp $ nat.cast_ring_hom ℚ) r.2 : f.map_div ... = r.1 / r.2 : by rw [eq_nat_cast, eq_int_cast] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer lemma ring_hom.map_rat_cast {k k'} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : f r = r := (f.comp (cast_hom k)).eq_rat_cast r lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩
b659521f262f9e8762edd457f4757a0948711b2c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/multiset/fold.lean
9adcacde43569524d8ceca15f2a0ab8be487d398
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,672
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.dedup import data.list.min_max /-! # The fold operation for a commutative associative operation over a multiset. -/ namespace multiset variables {α β : Type*} /-! ### fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation (name := op) a ` * ` b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a ::ₘ s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a ::ₘ s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a ::ₘ s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a ::ₘ s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_bind {ι : Type*} (s : multiset ι) (t : ι → multiset α) (b : ι → α) (b₀ : α) : (s.bind t).fold op ((s.map b).fold op b₀) = (s.map (λ i, (t i).fold op (b i))).fold op b₀ := begin induction s using multiset.induction_on with a ha ih, { rw [zero_bind, map_zero, map_zero, fold_zero] }, { rw [cons_bind, map_cons, map_cons, fold_cons_left, fold_cons_left, fold_add, ih] }, end theorem fold_singleton (b a : α) : ({a} : multiset α).fold op b = a * b := foldr_singleton _ _ _ _ theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_dedup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (dedup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold section order lemma max_le_of_forall_le {α : Type*} [canonically_linear_ordered_add_monoid α] (l : multiset α) (n : α) (h : ∀ (x ∈ l), x ≤ n) : l.fold max ⊥ ≤ n := begin induction l using quotient.induction_on, simpa using list.max_le_of_forall_le _ _ h end lemma max_nat_le_of_forall_le (l : multiset ℕ) (n : ℕ) (h : ∀ (x ∈ l), x ≤ n) : l.fold max 0 ≤ n := max_le_of_forall_le l n h end order open nat theorem le_smul_dedup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • dedup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_nsmul, by_cases a ∈ s, { refine le_trans _ (nat.mul_le_mul_left _ $ count_pos.2 $ mem_dedup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a ::ₘ erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ end multiset
2f310373e69d43be5fbe0fcfe9de09bc7f1378b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/succ_pred/interval_succ.lean
b2a00b4e2f07066287f0163ff504abb85f73f25c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,016
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.set.pairwise.basic import order.succ_pred.basic /-! # Intervals `Ixx (f x) (f (order.succ x))` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove * `monotone.bUnion_Ico_Ioc_map_succ`: if `α` is a linear archimedean succ order and `β` is a linear order, then for any monotone function `f` and `m n : α`, the union of intervals `set.Ioc (f i) (f (order.succ i))`, `m ≤ i < n`, is equal to `set.Ioc (f m) (f n)`; * `monotone.pairwise_disjoint_on_Ioc_succ`: if `α` is a linear succ order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ioc (f n) (f (order.succ n))` are pairwise disjoint. For the latter lemma, we also prove various order dual versions. -/ open set order variables {α β : Type*} [linear_order α] namespace monotone /-- If `α` is a linear archimedean succ order and `β` is a linear order, then for any monotone function `f` and `m n : α`, the union of intervals `set.Ioc (f i) (f (order.succ i))`, `m ≤ i < n`, is equal to `set.Ioc (f m) (f n)` -/ lemma bUnion_Ico_Ioc_map_succ [succ_order α] [is_succ_archimedean α] [linear_order β] {f : α → β} (hf : monotone f) (m n : α) : (⋃ i ∈ Ico m n, Ioc (f i) (f (succ i))) = Ioc (f m) (f n) := begin cases le_total n m with hnm hmn, { rw [Ico_eq_empty_of_le hnm, Ioc_eq_empty_of_le (hf hnm), bUnion_empty] }, { refine succ.rec _ _ hmn, { simp only [Ioc_self, Ico_self, bUnion_empty] }, { intros k hmk ihk, rw [← Ioc_union_Ioc_eq_Ioc (hf hmk) (hf $ le_succ _), union_comm, ← ihk], by_cases hk : is_max k, { rw [hk.succ_eq, Ioc_self, empty_union] }, { rw [Ico_succ_right_eq_insert_of_not_is_max hmk hk, bUnion_insert] } } } end /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ioc (f n) (f (order.succ n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioc_succ [succ_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ioc (f n) (f (succ n)))) := (pairwise_disjoint_on _).2 $ λ m n hmn, disjoint_iff_inf_le.mpr $ λ x ⟨⟨_, h₁⟩, ⟨h₂, _⟩⟩, h₂.not_le $ h₁.trans $ hf $ succ_le_of_lt hmn /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ico (f n) (f (order.succ n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ico_succ [succ_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ico (f n) (f (succ n)))) := (pairwise_disjoint_on _).2 $ λ m n hmn, disjoint_iff_inf_le.mpr $ λ x ⟨⟨_, h₁⟩, ⟨h₂, _⟩⟩, h₁.not_le $ (hf $ succ_le_of_lt hmn).trans h₂ /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ioo (f n) (f (order.succ n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioo_succ [succ_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ioo (f n) (f (succ n)))) := hf.pairwise_disjoint_on_Ico_succ.mono $ λ i j h, h.mono Ioo_subset_Ico_self Ioo_subset_Ico_self /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ioc (f order.pred n) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioc_pred [pred_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ioc (f (pred n)) (f n))) := by simpa only [(∘), dual_Ico] using hf.dual.pairwise_disjoint_on_Ico_succ /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ico (f order.pred n) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ico_pred [pred_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ico (f (pred n)) (f n))) := by simpa only [(∘), dual_Ioc] using hf.dual.pairwise_disjoint_on_Ioc_succ /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is a monotone function, then the intervals `set.Ioo (f order.pred n) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioo_pred [pred_order α] [preorder β] {f : α → β} (hf : monotone f) : pairwise (disjoint on (λ n, Ioo (f (pred n)) (f n))) := by simpa only [(∘), dual_Ioo] using hf.dual.pairwise_disjoint_on_Ioo_succ end monotone namespace antitone /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ioc (f (order.succ n)) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioc_succ [succ_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ioc (f (succ n)) (f n))) := hf.dual_left.pairwise_disjoint_on_Ioc_pred /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ico (f (order.succ n)) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ico_succ [succ_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ico (f (succ n)) (f n))) := hf.dual_left.pairwise_disjoint_on_Ico_pred /-- If `α` is a linear succ order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ioo (f (order.succ n)) (f n)` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioo_succ [succ_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ioo (f (succ n)) (f n))) := hf.dual_left.pairwise_disjoint_on_Ioo_pred /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ioc (f n) (f (order.pred n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioc_pred [pred_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ioc (f n) (f (pred n)))) := hf.dual_left.pairwise_disjoint_on_Ioc_succ /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ico (f n) (f (order.pred n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ico_pred [pred_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ico (f n) (f (pred n)))) := hf.dual_left.pairwise_disjoint_on_Ico_succ /-- If `α` is a linear pred order, `β` is a preorder, and `f : α → β` is an antitone function, then the intervals `set.Ioo (f n) (f (order.pred n))` are pairwise disjoint. -/ lemma pairwise_disjoint_on_Ioo_pred [pred_order α] [preorder β] {f : α → β} (hf : antitone f) : pairwise (disjoint on (λ n, Ioo (f n) (f (pred n)))) := hf.dual_left.pairwise_disjoint_on_Ioo_succ end antitone
3c85762063544b86c64121f31b47d8faa93ee7d5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/dfinsupp/well_founded.lean
a51551fba65f5cfdc503ef282796c306fe5b3cb9
[ "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
11,119
lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import data.dfinsupp.lex import order.game_add import order.antisymmetrization import set_theory.ordinal.basic /-! # Well-foundedness of the lexicographic and product orders on `dfinsupp` and `pi` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The primary results are `dfinsupp.lex.well_founded` and the two variants that follow it, which essentially say that if `(>)` is a well order on `ι`, `(<)` is well-founded on each `α i`, and `0` is a bottom element in `α i`, then the lexicographic `(<)` is well-founded on `Π₀ i, α i`. The proof is modelled on the proof of `well_founded.cut_expand`. The results are used to prove `pi.lex.well_founded` and two variants, which say that if `ι` is finite and equipped with a linear order and `(<)` is well-founded on each `α i`, then the lexicographic `(<)` is well-founded on `Π i, α i`, and the same is true for `Π₀ i, α i` (`dfinsupp.lex.well_founded_of_finite`), because `dfinsupp` is order-isomorphic to `pi` when `ι` is finite. Finally, we deduce `dfinsupp.well_founded_lt`, `pi.well_founded_lt`, `dfinsupp.well_founded_lt_of_finite` and variants, which concern the product order rather than the lexicographic one. An order on `ι` is not required in these results, but we deduce them from the well-foundedness of the lexicographic order by choosing a well order on `ι` so that the product order `(<)` becomes a subrelation of the lexicographic `(<)`. All results are provided in two forms whenever possible: a general form where the relations can be arbitrary (not the `(<)` of a preorder, or not even transitive, etc.) and a specialized form provided as `well_founded_lt` instances where the `(d)finsupp/pi` type (or their `lex` type synonyms) carries a natural `(<)`. Notice that the definition of `dfinsupp.lex` says that `x < y` according to `dfinsupp.lex r s` iff there exists a coordinate `i : ι` such that `x i < y i` according to `s i`, and at all `r`-smaller coordinates `j` (i.e. satisfying `r j i`), `x` remains unchanged relative to `y`; in other words, coordinates `j` such that `¬ r j i` and `j ≠ i` are exactly where changes can happen arbitrarily. This explains the appearance of `rᶜ ⊓ (≠)` in `dfinsupp.acc_single` and `dfinsupp.well_founded`. When `r` is trichotomous (e.g. the `(<)` of a linear order), `¬ r j i ∧ j ≠ i` implies `r i j`, so it suffices to require `r.swap` to be well-founded. -/ variables {ι : Type*} {α : ι → Type*} namespace dfinsupp variables [hz : Π i, has_zero (α i)] (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) include hz open relation prod /-- This key lemma says that if a finitely supported dependent function `x₀` is obtained by merging two such functions `x₁` and `x₂`, and if we evolve `x₀` down the `dfinsupp.lex` relation one step and get `x`, we can always evolve one of `x₁` and `x₂` down the `dfinsupp.lex` relation one step while keeping the other unchanged, and merge them back (possibly in a different way) to get back `x`. In other words, the two parts evolve essentially independently under `dfinsupp.lex`. This is used to show that a function `x` is accessible if `dfinsupp.single i (x i)` is accessible for each `i` in the (finite) support of `x` (`dfinsupp.lex.acc_of_single`). -/ lemma lex_fibration [Π i (s : set ι), decidable (i ∈ s)] : fibration (inv_image (game_add (dfinsupp.lex r s) (dfinsupp.lex r s)) snd) (dfinsupp.lex r s) (λ x, piecewise x.2.1 x.2.2 x.1) := begin rintro ⟨p, x₁, x₂⟩ x ⟨i, hr, hs⟩, simp_rw [piecewise_apply] at hs hr, split_ifs at hs, classical, work_on_goal 1 { refine ⟨⟨{j | r j i → j ∈ p}, piecewise x₁ x {j | r j i}, x₂⟩, game_add.fst ⟨i, _⟩, _⟩ }, work_on_goal 3 { refine ⟨⟨{j | r j i ∧ j ∈ p}, x₁, piecewise x₂ x {j | r j i}⟩, game_add.snd ⟨i, _⟩, _⟩ }, swap 3, iterate 2 { simp_rw piecewise_apply, refine ⟨λ j h, if_pos h, _⟩, convert hs, refine ite_eq_right_iff.2 (λ h', (hr i h').symm ▸ _), rw if_neg h <|> rw if_pos h }, all_goals { ext j, simp_rw piecewise_apply, split_ifs with h₁ h₂ }, { rw [hr j h₂, if_pos (h₁ h₂)] }, { refl }, { rw [set.mem_set_of, not_imp] at h₁, rw [hr j h₁.1, if_neg h₁.2] }, { rw [hr j h₁.1, if_pos h₁.2] }, { rw [hr j h₂, if_neg (λ h', h₁ ⟨h₂, h'⟩)] }, { refl }, end variables {r s} lemma lex.acc_of_single_erase [decidable_eq ι] {x : Π₀ i, α i} (i : ι) (hs : acc (dfinsupp.lex r s) $ single i (x i)) (hu : acc (dfinsupp.lex r s) $ x.erase i) : acc (dfinsupp.lex r s) x := begin classical, convert ← @acc.of_fibration _ _ _ _ _ (lex_fibration r s) ⟨{i}, _⟩ (inv_image.accessible snd $ hs.prod_game_add hu), convert piecewise_single_erase x i, end variable (hbot : ∀ ⦃i a⦄, ¬ s i a 0) include hbot lemma lex.acc_zero : acc (dfinsupp.lex r s) 0 := acc.intro 0 $ λ x ⟨_, _, h⟩, (hbot h).elim lemma lex.acc_of_single [decidable_eq ι] [Π i (x : α i), decidable (x ≠ 0)] (x : Π₀ i, α i) : (∀ i ∈ x.support, acc (dfinsupp.lex r s) $ single i (x i)) → acc (dfinsupp.lex r s) x := begin generalize ht : x.support = t, revert x, classical, induction t using finset.induction with b t hb ih, { intros x ht, rw support_eq_empty.1 ht, exact λ _, lex.acc_zero hbot }, refine λ x ht h, lex.acc_of_single_erase b (h b $ t.mem_insert_self b) _, refine ih _ (by rw [support_erase, ht, finset.erase_insert hb]) (λ a ha, _), rw [erase_ne (ha.ne_of_not_mem hb)], exact h a (finset.mem_insert_of_mem ha), end variable (hs : ∀ i, well_founded (s i)) include hs lemma lex.acc_single [decidable_eq ι] {i : ι} (hi : acc (rᶜ ⊓ (≠)) i) : ∀ a, acc (dfinsupp.lex r s) (single i a) := begin induction hi with i hi ih, refine λ a, (hs i).induction a (λ a ha, _), refine acc.intro _ (λ x, _), rintro ⟨k, hr, hs⟩, classical, rw single_apply at hs, split_ifs at hs with hik, swap, { exact (hbot hs).elim }, subst hik, refine lex.acc_of_single hbot x (λ j hj, _), obtain rfl | hij := eq_or_ne i j, { exact ha _ hs }, by_cases r j i, { rw [hr j h, single_eq_of_ne hij, single_zero], exact lex.acc_zero hbot }, { exact ih _ ⟨h, hij.symm⟩ _ }, end lemma lex.acc [decidable_eq ι] [Π i (x : α i), decidable (x ≠ 0)] (x : Π₀ i, α i) (h : ∀ i ∈ x.support, acc (rᶜ ⊓ (≠)) i) : acc (dfinsupp.lex r s) x := lex.acc_of_single hbot x $ λ i hi, lex.acc_single hbot hs (h i hi) _ theorem lex.well_founded (hr : well_founded $ rᶜ ⊓ (≠)) : well_founded (dfinsupp.lex r s) := ⟨λ x, by classical; exact lex.acc hbot hs x (λ i _, hr.apply i)⟩ theorem lex.well_founded' [is_trichotomous ι r] (hr : well_founded r.swap) : well_founded (dfinsupp.lex r s) := lex.well_founded hbot hs $ subrelation.wf (λ i j h, ((@is_trichotomous.trichotomous ι r _ i j).resolve_left h.1).resolve_left h.2) hr omit hz hbot hs instance lex.well_founded_lt [has_lt ι] [is_trichotomous ι (<)] [hι : well_founded_gt ι] [Π i, canonically_ordered_add_monoid (α i)] [hα : ∀ i, well_founded_lt (α i)] : well_founded_lt (lex (Π₀ i, α i)) := ⟨lex.well_founded' (λ i a, (zero_le a).not_lt) (λ i, (hα i).wf) hι.wf⟩ end dfinsupp open dfinsupp variables (r : ι → ι → Prop) {s : Π i, α i → α i → Prop} theorem pi.lex.well_founded [is_strict_total_order ι r] [finite ι] (hs : ∀ i, well_founded (s i)) : well_founded (pi.lex r s) := begin obtain h | ⟨⟨x⟩⟩ := is_empty_or_nonempty (Π i, α i), { convert empty_wf, ext1 x, exact (h.1 x).elim }, letI : Π i, has_zero (α i) := λ i, ⟨(hs i).min ⊤ ⟨x i, trivial⟩⟩, haveI := is_trans.swap r, haveI := is_irrefl.swap r, haveI := fintype.of_finite ι, refine inv_image.wf equiv_fun_on_fintype.symm (lex.well_founded' (λ i a, _) hs _), exacts [(hs i).not_lt_min ⊤ _ trivial, finite.well_founded_of_trans_of_irrefl r.swap], end instance pi.lex.well_founded_lt [linear_order ι] [finite ι] [Π i, has_lt (α i)] [hwf : ∀ i, well_founded_lt (α i)] : well_founded_lt (lex (Π i, α i)) := ⟨pi.lex.well_founded (<) (λ i, (hwf i).1)⟩ instance function.lex.well_founded_lt {α} [linear_order ι] [finite ι] [has_lt α] [well_founded_lt α] : well_founded_lt (lex (ι → α)) := pi.lex.well_founded_lt theorem dfinsupp.lex.well_founded_of_finite [is_strict_total_order ι r] [finite ι] [Π i, has_zero (α i)] (hs : ∀ i, well_founded (s i)) : well_founded (dfinsupp.lex r s) := have _ := fintype.of_finite ι, by exactI inv_image.wf equiv_fun_on_fintype (pi.lex.well_founded r hs) instance dfinsupp.lex.well_founded_lt_of_finite [linear_order ι] [finite ι] [Π i, has_zero (α i)] [Π i, has_lt (α i)] [hwf : ∀ i, well_founded_lt (α i)] : well_founded_lt (lex (Π₀ i, α i)) := ⟨dfinsupp.lex.well_founded_of_finite (<) $ λ i, (hwf i).1⟩ protected theorem dfinsupp.well_founded_lt [Π i, has_zero (α i)] [Π i, preorder (α i)] [∀ i, well_founded_lt (α i)] (hbot : ∀ ⦃i⦄ ⦃a : α i⦄, ¬ a < 0) : well_founded_lt (Π₀ i, α i) := ⟨begin letI : Π i, has_zero (antisymmetrization (α i) (≤)) := λ i, ⟨to_antisymmetrization (≤) 0⟩, let f := map_range (λ i, @to_antisymmetrization (α i) (≤) _) (λ i, rfl), refine subrelation.wf (λ x y h, _) (inv_image.wf f $ lex.well_founded' _ (λ i, _) _), { exact well_ordering_rel.swap }, { exact λ i, (<) }, { haveI := is_strict_order.swap (@well_ordering_rel ι), obtain ⟨i, he, hl⟩ := lex_lt_of_lt_of_preorder well_ordering_rel.swap h, exact ⟨i, λ j hj, quot.sound (he j hj), hl⟩ }, { rintro i ⟨a⟩, apply hbot }, exacts [is_well_founded.wf, is_trichotomous.swap _, is_well_founded.wf], end⟩ instance dfinsupp.well_founded_lt' [Π i, canonically_ordered_add_monoid (α i)] [∀ i, well_founded_lt (α i)] : well_founded_lt (Π₀ i, α i) := dfinsupp.well_founded_lt $ λ i a, (zero_le a).not_lt instance pi.well_founded_lt [finite ι] [Π i, preorder (α i)] [hw : ∀ i, well_founded_lt (α i)] : well_founded_lt (Π i, α i) := ⟨begin obtain h | ⟨⟨x⟩⟩ := is_empty_or_nonempty (Π i, α i), { convert empty_wf, ext1 x, exact (h.1 x).elim }, letI : Π i, has_zero (α i) := λ i, ⟨(hw i).wf.min ⊤ ⟨x i, trivial⟩⟩, haveI := fintype.of_finite ι, refine inv_image.wf equiv_fun_on_fintype.symm (dfinsupp.well_founded_lt $ λ i a, _).wf, exact (hw i).wf.not_lt_min ⊤ _ trivial, end⟩ instance function.well_founded_lt {α} [finite ι] [preorder α] [well_founded_lt α] : well_founded_lt (ι → α) := pi.well_founded_lt instance dfinsupp.well_founded_lt_of_finite [finite ι] [Π i, has_zero (α i)] [Π i, preorder (α i)] [∀ i, well_founded_lt (α i)] : well_founded_lt (Π₀ i, α i) := have _ := fintype.of_finite ι, by exactI ⟨inv_image.wf equiv_fun_on_fintype pi.well_founded_lt.wf⟩
6bef11eea13554093456c08438106c321ef18bf8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/gcd_monoid_auto.lean
c7c78a4649f157718be3fcdbc9749a5f05d947f9
[]
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
29,230
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, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.associated import Mathlib.PostPort universes u_2 l u_1 namespace Mathlib /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` * `gcd_monoid_of_exists_gcd` * `gcd_monoid_of_exists_lcm` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. * `gcd_monoid_of_gcd` noncomputably constructs a `gcd_monoid` structure just from the `gcd` and its properties. * `gcd_monoid_of_exists_gcd` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `gcd`. * `gcd_monoid_of_lcm` noncomputably constructs a `gcd_monoid` structure just from the `lcm` and its properties. * `gcd_monoid_of_exists_lcm` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `lcm`. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ class normalization_monoid (α : Type u_2) [nontrivial α] [comm_cancel_monoid_with_zero α] where norm_unit : α → units α norm_unit_zero : norm_unit 0 = 1 norm_unit_mul : ∀ {a b : α}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b norm_unit_coe_units : ∀ (u : units α), norm_unit ↑u = (u⁻¹) @[simp] theorem norm_unit_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : norm_unit 1 = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : monoid_with_zero_hom α α := monoid_with_zero_hom.mk (fun (x : α) => x * ↑(norm_unit x)) sorry sorry sorry theorem associated_normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : associated x (coe_fn normalize x) := Exists.intro (norm_unit x) rfl theorem normalize_associated {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : associated (coe_fn normalize x) x := associated.symm associated_normalize theorem associates.mk_normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : associates.mk (coe_fn normalize x) = associates.mk x := iff.mpr associates.mk_eq_mk_iff_associated normalize_associated @[simp] theorem normalize_apply {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : coe_fn normalize x = x * ↑(norm_unit x) := rfl @[simp] theorem normalize_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : coe_fn normalize 0 = 0 := monoid_with_zero_hom.map_zero normalize @[simp] theorem normalize_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : coe_fn normalize 1 = 1 := monoid_with_zero_hom.map_one normalize theorem normalize_coe_units {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (u : units α) : coe_fn normalize ↑u = 1 := sorry theorem normalize_eq_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : coe_fn normalize x = 0 ↔ x = 0 := { mp := fun (hx : coe_fn normalize x = 0) => iff.mp (associated_zero_iff_eq_zero x) (hx ▸ associated_normalize), mpr := fun (ᾰ : x = 0) => Eq._oldrec normalize_zero (Eq.symm ᾰ) } theorem normalize_eq_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} : coe_fn normalize x = 1 ↔ is_unit x := sorry @[simp] theorem norm_unit_mul_norm_unit {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : α) : norm_unit (a * ↑(norm_unit a)) = 1 := sorry theorem normalize_idem {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (x : α) : coe_fn normalize (coe_fn normalize x) = coe_fn normalize x := sorry theorem normalize_eq_normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {a : α} {b : α} (hab : a ∣ b) (hba : b ∣ a) : coe_fn normalize a = coe_fn normalize b := sorry theorem normalize_eq_normalize_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {x : α} {y : α} : coe_fn normalize x = coe_fn normalize y ↔ x ∣ y ∧ y ∣ x := sorry theorem dvd_antisymm_of_normalize_eq {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {a : α} {b : α} (ha : coe_fn normalize a = a) (hb : coe_fn normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp theorem dvd_normalize_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {a : α} {b : α} : a ∣ coe_fn normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp theorem normalize_dvd_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] {a : α} {b : α} : coe_fn normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd namespace comm_group_with_zero protected instance normalization_monoid {α : Type u_1} [DecidableEq α] [comm_group_with_zero α] : normalization_monoid α := normalization_monoid.mk (fun (x : α) => dite (x = 0) (fun (h : x = 0) => 1) fun (h : ¬x = 0) => units.mk0 x h⁻¹) sorry sorry sorry @[simp] theorem coe_norm_unit {α : Type u_1} [DecidableEq α] [comm_group_with_zero α] {a : α} (h0 : a ≠ 0) : ↑(norm_unit a) = (a⁻¹) := sorry end comm_group_with_zero namespace associates /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : associates α → α := quotient.lift ⇑normalize sorry theorem out_mk {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : α) : associates.out (associates.mk a) = coe_fn normalize a := rfl @[simp] theorem out_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : associates.out 1 = 1 := normalize_one theorem out_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : associates α) (b : associates α) : associates.out (a * b) = associates.out a * associates.out b := sorry theorem dvd_out_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : α) (b : associates α) : a ∣ associates.out b ↔ associates.mk a ≤ b := sorry theorem out_dvd_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : α) (b : associates α) : associates.out b ∣ a ↔ b ≤ associates.mk a := sorry @[simp] theorem out_top {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] : associates.out ⊤ = 0 := normalize_zero @[simp] theorem normalize_out {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] (a : associates α) : coe_fn normalize (associates.out a) = associates.out a := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ class gcd_monoid (α : Type u_2) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α where gcd : α → α → α lcm : α → α → α gcd_dvd_left : ∀ (a b : α), gcd a b ∣ a gcd_dvd_right : ∀ (a b : α), gcd a b ∣ b dvd_gcd : ∀ {a b c : α}, a ∣ c → a ∣ b → a ∣ gcd c b normalize_gcd : ∀ (a b : α), coe_fn normalize (gcd a b) = gcd a b gcd_mul_lcm : ∀ (a b : α), gcd a b * lcm a b = coe_fn normalize (a * b) lcm_zero_left : ∀ (a : α), lcm 0 a = 0 lcm_zero_right : ∀ (a : α), lcm a 0 = 0 @[simp] theorem normalize_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : coe_fn normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : gcd a b * lcm a b = coe_fn normalize (a * b) := gcd_monoid.gcd_mul_lcm theorem dvd_gcd_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (c : α) : a ∣ gcd b c ↔ a ∣ b ∧ a ∣ c := sorry theorem gcd_comm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd a b) (normalize_gcd b a) (dvd_gcd (gcd_dvd_right a b) (gcd_dvd_left a b)) (dvd_gcd (gcd_dvd_right b a) (gcd_dvd_left b a)) theorem gcd_assoc {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : gcd (gcd m n) k = gcd m (gcd n k) := sorry protected instance gcd_monoid.gcd.is_commutative {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : is_commutative α gcd := is_commutative.mk gcd_comm protected instance gcd_monoid.gcd.is_associative {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : is_associative α gcd := is_associative.mk gcd_assoc theorem gcd_eq_normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = coe_fn normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : gcd 0 a = coe_fn normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero a) (dvd_refl a)) @[simp] theorem gcd_zero_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : gcd a 0 = coe_fn normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero a)) @[simp] theorem gcd_eq_zero_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := sorry @[simp] theorem gcd_one_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd 1 a) normalize_one (gcd_dvd_left 1 a) (one_dvd (gcd 1 a)) @[simp] theorem gcd_one_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd a 1) normalize_one (gcd_dvd_right a 1) (one_dvd (gcd a 1)) theorem gcd_dvd_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} {d : α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left a c) hab) (dvd.trans (gcd_dvd_right a c) hcd) @[simp] theorem gcd_same {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : gcd a a = coe_fn normalize a := gcd_eq_normalize (gcd_dvd_left a a) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (c : α) : gcd (a * b) (a * c) = coe_fn normalize a * gcd b c := sorry @[simp] theorem gcd_mul_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (c : α) : gcd (b * a) (c * a) = gcd b c * coe_fn normalize a := sorry theorem gcd_eq_left_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (h : coe_fn normalize a = a) : gcd a b = a ↔ a ∣ b := sorry theorem gcd_eq_right_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (h : coe_fn normalize b = b) : gcd a b = b ↔ b ∣ a := sorry theorem gcd_dvd_gcd_mul_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left m k) (dvd_refl n) theorem gcd_dvd_gcd_mul_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right m k) (dvd_refl n) theorem gcd_dvd_gcd_mul_left_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl m) (dvd_mul_left n k) theorem gcd_dvd_gcd_mul_right_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl m) (dvd_mul_right n k) theorem gcd_eq_of_associated_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} (h : associated m n) (k : α) : gcd m k = gcd n k := dvd_antisymm_of_normalize_eq (normalize_gcd m k) (normalize_gcd n k) (gcd_dvd_gcd (dvd_of_associated h) (dvd_refl k)) (gcd_dvd_gcd (dvd_of_associated (associated.symm h)) (dvd_refl k)) theorem gcd_eq_of_associated_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} (h : associated m n) (k : α) : gcd k m = gcd k n := dvd_antisymm_of_normalize_eq (normalize_gcd k m) (normalize_gcd k n) (gcd_dvd_gcd (dvd_refl k) (dvd_of_associated h)) (gcd_dvd_gcd (dvd_refl k) (dvd_of_associated (associated.symm h))) theorem dvd_gcd_mul_of_dvd_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} {k : α} (H : k ∣ m * n) : k ∣ gcd k m * n := sorry theorem dvd_mul_gcd_of_dvd_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} {k : α} (H : k ∣ m * n) : k ∣ m * gcd k n := eq.mpr (id (Eq._oldrec (Eq.refl (k ∣ m * gcd k n)) (mul_comm m (gcd k n)))) (dvd_gcd_mul_of_dvd_mul (eq.mp (Eq._oldrec (Eq.refl (k ∣ m * n)) (mul_comm m n)) H)) /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. Note: In general, this representation is highly non-unique. -/ theorem exists_dvd_and_dvd_of_dvd_mul {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} {k : α} (H : k ∣ m * n) : ∃ (d₁ : α), ∃ (hd₁ : d₁ ∣ m), ∃ (d₂ : α), ∃ (hd₂ : d₂ ∣ n), k = d₁ * d₂ := sorry theorem gcd_mul_dvd_mul_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (k : α) (m : α) (n : α) : gcd k (m * n) ∣ gcd k m * gcd k n := sorry theorem gcd_pow_right_dvd_pow_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {k : ℕ} : gcd a (b ^ k) ∣ gcd a b ^ k := sorry theorem gcd_pow_left_dvd_pow_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {k : ℕ} : gcd (a ^ k) b ∣ gcd a b ^ k := eq.mpr (id (Eq._oldrec (Eq.refl (gcd (a ^ k) b ∣ gcd a b ^ k)) (gcd_comm (a ^ k) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd b (a ^ k) ∣ gcd a b ^ k)) (gcd_comm a b))) gcd_pow_right_dvd_pow_gcd) theorem pow_dvd_of_mul_eq_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} {d₁ : α} {d₂ : α} (ha : a ≠ 0) (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂) (hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a := sorry theorem exists_associated_pow_of_mul_eq_pow {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a := sorry theorem lcm_dvd_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := sorry theorem dvd_lcm_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : a ∣ lcm a b := and.left (iff.mp lcm_dvd_iff (dvd_refl (lcm a b))) theorem dvd_lcm_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : b ∣ lcm a b := and.right (iff.mp lcm_dvd_iff (dvd_refl (lcm a b))) theorem lcm_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := iff.mpr lcm_dvd_iff { left := hab, right := hcb } @[simp] theorem lcm_eq_zero_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := sorry @[simp] theorem normalize_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : coe_fn normalize (lcm a b) = lcm a b := sorry theorem lcm_comm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm a b) (normalize_lcm b a) (lcm_dvd (dvd_lcm_right b a) (dvd_lcm_left b a)) (lcm_dvd (dvd_lcm_right a b) (dvd_lcm_left a b)) theorem lcm_assoc {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : lcm (lcm m n) k = lcm m (lcm n k) := sorry protected instance gcd_monoid.lcm.is_commutative {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : is_commutative α lcm := is_commutative.mk lcm_comm protected instance gcd_monoid.lcm.is_associative {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : is_associative α lcm := is_associative.mk lcm_assoc theorem lcm_eq_normalize {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = coe_fn normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} {b : α} {c : α} {d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left b d)) (dvd.trans hcd (dvd_lcm_right b d)) @[simp] theorem lcm_units_coe_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (u : units α) (a : α) : lcm (↑u) a = coe_fn normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl a)) (dvd_lcm_right (↑u) a) @[simp] theorem lcm_units_coe_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (u : units α) : lcm a ↑u = coe_fn normalize a := Eq.trans (lcm_comm a ↑u) (lcm_units_coe_left u a) @[simp] theorem lcm_one_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : lcm 1 a = coe_fn normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : lcm a 1 = coe_fn normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) : lcm a a = coe_fn normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl a) (dvd_refl a)) (dvd_lcm_left a a) @[simp] theorem lcm_eq_one_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := sorry @[simp] theorem lcm_mul_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (c : α) : lcm (a * b) (a * c) = coe_fn normalize a * lcm b c := sorry @[simp] theorem lcm_mul_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (c : α) : lcm (b * a) (c * a) = lcm b c * coe_fn normalize a := sorry theorem lcm_eq_left_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (h : coe_fn normalize a = a) : lcm a b = a ↔ b ∣ a := sorry theorem lcm_eq_right_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (b : α) (h : coe_fn normalize b = b) : lcm a b = b ↔ a ∣ b := sorry theorem lcm_dvd_lcm_mul_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left m k) (dvd_refl n) theorem lcm_dvd_lcm_mul_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right m k) (dvd_refl n) theorem lcm_dvd_lcm_mul_left_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl m) (dvd_mul_left n k) theorem lcm_dvd_lcm_mul_right_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (m : α) (n : α) (k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl m) (dvd_mul_right n k) theorem lcm_eq_of_associated_left {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} (h : associated m n) (k : α) : lcm m k = lcm n k := dvd_antisymm_of_normalize_eq (normalize_lcm m k) (normalize_lcm n k) (lcm_dvd_lcm (dvd_of_associated h) (dvd_refl k)) (lcm_dvd_lcm (dvd_of_associated (associated.symm h)) (dvd_refl k)) theorem lcm_eq_of_associated_right {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {m : α} {n : α} (h : associated m n) (k : α) : lcm k m = lcm k n := dvd_antisymm_of_normalize_eq (normalize_lcm k m) (normalize_lcm k n) (lcm_dvd_lcm (dvd_refl k) (dvd_of_associated h)) (lcm_dvd_lcm (dvd_refl k) (dvd_of_associated (associated.symm h))) namespace gcd_monoid theorem prime_of_irreducible {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {x : α} (hi : irreducible x) : prime x := sorry theorem irreducible_iff_prime {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {p : α} : irreducible p ↔ prime p := { mp := prime_of_irreducible, mpr := irreducible_of_prime } end gcd_monoid theorem units_eq_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique (units α)] (u : units α) : u = 1 := subsingleton.elim u 1 protected instance normalization_monoid_of_unique_units {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique (units α)] [nontrivial α] : normalization_monoid α := normalization_monoid.mk (fun (x : α) => 1) sorry sorry sorry @[simp] theorem norm_unit_eq_one {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique (units α)] [nontrivial α] (x : α) : norm_unit x = 1 := rfl @[simp] theorem normalize_eq {α : Type u_1} [comm_cancel_monoid_with_zero α] [unique (units α)] [nontrivial α] (x : α) : coe_fn normalize x = x := mul_one x theorem gcd_eq_of_dvd_sub_right {α : Type u_1} [integral_domain α] [gcd_monoid α] {a : α} {b : α} {c : α} (h : a ∣ b - c) : gcd a b = gcd a c := sorry theorem gcd_eq_of_dvd_sub_left {α : Type u_1} [integral_domain α] [gcd_monoid α] {a : α} {b : α} {c : α} (h : a ∣ b - c) : gcd b a = gcd c a := eq.mpr (id (Eq._oldrec (Eq.refl (gcd b a = gcd c a)) (gcd_comm b a))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd a b = gcd c a)) (gcd_comm c a))) (eq.mpr (id (Eq._oldrec (Eq.refl (gcd a b = gcd a c)) (gcd_eq_of_dvd_sub_right h))) (Eq.refl (gcd a c)))) /-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/ def normalization_monoid_of_monoid_hom_right_inverse {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [DecidableEq α] (f : associates α →* α) (hinv : function.right_inverse (⇑f) associates.mk) : normalization_monoid α := normalization_monoid.mk (fun (a : α) => ite (a = 0) 1 (classical.some sorry)) sorry sorry sorry /-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/ def gcd_monoid_of_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] [DecidableEq α] (gcd : α → α → α) (gcd_dvd_left : ∀ (a b : α), gcd a b ∣ a) (gcd_dvd_right : ∀ (a b : α), gcd a b ∣ b) (dvd_gcd : ∀ {a b c : α}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀ (a b : α), coe_fn normalize (gcd a b) = gcd a b) : gcd_monoid α := gcd_monoid.mk norm_unit sorry sorry sorry gcd (fun (a b : α) => ite (a = 0) 0 (classical.some sorry)) gcd_dvd_left gcd_dvd_right sorry normalize_gcd sorry sorry sorry /-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/ def gcd_monoid_of_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] [DecidableEq α] (lcm : α → α → α) (dvd_lcm_left : ∀ (a b : α), a ∣ lcm a b) (dvd_lcm_right : ∀ (a b : α), b ∣ lcm a b) (lcm_dvd : ∀ {a b c : α}, c ∣ a → b ∣ a → lcm c b ∣ a) (normalize_lcm : ∀ (a b : α), coe_fn normalize (lcm a b) = lcm a b) : gcd_monoid α := let exists_gcd : ∀ (a b : α), lcm a b ∣ coe_fn normalize (a * b) := sorry; gcd_monoid.mk norm_unit sorry sorry sorry (fun (a b : α) => ite (a = 0) (coe_fn normalize b) (ite (b = 0) (coe_fn normalize a) (classical.some (exists_gcd a b)))) lcm sorry sorry sorry sorry sorry sorry sorry /-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/ def gcd_monoid_of_exists_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] [DecidableEq α] (h : ∀ (a b : α), ∃ (c : α), ∀ (d : α), d ∣ a ∧ d ∣ b ↔ d ∣ c) : gcd_monoid α := gcd_monoid_of_gcd (fun (a b : α) => coe_fn normalize (classical.some (h a b))) sorry sorry sorry sorry /-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/ def gcd_monoid_of_exists_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] [DecidableEq α] (h : ∀ (a b : α), ∃ (c : α), ∀ (d : α), a ∣ d ∧ b ∣ d ↔ c ∣ d) : gcd_monoid α := gcd_monoid_of_lcm (fun (a b : α) => coe_fn normalize (classical.some (h a b))) sorry sorry sorry sorry end Mathlib
cbc53449a31c83d4db745498e96277574dbe0bd9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/determinant.lean
c005163173ff9be3bd90800174571737a55e7695
[ "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
26,274
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' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (e : ι ≃ ι') : (b.reindex e).det = b.det.dom_dom_congr e := alternating_map.ext $ λ _, basis.det_reindex _ _ _ 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 _
4fd9959adf96753df2b68efab07c17f3b48e10c7
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/filter/countable_Inter.lean
7c1b523d91fa195e26614585243606b7debcfb3f
[ "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
8,676
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import order.filter.basic import data.set.countable /-! # Filters with countable intersection property > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `countable_Inter_filter` to be the class of filters with the following property: for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. Two main examples are the `residual` filter defined in `topology.metric_space.baire` and the `measure.ae` filter defined in `measure_theory.measure_space`. We reformulate the definition in terms of indexed intersection and in terms of `filter.eventually` and provide instances for some basic constructions (`⊥`, `⊤`, `filter.principal`, `filter.map`, `filter.comap`, `has_inf.inf`). We also provide a custom constructor `filter.of_countable_Inter` that deduces two axioms of a `filter` from the countable intersection property. ## Tags filter, countable -/ open set filter open_locale filter variables {ι : Sort*} {α β : Type*} /-- A filter `l` has the countable intersection property if for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. -/ class countable_Inter_filter (l : filter α) : Prop := (countable_sInter_mem' : ∀ {S : set (set α)} (hSc : S.countable) (hS : ∀ s ∈ S, s ∈ l), ⋂₀ S ∈ l) variables {l : filter α} [countable_Inter_filter l] lemma countable_sInter_mem {S : set (set α)} (hSc : S.countable) : ⋂₀ S ∈ l ↔ ∀ s ∈ S, s ∈ l := ⟨λ hS s hs, mem_of_superset hS (sInter_subset_of_mem hs), countable_Inter_filter.countable_sInter_mem' hSc⟩ lemma countable_Inter_mem [countable ι] {s : ι → set α} : (⋂ i, s i) ∈ l ↔ ∀ i, s i ∈ l := sInter_range s ▸ (countable_sInter_mem (countable_range _)).trans forall_range_iff lemma countable_bInter_mem {ι : Type*} {S : set ι} (hS : S.countable) {s : Π i ∈ S, set α} : (⋂ i ∈ S, s i ‹_›) ∈ l ↔ ∀ i ∈ S, s i ‹_› ∈ l := begin rw [bInter_eq_Inter], haveI := hS.to_encodable, exact countable_Inter_mem.trans subtype.forall end lemma eventually_countable_forall [countable ι] {p : α → ι → Prop} : (∀ᶠ x in l, ∀ i, p x i) ↔ ∀ i, ∀ᶠ x in l, p x i := by simpa only [filter.eventually, set_of_forall] using @countable_Inter_mem _ _ l _ _ (λ i, {x | p x i}) lemma eventually_countable_ball {ι : Type*} {S : set ι} (hS : S.countable) {p : Π (x : α) (i ∈ S), Prop} : (∀ᶠ x in l, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᶠ x in l, p x i ‹_› := by simpa only [filter.eventually, set_of_forall] using @countable_bInter_mem _ l _ _ _ hS (λ i hi, {x | p x i hi}) lemma eventually_le.countable_Union [countable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋃ i, s i) ≤ᶠ[l] ⋃ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Union.2 $ (mem_Union.1 hs).imp hst lemma eventually_eq.countable_Union [countable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋃ i, s i) =ᶠ[l] ⋃ i, t i := (eventually_le.countable_Union (λ i, (h i).le)).antisymm (eventually_le.countable_Union (λ i, (h i).symm.le)) lemma eventually_le.countable_bUnion {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋃ i ∈ S, t i ‹_› := begin simp only [bUnion_eq_Union], haveI := hS.to_encodable, exact eventually_le.countable_Union (λ i, h i i.2) end lemma eventually_eq.countable_bUnion {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) =ᶠ[l] ⋃ i ∈ S, t i ‹_› := (eventually_le.countable_bUnion hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bUnion hS (λ i hi, (h i hi).symm.le)) lemma eventually_le.countable_Inter [countable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋂ i, s i) ≤ᶠ[l] ⋂ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Inter.2 $ λ i, hst _ (mem_Inter.1 hs i) lemma eventually_eq.countable_Inter [countable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋂ i, s i) =ᶠ[l] ⋂ i, t i := (eventually_le.countable_Inter (λ i, (h i).le)).antisymm (eventually_le.countable_Inter (λ i, (h i).symm.le)) lemma eventually_le.countable_bInter {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋂ i ∈ S, t i ‹_› := begin simp only [bInter_eq_Inter], haveI := hS.to_encodable, exact eventually_le.countable_Inter (λ i, h i i.2) end lemma eventually_eq.countable_bInter {ι : Type*} {S : set ι} (hS : S.countable) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) =ᶠ[l] ⋂ i ∈ S, t i ‹_› := (eventually_le.countable_bInter hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bInter hS (λ i hi, (h i hi).symm.le)) /-- Construct a filter with countable intersection property. This constructor deduces `filter.univ_sets` and `filter.inter_sets` from the countable intersection property. -/ def filter.of_countable_Inter (l : set (set α)) (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : filter α := { sets := l, univ_sets := @sInter_empty α ▸ hp _ countable_empty (empty_subset _), sets_of_superset := h_mono, inter_sets := λ s t hs ht, sInter_pair s t ▸ hp _ ((countable_singleton _).insert _) (insert_subset.2 ⟨hs, singleton_subset_iff.2 ht⟩) } instance filter.countable_Inter_of_countable_Inter (l : set (set α)) (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) : countable_Inter_filter (filter.of_countable_Inter l hp h_mono) := ⟨hp⟩ @[simp] lemma filter.mem_of_countable_Inter {l : set (set α)} (hp : ∀ S : set (set α), S.countable → S ⊆ l → (⋂₀ S) ∈ l) (h_mono : ∀ s t, s ∈ l → s ⊆ t → t ∈ l) {s : set α} : s ∈ filter.of_countable_Inter l hp h_mono ↔ s ∈ l := iff.rfl instance countable_Inter_filter_principal (s : set α) : countable_Inter_filter (𝓟 s) := ⟨λ S hSc hS, subset_sInter hS⟩ instance countable_Inter_filter_bot : countable_Inter_filter (⊥ : filter α) := by { rw ← principal_empty, apply countable_Inter_filter_principal } instance countable_Inter_filter_top : countable_Inter_filter (⊤ : filter α) := by { rw ← principal_univ, apply countable_Inter_filter_principal } instance (l : filter β) [countable_Inter_filter l] (f : α → β) : countable_Inter_filter (comap f l) := begin refine ⟨λ S hSc hS, _⟩, choose! t htl ht using hS, have : (⋂ s ∈ S, t s) ∈ l, from (countable_bInter_mem hSc).2 htl, refine ⟨_, this, _⟩, simpa [preimage_Inter] using (Inter₂_mono ht) end instance (l : filter α) [countable_Inter_filter l] (f : α → β) : countable_Inter_filter (map f l) := begin constructor, intros S hSc hS, simp only [mem_map, sInter_eq_bInter, preimage_Inter₂] at hS ⊢, exact (countable_bInter_mem hSc).2 hS end /-- Infimum of two `countable_Inter_filter`s is a `countable_Inter_filter`. This is useful, e.g., to automatically get an instance for `residual α ⊓ 𝓟 s`. -/ instance countable_Inter_filter_inf (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊓ l₂) := begin refine ⟨λ S hSc hS, _⟩, choose s hs t ht hst using hS, replace hs : (⋂ i ∈ S, s i ‹_›) ∈ l₁ := (countable_bInter_mem hSc).2 hs, replace ht : (⋂ i ∈ S, t i ‹_›) ∈ l₂ := (countable_bInter_mem hSc).2 ht, refine mem_of_superset (inter_mem_inf hs ht) (subset_sInter $ λ i hi, _), rw hst i hi, apply inter_subset_inter ; exact Inter_subset_of_subset i (Inter_subset _ _) end /-- Supremum of two `countable_Inter_filter`s is a `countable_Inter_filter`. -/ instance countable_Inter_filter_sup (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊔ l₂) := begin refine ⟨λ S hSc hS, ⟨_, _⟩⟩; refine (countable_sInter_mem hSc).2 (λ s hs, _), exacts [(hS s hs).1, (hS s hs).2] end
7474b9b82611530cb3ea10e926a77ea69ad80501
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/refine3.lean
3148aa23ecee7ea98ab6d7747f605c9c1b36b235
[ "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
277
lean
import data.nat.basic open nat algebra theorem zero_left (n : ℕ) : 0 + n = n := nat.induction_on n !add_zero (take m IH, begin refine (calc 0 + succ m = succ (0 + m) : _ ... = succ m : IH), esimp end)
b55fb8abb34a44f9ad5f2d0f5153695f941bf355
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/direct_sum.lean
51459f09eb562f50625ebdc5a0e3e317e2a024c2
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,499
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.dfinsupp /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ open_locale big_operators universes u v w u₁ variables (ι : Type v) [dec_ι : decidable_eq ι] (β : ι → Type w) [Π i, add_comm_group (β i)] /-- `direct_sum β` is the direct sum of a family of additive commutative groups `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ def direct_sum : Type* := Π₀ i, β i localized "notation `⨁` binders `, ` r:(scoped f, direct_sum _ f) := r" in direct_sum namespace direct_sum variables {ι β} instance : add_comm_group (⨁ i, β i) := dfinsupp.add_comm_group instance : inhabited (⨁ i, β i) := ⟨0⟩ variables β include dec_ι /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk : Π s : finset ι, (Π i : (↑s : set ι), β i.1) → ⨁ i, β i := dfinsupp.mk /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of : Π i : ι, β i → ⨁ i, β i := dfinsupp.single variables {β} instance mk.is_add_group_hom (s : finset ι) : is_add_group_hom (mk β s) := { map_add := λ _ _, dfinsupp.mk_add } @[simp] lemma mk_zero (s : finset ι) : mk β s 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma mk_add (s : finset ι) (x y) : mk β s (x + y) = mk β s x + mk β s y := is_add_hom.map_add _ x y @[simp] lemma mk_neg (s : finset ι) (x) : mk β s (-x) = -mk β s x := is_add_group_hom.map_neg _ x @[simp] lemma mk_sub (s : finset ι) (x y) : mk β s (x - y) = mk β s x - mk β s y := is_add_group_hom.map_sub _ x y instance of.is_add_group_hom (i : ι) : is_add_group_hom (of β i) := { map_add := λ _ _, dfinsupp.single_add } @[simp] lemma of_zero (i : ι) : of β i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i : ι) (x y) : of β i (x + y) = of β i x + of β i y := is_add_hom.map_add _ x y @[simp] lemma of_neg (i : ι) (x) : of β i (-x) = -of β i x := is_add_group_hom.map_neg _ x @[simp] lemma of_sub (i : ι) (x y) : of β i (x - y) = of β i x - of β i y := is_add_group_hom.map_sub _ x y theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := λ x y H, congr_fun (mk_injective _ H) ⟨i, by simp⟩ @[elab_as_eliminator] protected theorem induction_on {C : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end variables {γ : Type u₁} [add_comm_group γ] variables (φ : Π i, β i → γ) [Π i, is_add_group_hom (φ i)] variables (φ) /-- `to_group φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_group (f : ⨁ i, β i) : γ := quotient.lift_on f (λ x, ∑ i in x.2.to_finset, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), is_add_group_hom.map_zero (φ i)] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), is_add_group_hom.map_zero (φ i)] } end variables {φ} instance to_group.is_add_group_hom : is_add_group_hom (to_group φ) := { map_add := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change ∑ i in _, _ = (∑ i in _, _) + (∑ i in _, _), simp only, conv { to_lhs, congr, skip, funext, rw is_add_hom.map_add (φ i) }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } } end } variables (φ) @[simp] lemma to_group_zero : to_group φ 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma to_group_add (x y) : to_group φ (x + y) = to_group φ x + to_group φ y := is_add_hom.map_add _ x y @[simp] lemma to_group_neg (x) : to_group φ (-x) = -to_group φ x := is_add_group_hom.map_neg _ x @[simp] lemma to_group_sub (x y) : to_group φ (x - y) = to_group φ x - to_group φ y := is_add_group_hom.map_sub _ x y @[simp] lemma to_group_of (i) (x : β i) : to_group φ (of β i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ ({i} : finset _) then x else 0) = x, from dif_pos $ finset.mem_singleton_self i variables (ψ : (⨁ i, β i) → γ) [is_add_group_hom ψ] theorem to_group.unique (f : ⨁ i, β i) : ψ f = @to_group _ _ _ _ _ _ (λ i, ψ ∘ of β i) (λ i, is_add_group_hom.comp (of β i) ψ) f := by haveI : ∀ i, is_add_group_hom (ψ ∘ of β i) := (λ _, is_add_group_hom.comp _ _); exact direct_sum.induction_on f (by rw [is_add_group_hom.map_zero ψ, is_add_group_hom.map_zero (to_group (λ i, ψ ∘ of β i))]) (λ i x, by rw [to_group_of]) (λ x y ihx ihy, by rw [is_add_hom.map_add ψ, is_add_hom.map_add (to_group (λ i, ψ ∘ of β i)), ihx, ihy]) variables (β) /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), β i) → (⨁ (i : T), β i) := to_group $ λ i, of (β ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ variables {β} instance (S T : set ι) (H : S ⊆ T) : is_add_group_hom (set_to_set β S T H) := to_group.is_add_group_hom omit dec_ι /-- The natural equivalence between `⨁ _ : punit, M` and `M`. -/ -- TODO: generalize this to a sum over any type `ι` that is `unique ι`. protected def id (M : Type v) [add_comm_group M] : (⨁ (_ : punit), M) ≃ M := { to_fun := direct_sum.to_group (λ _, id), inv_fun := of (λ _, M) punit.star, left_inv := λ x, direct_sum.induction_on x (by rw [to_group_zero, of_zero]) (λ ⟨⟩ x, by rw [to_group_of]; refl) (λ x y ihx ihy, by rw [to_group_add, of_add, ihx, ihy]), right_inv := λ x, to_group_of _ _ _ } instance : has_coe_to_fun (⨁ i, β i) := dfinsupp.has_coe_to_fun end direct_sum
810c53cd0ec50652dffa9b5819f0486500a5a5ad
0003047346476c031128723dfd16fe273c6bc605
/src/analysis/normed_space/bounded_linear_maps.lean
87309ba8586250e239a1b962cc194d6ca29e58e8
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,636
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 Continuous linear functions -- functions between normed vector spaces which are bounded and linear. -/ import algebra.field import tactic.norm_num import analysis.normed_space.basic import ..asymptotics @[simp] lemma mul_inv_eq' {α} [discrete_field α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := classical.by_cases (assume : a = 0, by simp [this]) $ assume ha, classical.by_cases (assume : b = 0, by simp [this]) $ assume hb, mul_inv_eq hb ha noncomputable theory local attribute [instance] classical.prop_decidable local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b) open filter (tendsto) open metric variables {k : Type*} [normed_field k] variables {E : Type*} [normed_space k E] variables {F : Type*} [normed_space k F] variables {G : Type*} [normed_space k G] structure is_bounded_linear_map {k : Type*} [normed_field k] {E : Type*} [normed_space k E] {F : Type*} [normed_space k F] (L : E → F) extends is_linear_map k L : Prop := (bound : ∃ M, M > 0 ∧ ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) include k lemma is_linear_map.with_bound {L : E → F} (hf : is_linear_map k L) (M : ℝ) (h : ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map L := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, assume x, le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ namespace is_bounded_linear_map def to_linear_map (f : E → F) (h : is_bounded_linear_map f) : E →ₗ[k] F := (is_linear_map.mk' _ h.to_is_linear_map) lemma zero : is_bounded_linear_map (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma smul {f : E → F} (c : k) : is_bounded_linear_map f → is_bounded_linear_map (λ e, c • f e) | ⟨hf, ⟨M, hM, h⟩⟩ := (c • hf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (h x) (norm_nonneg c) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg {f : E → F} (hf : is_bounded_linear_map f) : is_bounded_linear_map (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : k) • f e), { funext, simp }, exact smul (-1) hf end lemma add {f : E → F} {g : E → F} : is_bounded_linear_map f → is_bounded_linear_map g → is_bounded_linear_map (λ e, f e + g e) | ⟨hlf, Mf, hMf, hf⟩ ⟨hlg, Mg, hMg, hg⟩ := (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x, calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _ ... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hf x) (hg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub {f : E → F} {g : E → F} (hf : is_bounded_linear_map f) (hg : is_bounded_linear_map g) : is_bounded_linear_map (λ e, f e - g e) := add hf (neg hg) lemma comp {f : E → F} {g : F → G} : is_bounded_linear_map g → is_bounded_linear_map f → is_bounded_linear_map (g ∘ f) | ⟨hlg, Mg, hMg, hg⟩ ⟨hlf, Mf, hMf, hf⟩ := ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x, calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hg _ ... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hf _) (le_of_lt hMg) ... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm lemma tendsto {L : E → F} (x : E) : is_bounded_linear_map L → L →_{x} (L x) | ⟨hL, M, hM, h_ineq⟩ := tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (assume e, norm_nonneg _) (assume e, calc ∥L e - L x∥ = ∥hL.mk' L (e - x)∥ : by rw (hL.mk' _).map_sub e x; refl ... ≤ M*∥e-x∥ : h_ineq (e-x)) (suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa, tendsto_mul tendsto_const_nhds (lim_norm _)) lemma continuous {L : E → F} (hL : is_bounded_linear_map L) : continuous L := continuous_iff_continuous_at.2 $ assume x, hL.tendsto x lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map L) : (L →_{0} 0) := (H.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 H.continuous 0 section open asymptotics filter theorem is_O_id {L : E → F} (h : is_bounded_linear_map L) (l : filter E) : is_O L (λ x, x) l := let ⟨M, Mpos, hM⟩ := h.bound in ⟨M, Mpos, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩ theorem is_O_comp {L : F → G} (h : is_bounded_linear_map L) {f : E → F} (l : filter E) : is_O (λ x', L (f x')) f l := ((h.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top) theorem is_O_sub {L : E → F} (h : is_bounded_linear_map L) (l : filter E) (x : E) : is_O (λ x', L (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map -- Next lemma is stated for real normed space but it would work as soon as the base field is an extension of ℝ lemma bounded_continuous_linear_map {E : Type*} [normed_space ℝ E] {F : Type*} [normed_space ℝ F] {L : E → F} (lin : is_linear_map ℝ L) (cont : continuous L) : is_bounded_linear_map L := let ⟨δ, δ_pos, hδ⟩ := exists_delta_of_continuous cont zero_lt_one 0 in have HL0 : L 0 = 0, from (lin.mk' _).map_zero, have H : ∀{a}, ∥a∥ ≤ δ → ∥L a∥ < 1, by simpa only [HL0, dist_zero_right] using hδ, lin.with_bound (δ⁻¹) $ assume x, classical.by_cases (assume : x = 0, by simp only [this, HL0, norm_zero, mul_zero]) $ assume h : x ≠ 0, let p := ∥x∥ * δ⁻¹, q := p⁻¹ in have p_inv : p⁻¹ = δ*∥x∥⁻¹, by simp, have norm_x_pos : ∥x∥ > 0 := (norm_pos_iff x).2 h, have norm_x : ∥x∥ ≠ 0 := mt (norm_eq_zero x).1 h, have p_pos : p > 0 := mul_pos norm_x_pos (inv_pos δ_pos), have p0 : _ := ne_of_gt p_pos, have q_pos : q > 0 := inv_pos p_pos, have q0 : _ := ne_of_gt q_pos, have ∥p⁻¹ • x∥ = δ := calc ∥p⁻¹ • x∥ = abs p⁻¹ * ∥x∥ : by rw norm_smul; refl ... = p⁻¹ * ∥x∥ : by rw [abs_of_nonneg $ le_of_lt q_pos] ... = δ : by simp [mul_assoc, inv_mul_cancel norm_x], calc ∥L x∥ = (p * q) * ∥L x∥ : begin dsimp [q], rw [mul_inv_cancel p0, one_mul] end ... = p * ∥L (q • x)∥ : by simp [lin.smul, norm_smul, real.norm_eq_abs, abs_of_pos q_pos, mul_assoc] ... ≤ p * 1 : mul_le_mul_of_nonneg_left (le_of_lt $ H $ le_of_eq $ this) (le_of_lt p_pos) ... = δ⁻¹ * ∥x∥ : by rw [mul_one, mul_comm]
eb07768c45b0f972349b9b61d01172e6b6f0a63f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/lint/frontend_auto.lean
52e19e4afb757bf8e0e00667e53c94c1e31d153f
[]
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
6,212
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.lint.basic import Mathlib.PostPort universes l namespace Mathlib /-! # Linter frontend and commands This file defines the linter commands which spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ /-- Verbosity for the linter output. * `low`: only print failing checks, print nothing on success. * `medium`: only print failing checks, print confirmation on success. * `high`: print output of every check. -/ inductive lint_verbosity where | low : lint_verbosity | medium : lint_verbosity | high : lint_verbosity /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ /-- `lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations. If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`. If `auto_decls` is true, then it is applied to `all_decls`. The resulting list has one element for each linter, containing the linter as well as a map from declaration name to warning. -/ /-- Sorts a map with declaration keys as names by line number. -/ /-- Formats a linter warning as `#print` command with comment. -/ /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ /-- Formats the linter results as Lean code with comments and `#print` commands. -/ /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `group_by_filename` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ /-- Returns the declarations considered by the mathlib linter. -/ /-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/ /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ /-- Parses a "-" or "+", returning `lint_verbosity.low` or `lint_verbosity.high` respectively, or returns `none`. -/ /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output if all checks pass. `#lint+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output if all checks pass. `lint_mathlib+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output if all checks pass. `lint_all+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ /-- The command `#list_linters` prints a list of all available linters. -/ /-- Invoking the hole command `lint` ("Find common mistakes in current file") will print text that indicates mistakes made in the file above the command. It is equivalent to copying and pasting the output of `#lint`. On large files, it may take some time before the output appears. -/ end Mathlib
cf7e953b00bc102fb96e330374ed02c22afedd8a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mv_polynomial/default.lean
19ebb3633c3d2cd7d828bca02928962e32ddaa6e
[]
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
273
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.mv_polynomial.basic import Mathlib.data.mv_polynomial.variables import Mathlib.data.mv_polynomial.rename import Mathlib.data.mv_polynomial.comm_ring import Mathlib.PostPort namespace Mathlib
e49817ab7233919afb8818f290b9daec71a20c19
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Leanpkg/Git.lean
1203abb875609a96e9b20c8ed19200269487eea2
[ "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
1,447
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ import Leanpkg.LeanVersion namespace Leanpkg def upstreamGitBranch := if Lean.version.isRelease then "Lean-" ++ leanVersionStringCore else "master" def gitdefaultRevision : Option String → String | none => upstreamGitBranch | some branch => branch def gitParseRevision (gitRepoDir : String) (rev : String) : IO String := do let rev ← IO.Process.run {cmd := "git", args := #["rev-parse", "-q", "--verify", rev], cwd := gitRepoDir} rev.trim -- remove newline at end def gitHeadRevision (gitRepoDir : String) : IO String := gitParseRevision gitRepoDir "HEAD" def gitParseOriginRevision (gitRepoDir : String) (rev : String) : IO String := (gitParseRevision gitRepoDir $ "origin/" ++ rev) <|> gitParseRevision gitRepoDir rev <|> throw (IO.userError s!"cannot find revision {rev} in repository {gitRepoDir}") def gitLatestOriginRevision (gitRepoDir : String) (branch : Option String) : IO String := do discard <| IO.Process.run {cmd := "git", args := #["fetch"], cwd := gitRepoDir} gitParseOriginRevision gitRepoDir (gitdefaultRevision branch) def gitRevisionExists (gitRepoDir : String) (rev : String) : IO Bool := do try discard <| gitParseRevision gitRepoDir (rev ++ "^{commit}") true catch _ => false end Leanpkg
91f3db3e541689a5a45e971ff510c85142989355
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/init/reserved_notation.lean
41f4ea20200dae55ea8acddeea58ecb75a64ca3a
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,348
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ prelude import init.datatypes notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixr ` ∘ `:60 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixl ` ⊎ `:25 reserve infixl ` × `:30 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` div `:70 reserve infixl ` mod `:70 reserve infixl ` / `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:65
2907f25d203ff8d8a448d789c6fdf2c67e045871
bf532e3e865883a676110e756f800e0ddeb465be
/set_theory/cardinal.lean
b1c4e178c4bd57b4176c11002c8b0f1a40ca2a57
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,358
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.schroeder_bernstein logic.function noncomputable theory open function lattice set classical local attribute [instance] prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := assume a, quot.induction_on a $ λ α, ⟨embedding.refl _⟩, le_trans := assume a b c, quotient.induction_on₃ a b c $ assume α β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩, le_antisymm := assume a b, quotient.induction_on₂ a b $ assume α β ⟨e₁⟩ ⟨e₂⟩, quotient.sound (e₁.antisymm e₂), le_total := assume a b, quotient.induction_on₂ a b $ assume α β, embedding.total } instance : decidable_linear_order cardinal.{u} := { decidable_le := by apply_instance, ..cardinal.linear_order } instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦ulift empty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.ulift.symm⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).down.elim⟩ instance : has_one cardinal.{u} := ⟨⟦ulift unit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨⟨()⟩⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, ⟨()⟩, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.sum_congr equiv.ulift (equiv.refl α)) (equiv.empty_sum α)⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) $ equiv.trans (equiv.empty_prod α) equiv.ulift.symm⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) (equiv.unit_prod α)⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ local notation a ^ b := cardinal.power a b @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.trans equiv.arrow_empty_unit $ equiv.ulift.symm⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.unit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans (equiv.arrow_unit_equiv_unit α) $ equiv.ulift.symm⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans $ equiv.bool_equiv_unit_sum_unit.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, have nonempty α, from ne_zero_iff_nonempty.1 heq, let a := choice this in have (α → empty) ≃ empty, from ⟨λf, f a, λe a, e, assume f, (f a).rec_on (λ_, (λa', f a) = f), assume e, rfl⟩, quotient.sound ⟨equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans this equiv.ulift.symm⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le (a : cardinal) : 0 ≤ a := quot.induction_on a $ λ α, ⟨embedding.of_not_nonempty $ λ ⟨⟨a⟩⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add {a b c d : cardinal} : a ≤ b → c ≤ d → a + c ≤ b + d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul {a b c d : cardinal} : a ≤ b → c ≤ d → a * c ≤ b * d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left {a b c : cardinal} : a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := quotient.induction_on₃ a b c $ assume α β γ hα ⟨e⟩, have nonempty α, from classical.by_contradiction $ assume hnα, hα $ quotient.sound ⟨equiv.trans (equiv.empty_of_not_nonempty hnα) equiv.ulift.symm⟩, let ⟨a⟩ := this in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, le_imp_le_iff_lt_imp_lt.1 (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.comm_semiring, ..cardinal.linear_order } instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } theorem cantor (a : cardinal.{u}) : a < 2 ^ a := by rw ← prop_eq_two; exact quot.induction_on a (λ α, ⟨⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩) instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} (f : ι → cardinal) (a) : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := (sup_le _ _).2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := (sup_le _ _).2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.empty_of_not_nonempty $ by exact λ ⟨h⟩, h.elim0).trans equiv.ulift.symm⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) @[simp] theorem nat_cast_pow {m n : ℕ} : (nat.pow m n : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := some_spec (P n (λ y _, F y)), rw [← show F n = some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, have : ∀ i, ¬ ∀ b, ∃ a, G ⟨i, a⟩ i = b, { refine λ i h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, simp [classical.not_forall] at this, exact let ⟨C, hc⟩ := axiom_of_choice this, ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _), end end cardinal
29cd7f92782f5eda379b735f8577e6c493c8e4cf
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/constructions/finite_cats.hlean
78a2d339bb31a1554ec6a16e788374fbfd7a3716
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
5,177
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Some finite categories which are neither discrete nor indiscrete -/ import ..functor.basic types.sum open bool unit is_trunc sum eq functor equiv namespace category variables {A : Type} (R : A → A → Type) (H : Π⦃a b c⦄, R a b → R b c → empty) [HR : Πa b, is_hset (R a b)] [HA : is_trunc 1 A] include H HR HA -- we call a category sparse if you cannot compose two morphism, except the ones which come from equality definition sparse_category' [constructor] : precategory A := precategory.mk (λa b, R a b ⊎ a = b) begin intros a b c g f, induction g with rg pg: induction f with rf pf, { exfalso, exact H rf rg}, { exact inl (pf⁻¹ ▸ rg)}, { exact inl (pg ▸ rf)}, { exact inr (pf ⬝ pg)}, end (λa, inr idp) abstract begin intros a b c d h g f, induction h with rh ph: induction g with rg pg: induction f with rf pf: esimp: try induction pf; try induction pg; try induction ph: esimp; try (exfalso; apply H;assumption;assumption) end end abstract by intros a b f; induction f with rf pf: reflexivity end abstract by intros a b f; (induction f with rf pf: esimp); rewrite idp_con end definition sparse_category [constructor] : Precategory := precategory.Mk (sparse_category' R @H) definition sparse_category_functor [constructor] (C : Precategory) (f : A → C) (g : Π{a b} (r : R a b), f a ⟶ f b) : sparse_category R H ⇒ C := functor.mk f (λa b, sum.rec g (eq.rec id)) (λa, idp) abstract begin intro a b c g f, induction g with rg pg: induction f with rf pf: esimp: try induction pg: try induction pf: esimp, exfalso, exact H rf rg, exact !id_right⁻¹, exact !id_left⁻¹, exact !id_id⁻¹ end end omit H HR HA section equalizer inductive equalizer_category_hom : bool → bool → Type := | f1 : equalizer_category_hom ff tt | f2 : equalizer_category_hom ff tt open equalizer_category_hom theorem is_hset_equalizer_category_hom (b₁ b₂ : bool) : is_hset (equalizer_category_hom b₁ b₂) := begin assert H : Πb b', equalizer_category_hom b b' ≃ bool.rec (bool.rec empty bool) (λb, empty) b b', { intro b b', fapply equiv.MK, { intro x, induction x, exact ff, exact tt}, { intro v, induction b: induction b': induction v, exact f1, exact f2}, { intro v, induction b: induction b': induction v: reflexivity}, { intro x, induction x: reflexivity}}, apply is_trunc_equiv_closed_rev, apply H, induction b₁: induction b₂: exact _ end local attribute is_hset_equalizer_category_hom [instance] definition equalizer_category [constructor] : Precategory := sparse_category equalizer_category_hom begin intro a b c g f; cases g: cases f end definition equalizer_category_functor [constructor] (C : Precategory) {x y : C} (f g : x ⟶ y) : equalizer_category ⇒ C := sparse_category_functor _ _ C (bool.rec x y) begin intro a b h; induction h, exact f, exact g end end equalizer section pullback inductive pullback_category_ob : Type := | TR : pullback_category_ob | BL : pullback_category_ob | BR : pullback_category_ob theorem pullback_category_ob_decidable_equality : decidable_eq pullback_category_ob := begin intro x y; induction x: induction y: try exact decidable.inl idp: apply decidable.inr; contradiction end open pullback_category_ob inductive pullback_category_hom : pullback_category_ob → pullback_category_ob → Type := | f1 : pullback_category_hom TR BR | f2 : pullback_category_hom BL BR open pullback_category_hom theorem is_hset_pullback_category_hom (b₁ b₂ : pullback_category_ob) : is_hset (pullback_category_hom b₁ b₂) := begin assert H : Πb b', pullback_category_hom b b' ≃ pullback_category_ob.rec (λb, empty) (λb, empty) (pullback_category_ob.rec unit unit empty) b' b, { intro b b', fapply equiv.MK, { intro x, induction x: exact star}, { intro v, induction b: induction b': induction v, exact f1, exact f2}, { intro v, induction b: induction b': induction v: reflexivity}, { intro x, induction x: reflexivity}}, apply is_trunc_equiv_closed_rev, apply H, induction b₁: induction b₂: exact _ end local attribute is_hset_pullback_category_hom pullback_category_ob_decidable_equality [instance] definition pullback_category [constructor] : Precategory := sparse_category pullback_category_hom begin intro a b c g f; cases g: cases f end definition pullback_category_functor [constructor] (C : Precategory) {x y z : C} (f : x ⟶ z) (g : y ⟶ z) : pullback_category ⇒ C := sparse_category_functor _ _ C (pullback_category_ob.rec x y z) begin intro a b h; induction h, exact f, exact g end end pullback end category
1cdaceb993f82352be7b8ee49480326c44f1e76d
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/measurable_space.lean
7b9542e4bb45d36898179da8ecc446cc5be4909a
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
61,236
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import data.tprod import order.filter.lift /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function, measurable equivalence, dynkin system, π-λ theorem, π-system -/ open set encodable function equiv open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀ s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀ f : ℕ → set α, (∀ i, is_measurable' (f i)) → is_measurable' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space (order_dual α) := h section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := compl_compl s ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl @[nontriviality] lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma set.finite.is_measurable_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := is_measurable.bUnion hs.countable h lemma finset.is_measurable_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := s.finite_to_set.is_measurable_bUnion h lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma set.finite.is_measurable_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := is_measurable.sUnion hs.countable h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.encodable lemma is_measurable.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := is_measurable.Union h lemma is_measurable.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.Inter h end fintype lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.is_measurable_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.bInter hs.countable h lemma finset.is_measurable_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := s.finite_to_set.is_measurable_bInter h lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma set.finite.is_measurable_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := is_measurable.sInter hs.countable h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀ i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ s, is_measurable.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_is_measurable [measurable_space α] : generate_from {s : set α | is_measurable s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, is_measurable_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λ s, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λ s, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @is_measurable_empty _ ⊥) (λ s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂ m ∈ ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λ m, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @is_measurable _ m s} s := begin change @is_measurable' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @is_measurable _ (m i) s} s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λ s, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λ s, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃ i, s' i, m.is_measurable_Union _ (λ i, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥ : measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} : (⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤ : measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ t ∈ s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[nontriviality] lemma subsingleton.measurable [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable.piecewise {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ lemma measurable.ite {p : α → Prop} {_ : decidable_pred p} {f g : α → β} (hp : is_measurable {a : α | p a}) (hf : measurable f) (hg : measurable g) : measurable (λ x, ite (p x) (f x) (g x)) := measurable.piecewise hp hf hg @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, is_measurable.const (a ∈ s) lemma measurable.indicator [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one [has_one α] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 lemma measurable_of_not_nonempty (h : ¬ nonempty α) (f : α → β) : measurable f := begin assume s hs, convert is_measurable.empty, exact eq_empty_of_not_nonempty h _, end end measurable_functions section constructions variables [measurable_space α] [measurable_space β] [measurable_space γ] instance : measurable_space empty := ⊤ instance : measurable_space punit := ⊤ -- this also works for `unit` instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit (f : unit → α) : measurable f := measurable_from_top section nat lemma measurable_from_nat {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {α} {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λ a : α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λ a : s, f a)) (hd : measurable (λ a : t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λ a, (f a).1)) (hf₂ : measurable (λ a, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λ a, (f a).1) ∧ measurable (λ a, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi variables {π : δ → Type*} instance measurable_space.pi [m : Π a, measurable_space (π a)] : measurable_space (Π a, π a) := ⨆ a, (m a).comap (λ b, b a) variables [Π a, measurable_space (π a)] [measurable_space γ] lemma measurable_pi_iff {g : α → Π a, π a} : measurable g ↔ ∀ a, measurable (λ x, g x a) := by simp_rw [measurable_iff_comap_le, measurable_space.pi, measurable_space.comap_supr, measurable_space.comap_comp, function.comp, supr_le_iff] lemma measurable_pi_apply (a : δ) : measurable (λ f : Π a, π a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable.eval {a : δ} {g : α → Π a, π a} (hg : measurable g) : measurable (λ x, g x a) := (measurable_pi_apply a).comp hg lemma measurable_pi_lambda (f : α → Π a, π a) (hf : ∀ a, measurable (λ c, f c a)) : measurable f := measurable_pi_iff.mpr hf /-- The function `update f a : π a → Π a, π a` is always measurable. This doesn't require `f` to be measurable. This should not be confused with the statement that `update f a x` is measurable. -/ lemma measurable_update (f : Π (a : δ), π a) {a : δ} : measurable (update f a) := begin apply measurable_pi_lambda, intro x, by_cases hx : x = a, { cases hx, convert measurable_id, ext, simp }, simp_rw [update_noteq hx], apply measurable_const, end /- Even though we cannot use projection notation, we still keep a dot to be consistent with similar lemmas, like `is_measurable.prod`. -/ lemma is_measurable.pi {s : set δ} {t : Π i : δ, set (π i)} (hs : countable s) (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (s.pi t) := by { rw [pi_def], exact is_measurable.bInter hs (λ i hi, measurable_pi_apply _ (ht i hi)) } lemma is_measurable.pi_univ [encodable δ] {t : Π i : δ, set (π i)} (ht : ∀ i, is_measurable (t i)) : is_measurable (pi univ t) := is_measurable.pi (countable_encodable _) (λ i _, ht i) lemma is_measurable_pi_of_nonempty {s : set δ} {t : Π i, set (π i)} (hs : countable s) (h : (pi s t).nonempty) : is_measurable (pi s t) ↔ ∀ i ∈ s, is_measurable (t i) := begin rcases h with ⟨f, hf⟩, refine ⟨λ hst i hi, _, is_measurable.pi hs⟩, convert measurable_update f hst, rw [update_preimage_pi hi], exact λ j hj _, hf j hj end lemma is_measurable_pi {s : set δ} {t : Π i, set (π i)} (hs : countable s) : is_measurable (pi s t) ↔ (∀ i ∈ s, is_measurable (t i)) ∨ pi s t = ∅ := begin cases (pi s t).eq_empty_or_nonempty with h h, { simp [h] }, { simp [is_measurable_pi_of_nonempty hs, h, ← not_nonempty_iff_eq_empty] } end section fintype local attribute [instance] fintype.encodable lemma is_measurable.pi_fintype [fintype δ] {s : set δ} {t : Π i, set (π i)} (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (pi s t) := is_measurable.pi (countable_encodable _) ht end fintype end pi instance tprod.measurable_space (π : δ → Type*) [∀ x, measurable_space (π x)] : ∀ (l : list δ), measurable_space (list.tprod π l) | [] := punit.measurable_space | (i :: is) := @prod.measurable_space _ _ _ (tprod.measurable_space is) section tprod open list variables {π : δ → Type*} [∀ x, measurable_space (π x)] lemma measurable_tprod_mk (l : list δ) : measurable (@tprod.mk δ π l) := begin induction l with i l ih, { exact measurable_const }, { exact (measurable_pi_apply i).prod_mk ih } end lemma measurable_tprod_elim : ∀ {l : list δ} {i : δ} (hi : i ∈ l), measurable (λ (v : tprod π l), v.elim hi) | (i :: is) j hj := begin by_cases hji : j = i, { subst hji, simp [measurable_fst] }, { rw [funext $ tprod.elim_of_ne _ hji], exact (measurable_tprod_elim (hj.resolve_left hji)).comp measurable_snd } end lemma measurable_tprod_elim' {l : list δ} (h : ∀ i, i ∈ l) : measurable (tprod.elim' h : tprod π l → Π i, π i) := measurable_pi_lambda _ (λ i, measurable_tprod_elim (h i)) lemma is_measurable.tprod (l : list δ) {s : ∀ i, set (π i)} (hs : ∀ i, is_measurable (s i)) : is_measurable (set.tprod l s) := by { induction l with i l ih, exact is_measurable.univ, exact (hs i).prod ih } end tprod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_elim {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {α} {β : α → Type*} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) infix ` ≃ᵐ `:25 := measurable_equiv namespace measurable_equiv variables (α β) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] instance : has_coe_to_fun (α ≃ᵐ β) := ⟨λ _, α → β, λ e, e.to_equiv⟩ variables {α β} lemma coe_eq (e : α ≃ᵐ β) : (e : α → β) = e.to_equiv := rfl protected lemma measurable (e : α ≃ᵐ β) : measurable (e : α → β) := e.measurable_to_fun @[simp] lemma coe_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β) : α → β) = e := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : α ≃ᵐ α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance : inhabited (α ≃ᵐ α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ @[simps] def trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } /-- The inverse of an equivalence between measurable spaces. -/ @[simps] def symm (ab : α ≃ᵐ β) : β ≃ᵐ α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } @[simp] lemma coe_symm_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β).symm : β → α) = e.symm := rfl @[simp] theorem symm_comp_self (e : α ≃ᵐ β) : e.symm ∘ e = id := funext e.left_inv @[simp] theorem self_comp_symm (e : α ≃ᵐ β) : e ∘ e.symm = id := funext e.right_inv /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : α ≃ᵐ β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable_coe_iff {f : β → γ} (e : α ≃ᵐ β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λ h, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ := { to_equiv := prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := (ab.measurable_to_fun.comp measurable_id.fst).prod_mk (cd.measurable_to_fun.comp measurable_id.snd), measurable_inv_fun := (ab.measurable_inv_fun.comp measurable_id.fst).prod_mk (cd.measurable_inv_fun.comp measurable_id.snd) } /-- Products of measurable spaces are symmetric. -/ def prod_comm : α × β ≃ᵐ β × α := { to_equiv := prod_comm α β, measurable_to_fun := measurable_id.snd.prod_mk measurable_id.fst, measurable_inv_fun := measurable_id.snd.prod_mk measurable_id.fst } /-- Products of measurable spaces are associative. -/ def prod_assoc : (α × β) × γ ≃ᵐ α × (β × γ) := { to_equiv := prod_assoc α β γ, measurable_to_fun := measurable_fst.fst.prod_mk $ measurable_fst.snd.prod_mk measurable_snd, measurable_inv_fun := (measurable_fst.prod_mk measurable_snd.fst).prod_mk measurable_snd.snd } /-- Sums of measurable spaces are symmetric. -/ def sum_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ := { to_equiv := sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod (s : set α) (t : set β) : s.prod t ≃ᵐ s × t := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable_id.subtype_coe.fst.subtype_mk.prod_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable_id.fst.subtype_coe.prod_mk measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : (univ : set α) ≃ᵐ α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton (a : α) : ({a} : set α) ≃ᵐ unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image (f : α → β) (s : set α) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : s ≃ᵐ (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range (f : α → β) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : α ≃ᵐ (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl : (range sum.inl : set (α ⊕ β)) ≃ᵐ α := { to_fun := λ ab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ a, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr : (range sum.inr : set (α ⊕ β)) ≃ᵐ β := { to_fun := λ ab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ b, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : (α ⊕ β) × γ ≃ᵐ (α × γ) ⊕ (β × γ) := { to_equiv := sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp measurable_fst).prod_mk measurable_snd) ((measurable_inr.comp measurable_fst).prod_mk measurable_snd) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : α × (β ⊕ γ) ≃ᵐ (α × β) ⊕ (α × γ) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ ((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ)) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) variables {π π' : δ' → Type*} [∀ x, measurable_space (π x)] [∀ x, measurable_space (π' x)] /-- A family of measurable equivalences `Π a, β₁ a ≃ᵐ β₂ a` generates a measurable equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right (e : Π a, π a ≃ᵐ π' a) : (Π a, π a) ≃ᵐ (Π a, π' a) := { to_equiv := Pi_congr_right (λ a, (e a).to_equiv), measurable_to_fun := measurable_pi_lambda _ (λ i, (e i).measurable_to_fun.comp (measurable_pi_apply i)), measurable_inv_fun := measurable_pi_lambda _ (λ i, (e i).measurable_inv_fun.comp (measurable_pi_apply i)) } /-- Pi-types are measurably equivalent to iterated products. -/ noncomputable def pi_measurable_equiv_tprod {l : list δ'} (hnd : l.nodup) (h : ∀ i, i ∈ l) : (Π i, π i) ≃ᵐ list.tprod π l := { to_equiv := list.tprod.pi_equiv_tprod hnd h, measurable_to_fun := measurable_tprod_mk l, measurable_inv_fun := measurable_tprod_elim' h } end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_is_measurable [measurable_space α] : is_pi_system {s : set α | is_measurable s} := λ s t hs ht _, hs.inter ht /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀ n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃ n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, is_measurable t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, is_measurable (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h lemma eventually.exists_measurable_mem_of_lift' {f : filter α} [is_measurably_generated f] {p : set α → Prop} (h : ∀ᶠ s in f.lift' powerset, p s) : ∃ s ∈ f, is_measurable s ∧ p s := let ⟨s, hsf, hs⟩ := eventually_lift'_powerset.1 h, ⟨t, htf, htm, hts⟩ := is_measurably_generated.exists_measurable_subset hsf in ⟨t, htf, htm, hs t hts⟩ instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning (C : set (set α)) : Prop := ∃ (s : ℕ → set α), (∀ n, s n ∈ C) ∧ (⋃ n, s n) = univ lemma is_countably_spanning_is_measurable [measurable_space α] : is_countably_spanning {s : set α | is_measurable s} := ⟨λ _, univ, λ _, is_measurable.univ, Union_const _⟩
af7d7204a15a49f36f91dbbd32a354f10ec4eb28
ad3e8f15221a986da27c99f371922c0b3f5792b6
/src/week06/e01_Z.lean
0ab25745d17651715b19a95aa30e83a5ac9e9794
[]
no_license
VArtem/lean-itmo
a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1
dc44cd06f9f5b984d051831b3aaa7364e64c2dc4
refs/heads/main
1,683,761,214,467
1,622,821,295,000
1,622,821,295,000
357,236,048
12
0
null
null
null
null
UTF-8
Lean
false
false
9,724
lean
import tactic -- Основано на https://github.com/ImperialCollegeLondon/formalising-mathematics/tree/master/src/week_7 -- Я убрал довольно много материала оттуда, посмотрите по возможности оригинал, в котором Kevin уходит гораздо глубже в концепцию `quotient` -- Больше в книге Theorem Proving in Lean: https://leanprover.github.io/theorem_proving_in_lean/axioms_and_computation.html#quotients -- В этом файле мы изучим конструкцию `quotient` -- И построим целые числа как классы эквивалентности пар натуральных чисел (a, b) -- Где (a, b) ≈ (c, d) ↔ a + d = b + c -- В первом приближении `quotient` можно описать как "тип классов эквивалентности по бинарному отношению" -- Пусть у нас есть тип `α` и отношение эквивалентности `r : α → α → Prop` -- `abbreviation` это просто синтаксический синоним abbreviation N2 := ℕ × ℕ namespace N2 section product def foo : ℕ × ℕ := (3, 4) #reduce (foo.fst, foo.snd) -- Аналогично можно писать `foo.1` или `foo.2` -- Чтобы доказать равенство двух пар, можно использовать `ext` example (X Y : Type) (s t : X × Y) (h1 : s.fst = t.fst) (h2 : s.snd = t.snd) : s = t := begin ext, { exact h1 }, { exact h2 }, end -- Чтобы разбить пару `x` на два натуральных числа, можно использовать `cases x with a b` example (A B : Type) (x : A × B) : x = (x.1, x.2) := begin cases x with a b, -- ⊢ (a, b) = ((a, b).fst, (a, b).snd) dsimp only, -- упрощает `(a, b).fst` до `a`. -- ⊢ (a, b) = (a, b) refl, end end product -- Как построить целые числа на основе натуральных? -- Стандартная конструкция: целое число либо `n : ℕ`, либо `-n-1` #check ℤ -- Иначе целые числа можно представить, как разность двух натуральных чисел, например, -1 = 3 - 4 -- Такое представление неоднозначно, 3 - 4 = 5 - 6 = ... -- В каком случае две пары задают одно число? a - b = c - d ↔ a + d = c + b -- Определим отношение `r : N2 → N2 → Prop`: r (a, b) (c, d) = a + d = c + b def r (ab cd : N2) : Prop := ab.1 + cd.2 = cd.1 + ab.2 lemma r_def (ab cd : N2) : r ab cd ↔ ab.1 + cd.2 = cd.1 + ab.2 := iff.rfl lemma r_def' (a b c d : ℕ) : r (a,b) (c,d) ↔ a + d = c + b := iff.rfl def r_refl : reflexive r := begin -- `unfold reflexive` раскроет определение и покажет, как оно определено -- не забывайте, что N2 = ℕ × ℕ, поэтому можно делать `rintro ⟨a, b⟩` sorry, end def r_symm : symmetric r := begin sorry, end def r_trans : transitive r := begin sorry, end -- Определим инстанс класса `setoid`: это просто отношение эквивалентности на `N2` instance setoid : setoid N2 := ⟨r, r_refl, r_symm, r_trans⟩ -- Теперь можно использовать `≈` (\~~ или \approx) example (x y : N2) : x ≈ y ↔ r x y := iff.rfl -- Добавим simp-леммы для упрощения жизни в будущем @[simp] lemma equiv_def (ab cd : N2) : ab ≈ cd ↔ ab.1 + cd.2 = cd.1 + ab.2 := begin refl end @[simp] lemma equiv_def' (a b c d : ℕ) : (a,b) ≈ (c,d) ↔ a + d = c + b := iff.rfl end N2 open N2 -- Определим Z как `quotient` по определенному отношению эквивалентности def Z := quotient N2.setoid namespace Z -- По заданной паре типа N2 можно легко получить элемент типа Z как `quotient.mk x` -- Или же `⟦x⟧` def bar : Z := quotient.mk foo -- соответствует целому числу -1. example : bar = ⟦foo⟧ := rfl -- Посмотрим на API `quotient` example (x y : N2) : x ≈ y → ⟦x⟧ = ⟦y⟧ := quotient.sound example (x y : N2) : ⟦x⟧ = ⟦y⟧ → x ≈ y := quotient.exact example (x y : N2) : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := quotient.eq -- Определим и докажем все операции над Z, дойдя до коммутативного кольца -- Определим 0 и 1: def zero : Z := ⟦(0, 0)⟧ def one : Z := ⟦(1, 0)⟧ instance : has_zero Z := ⟨zero⟩ instance : has_one Z := ⟨one⟩ @[simp] lemma zero_def : (0 : Z) = ⟦(0, 0)⟧ := rfl @[simp] lemma one_def : (1 : Z) = ⟦(1, 0)⟧ := rfl /- Определим обратное по сложению число. Как определить функцию для `quotient`? 1) Определим вспомогательное отображение `N2 → Z`: по `(a,b)` выдаем `⟦(b,a)⟧` 2) Докажем, что эта функция константна на классах эквивалентности: `(a, b) ≈ (c, d) → ⟦(b, a)⟧ = ⟦(d, c)⟧` 3) Используем `quotient.lift`, чтобы получить функцию `Z → Z`. -/ def neg_aux (ab : N2) : Z := ⟦(ab.2, ab.1)⟧ @[simp] lemma neg_aux_def (ab : N2) : neg_aux ab = ⟦(ab.2, ab.1)⟧ := rfl def neg : Z → Z := quotient.lift neg_aux begin -- ⊢ ∀ (a b : N2), a ≈ b → neg_aux a = neg_aux b intros a b rab, sorry, end -- нотация `-z` instance : has_neg Z := ⟨neg⟩ @[simp] lemma neg_def (a b : ℕ) : (-⟦(a, b)⟧ : Z) = ⟦(b, a)⟧ := rfl /- Определим сложение. Если бы мы определяли сложение так же, как отрицание, то пришлось бы использовать `lift` дважды: сначала показать, что функция независима по первому аргументу, потом по второму. Есть функция `quotient.lift₂`, которая позволяет взять функцию `f : A → B → C`, и доказательство, что она не меняет значение, если заменить первые два аргумента на эквивалентные, и выдает функцию `A/~ → B/~ → C`. -/ -- Вспомогательное определение сложения (note `(a-b)+(c-d)=(a+c)-(b+d)` ) def add_aux (ab cd : N2) : Z := ⟦(ab.1 + cd.1, ab.2 + cd.2)⟧ -- И simp-лемма для него @[simp] lemma add_aux_def (ab cd : N2) : add_aux ab cd = ⟦(ab.1 + cd.1, ab.2 + cd.2)⟧ := rfl def add : Z → Z → Z := quotient.lift₂ add_aux begin rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨c₁, d₁⟩ ⟨c₂, d₂⟩ rab rcd, sorry, end instance : has_add Z := ⟨add⟩ @[simp] lemma add_def (a b c d : ℕ) : (⟦(a, b)⟧ + ⟦(c, d)⟧ : Z) = ⟦(a+c, b+d)⟧ := rfl -- И определим вычитание целых чисел def sub (x y : Z) : Z := x + -y instance : has_sub Z := ⟨sub⟩ -- Покажем, что Z - коммутативная группа по сложению def add_comm_group : add_comm_group Z := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, -- Используйте `quotient.induction_on` для доказательства лемм про свойства операций над `quotient` -- "Если для всех `x : N2` верно `p ⟦x⟧`, то для всех `y : Z` верно p y" zero_add := begin intro x, apply quotient.induction_on x, clear x, rintro ⟨a, b⟩, simp, end, add_zero := begin sorry, end, -- Для версий с 2 и 3 аргументами есть `quotient.induction_on₂` и `quotient.induction_on₃` -- Не забывайте про `linarith` и `ring` add_assoc := begin sorry, end, add_left_neg := begin sorry, end, add_comm := begin sorry, end, } -- Умножение: `(a-b)*(c-d) = (a*c+b*d)-(a*d+b*c)` def mul_aux (ab cd : N2) : N2 := (ab.1 * cd.1 + ab.2 * cd.2, ab.1 * cd.2 + ab.2 * cd.1) @[simp] lemma mul_aux_def (a b c d : ℕ) : mul_aux (a,b) (c,d) = (a*c+b*d,a*d+b*c) := rfl -- Для разнообразия определим умножение слегка иначе. -- Вместо использования `quotient.lift₂` (который превращает `N2 → N2 → Z` в `Z → Z → Z`), -- используем `quotient.map₂`, который превращает `N2 → N2 → N2` в `Z → Z → Z`. -- `nlinarith` умеет доказывать некоторые цели, содержащие нелинейные [не]равенства def mul : Z → Z → Z := quotient.map₂ mul_aux begin sorry, end instance : has_mul Z := ⟨mul⟩ @[simp] lemma mul_def (a b c d : ℕ) : (⟦(a, b)⟧ * ⟦(c, d)⟧ : Z) = ⟦(a*c+b*d, a*d+b*c)⟧ := rfl -- И наконец, докажем, что Z - коммутативное кольцо def comm_ring : comm_ring Z := { one := 1, add := (+), mul := (*), mul_assoc := begin sorry, end, one_mul := begin sorry, end, mul_one := begin sorry, end, left_distrib := begin sorry, end, right_distrib := begin sorry, end, mul_comm := begin sorry, end, ..add_comm_group } end Z
3c79c05ac5291e4256d74c869f211ef3ba05841b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/enriched/basic.lean
dcb15e7119b03adbc6f0f6bfbe85fb5353b5e766
[ "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
17,189
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 category_theory.monoidal.types import category_theory.monoidal.center /-! # Enriched categories We set up the basic theory of `V`-enriched categories, for `V` an arbitrary monoidal category. We do not assume here that `V` is a concrete category, so there does not need to be a "honest" underlying category! Use `X ⟶[V] Y` to obtain the `V` object of morphisms from `X` to `Y`. This file contains the definitions of `V`-enriched categories and `V`-functors. We don't yet define the `V`-object of natural transformations between a pair of `V`-functors (this requires limits in `V`), but we do provide a presheaf isomorphic to the Yoneda embedding of this object. We verify that when `V = Type v`, all these notion reduce to the usual ones. -/ universes w v u₁ u₂ u₃ noncomputable theory namespace category_theory open opposite open monoidal_category variables (V : Type v) [category.{w} V] [monoidal_category V] /-- A `V`-category is a category enriched in a monoidal category `V`. Note that we do not assume that `V` is a concrete category, so there may not be an "honest" underlying category at all! -/ class enriched_category (C : Type u₁) := (hom : C → C → V) (notation X ` ⟶[] ` Y:10 := hom X Y) (id : Π X, 𝟙_ V ⟶ (X ⟶[] X)) (comp : Π X Y Z, (X ⟶[] Y) ⊗ (Y ⟶[] Z) ⟶ (X ⟶[] Z)) (id_comp : Π X Y, (λ_ (X ⟶[] Y)).inv ≫ (id X ⊗ 𝟙 _) ≫ comp X X Y = 𝟙 _ . obviously) (comp_id : Π X Y, (ρ_ (X ⟶[] Y)).inv ≫ (𝟙 _ ⊗ id Y) ≫ comp X Y Y = 𝟙 _ . obviously) (assoc : Π W X Y Z, (α_ _ _ _).inv ≫ (comp W X Y ⊗ 𝟙 _) ≫ comp W Y Z = (𝟙 _ ⊗ comp X Y Z) ≫ comp W X Z . obviously) notation X ` ⟶[`V`] ` Y:10 := (enriched_category.hom X Y : V) variables (V) {C : Type u₁} [enriched_category V C] /-- The `𝟙_ V`-shaped generalized element giving the identity in a `V`-enriched category. -/ def e_id (X : C) : 𝟙_ V ⟶ (X ⟶[V] X) := enriched_category.id X /-- The composition `V`-morphism for a `V`-enriched category. -/ def e_comp (X Y Z : C) : (X ⟶[V] Y) ⊗ (Y ⟶[V] Z) ⟶ (X ⟶[V] Z) := enriched_category.comp X Y Z -- We don't just use `restate_axiom` here; that would leave `V` as an implicit argument. @[simp, reassoc] lemma e_id_comp (X Y : C) : (λ_ (X ⟶[V] Y)).inv ≫ (e_id V X ⊗ 𝟙 _) ≫ e_comp V X X Y = 𝟙 (X ⟶[V] Y) := enriched_category.id_comp X Y @[simp, reassoc] lemma e_comp_id (X Y : C) : (ρ_ (X ⟶[V] Y)).inv ≫ (𝟙 _ ⊗ e_id V Y) ≫ e_comp V X Y Y = 𝟙 (X ⟶[V] Y) := enriched_category.comp_id X Y @[simp, reassoc] lemma e_assoc (W X Y Z : C) : (α_ _ _ _).inv ≫ (e_comp V W X Y ⊗ 𝟙 _) ≫ e_comp V W Y Z = (𝟙 _ ⊗ e_comp V X Y Z) ≫ e_comp V W X Z := enriched_category.assoc W X Y Z section variables {V} {W : Type v} [category.{w} W] [monoidal_category W] /-- A type synonym for `C`, which should come equipped with a `V`-enriched category structure. In a moment we will equip this with the `W`-enriched category structure obtained by applying the functor `F : lax_monoidal_functor V W` to each hom object. -/ @[nolint has_nonempty_instance unused_arguments] def transport_enrichment (F : lax_monoidal_functor V W) (C : Type u₁) := C instance (F : lax_monoidal_functor V W) : enriched_category W (transport_enrichment F C) := { hom := λ (X Y : C), F.obj (X ⟶[V] Y), id := λ (X : C), F.ε ≫ F.map (e_id V X), comp := λ (X Y Z : C), F.μ _ _ ≫ F.map (e_comp V X Y Z), id_comp := λ X Y, begin rw [comp_tensor_id, category.assoc, ←F.to_functor.map_id, F.μ_natural_assoc, F.to_functor.map_id, F.left_unitality_inv_assoc, ←F.to_functor.map_comp, ←F.to_functor.map_comp, e_id_comp, F.to_functor.map_id], end, comp_id := λ X Y, begin rw [id_tensor_comp, category.assoc, ←F.to_functor.map_id, F.μ_natural_assoc, F.to_functor.map_id, F.right_unitality_inv_assoc, ←F.to_functor.map_comp, ←F.to_functor.map_comp, e_comp_id, F.to_functor.map_id], end, assoc := λ P Q R S, begin rw [comp_tensor_id, category.assoc, ←F.to_functor.map_id, F.μ_natural_assoc, F.to_functor.map_id, ←F.associativity_inv_assoc, ←F.to_functor.map_comp, ←F.to_functor.map_comp, e_assoc, id_tensor_comp, category.assoc, ←F.to_functor.map_id, F.μ_natural_assoc, F.to_functor.map_comp], end, } end /-- Construct an honest category from a `Type v`-enriched category. -/ def category_of_enriched_category_Type (C : Type u₁) [𝒞 : enriched_category (Type v) C] : category.{v} C := { hom := 𝒞.hom, id := λ X, e_id (Type v) X punit.star, comp := λ X Y Z f g, e_comp (Type v) X Y Z ⟨f, g⟩, id_comp' := λ X Y f, congr_fun (e_id_comp (Type v) X Y) f, comp_id' := λ X Y f, congr_fun (e_comp_id (Type v) X Y) f, assoc' := λ W X Y Z f g h, (congr_fun (e_assoc (Type v) W X Y Z) ⟨f, g, h⟩ : _), } /-- Construct a `Type v`-enriched category from an honest category. -/ def enriched_category_Type_of_category (C : Type u₁) [𝒞 : category.{v} C] : enriched_category (Type v) C := { hom := 𝒞.hom, id := λ X p, 𝟙 X, comp := λ X Y Z p, p.1 ≫ p.2, id_comp := λ X Y, by { ext, simp, }, comp_id := λ X Y, by { ext, simp, }, assoc := λ W X Y Z, by { ext ⟨f, g, h⟩, simp, }, } /-- We verify that an enriched category in `Type u` is just the same thing as an honest category. -/ def enriched_category_Type_equiv_category (C : Type u₁) : (enriched_category (Type v) C) ≃ category.{v} C := { to_fun := λ 𝒞, by exactI category_of_enriched_category_Type C, inv_fun := λ 𝒞, by exactI enriched_category_Type_of_category C, left_inv := λ 𝒞, begin cases 𝒞, dsimp [enriched_category_Type_of_category], congr, { ext X ⟨⟩, refl, }, { ext X Y Z ⟨f, g⟩, refl, } end, right_inv := λ 𝒞, by { rcases 𝒞 with ⟨⟨⟨⟩⟩⟩, dsimp, congr, }, }. section variables {W : Type (v+1)} [category.{v} W] [monoidal_category W] [enriched_category W C] /-- A type synonym for `C`, which should come equipped with a `V`-enriched category structure. In a moment we will equip this with the (honest) category structure so that `X ⟶ Y` is `(𝟙_ W) ⟶ (X ⟶[W] Y)`. We obtain this category by transporting the enrichment in `V` along the lax monoidal functor `coyoneda_tensor_unit`, then using the equivalence of `Type`-enriched categories with honest categories. This is sometimes called the "underlying" category of an enriched category, although some care is needed as the functor `coyoneda_tensor_unit`, which always exists, does not necessarily coincide with "the forgetful functor" from `V` to `Type`, if such exists. When `V` is any of `Type`, `Top`, `AddCommGroup`, or `Module R`, `coyoneda_tensor_unit` is just the usual forgetful functor, however. For `V = Algebra R`, the usual forgetful functor is coyoneda of `polynomial R`, not of `R`. (Perhaps we should have a typeclass for this situation: `concrete_monoidal`?) -/ @[nolint has_nonempty_instance unused_arguments] def forget_enrichment (W : Type (v+1)) [category.{v} W] [monoidal_category W] (C : Type u₁) [enriched_category W C] := C variables (W) /-- Typecheck an object of `C` as an object of `forget_enrichment W C`. -/ def forget_enrichment.of (X : C) : forget_enrichment W C := X /-- Typecheck an object of `forget_enrichment W C` as an object of `C`. -/ def forget_enrichment.to (X : forget_enrichment W C) : C := X @[simp] lemma forget_enrichment.to_of (X : C) : forget_enrichment.to W (forget_enrichment.of W X) = X := rfl @[simp] lemma forget_enrichment.of_to (X : forget_enrichment W C) : forget_enrichment.of W (forget_enrichment.to W X) = X := rfl instance category_forget_enrichment : category (forget_enrichment W C) := begin let I : enriched_category (Type v) (transport_enrichment (coyoneda_tensor_unit W) C) := infer_instance, exact enriched_category_Type_equiv_category C I, end /-- We verify that the morphism types in `forget_enrichment W C` are `(𝟙_ W) ⟶ (X ⟶[W] Y)`. -/ example (X Y : forget_enrichment W C) : (X ⟶ Y) = ((𝟙_ W) ⟶ (forget_enrichment.to W X ⟶[W] forget_enrichment.to W Y)) := rfl /-- Typecheck a `(𝟙_ W)`-shaped `W`-morphism as a morphism in `forget_enrichment W C`. -/ def forget_enrichment.hom_of {X Y : C} (f : (𝟙_ W) ⟶ (X ⟶[W] Y)) : forget_enrichment.of W X ⟶ forget_enrichment.of W Y := f /-- Typecheck a morphism in `forget_enrichment W C` as a `(𝟙_ W)`-shaped `W`-morphism. -/ def forget_enrichment.hom_to {X Y : forget_enrichment W C} (f : X ⟶ Y) : (𝟙_ W) ⟶ (forget_enrichment.to W X ⟶[W] forget_enrichment.to W Y) := f @[simp] lemma forget_enrichment.hom_to_hom_of {X Y : C} (f : (𝟙_ W) ⟶ (X ⟶[W] Y)) : forget_enrichment.hom_to W (forget_enrichment.hom_of W f) = f := rfl @[simp] lemma forget_enrichment.hom_of_hom_to {X Y : forget_enrichment W C} (f : X ⟶ Y) : forget_enrichment.hom_of W (forget_enrichment.hom_to W f) = f := rfl /-- The identity in the "underlying" category of an enriched category. -/ @[simp] lemma forget_enrichment_id (X : forget_enrichment W C) : forget_enrichment.hom_to W (𝟙 X) = (e_id W (forget_enrichment.to W X : C)) := category.id_comp _ @[simp] lemma forget_enrichment_id' (X : C) : forget_enrichment.hom_of W (e_id W X) = (𝟙 (forget_enrichment.of W X : C)) := (forget_enrichment_id W (forget_enrichment.of W X)).symm /-- Composition in the "underlying" category of an enriched category. -/ @[simp] lemma forget_enrichment_comp {X Y Z : forget_enrichment W C} (f : X ⟶ Y) (g : Y ⟶ Z) : forget_enrichment.hom_to W (f ≫ g) = (((λ_ (𝟙_ W)).inv ≫ (forget_enrichment.hom_to W f ⊗ forget_enrichment.hom_to W g)) ≫ e_comp W _ _ _) := rfl end /-- A `V`-functor `F` between `V`-enriched categories has a `V`-morphism from `X ⟶[V] Y` to `F.obj X ⟶[V] F.obj Y`, satisfying the usual axioms. -/ structure enriched_functor (C : Type u₁) [enriched_category V C] (D : Type u₂) [enriched_category V D] := (obj : C → D) (map : Π X Y : C, (X ⟶[V] Y) ⟶ (obj X ⟶[V] obj Y)) (map_id' : ∀ X : C, e_id V X ≫ map X X = e_id V (obj X) . obviously) (map_comp' : ∀ X Y Z : C, e_comp V X Y Z ≫ map X Z = (map X Y ⊗ map Y Z) ≫ e_comp V (obj X) (obj Y) (obj Z) . obviously) restate_axiom enriched_functor.map_id' restate_axiom enriched_functor.map_comp' attribute [simp, reassoc] enriched_functor.map_id attribute [simp, reassoc] enriched_functor.map_comp /-- The identity enriched functor. -/ @[simps] def enriched_functor.id (C : Type u₁) [enriched_category V C] : enriched_functor V C C := { obj := λ X, X, map := λ X Y, 𝟙 _, } instance : inhabited (enriched_functor V C C) := ⟨enriched_functor.id V C⟩ /-- Composition of enriched functors. -/ @[simps] def enriched_functor.comp {C : Type u₁} {D : Type u₂} {E : Type u₃} [enriched_category V C] [enriched_category V D] [enriched_category V E] (F : enriched_functor V C D) (G : enriched_functor V D E) : enriched_functor V C E := { obj := λ X, G.obj (F.obj X), map := λ X Y, F.map _ _ ≫ G.map _ _, } section variables {W : Type (v+1)} [category.{v} W] [monoidal_category W] /-- An enriched functor induces an honest functor of the underlying categories, by mapping the `(𝟙_ W)`-shaped morphisms. -/ def enriched_functor.forget {C : Type u₁} {D : Type u₂} [enriched_category W C] [enriched_category W D] (F : enriched_functor W C D) : (forget_enrichment W C) ⥤ (forget_enrichment W D) := { obj := λ X, forget_enrichment.of W (F.obj (forget_enrichment.to W X)), map := λ X Y f, forget_enrichment.hom_of W (forget_enrichment.hom_to W f ≫ F.map (forget_enrichment.to W X) (forget_enrichment.to W Y)), map_comp' := λ X Y Z f g, begin dsimp, apply_fun forget_enrichment.hom_to W, { simp only [iso.cancel_iso_inv_left, category.assoc, tensor_comp, forget_enrichment.hom_to_hom_of, enriched_functor.map_comp, forget_enrichment_comp], refl, }, { intros f g w, apply_fun forget_enrichment.hom_of W at w, simpa using w, }, end, } end section variables {V} variables {D : Type u₂} [enriched_category V D] /-! We now turn to natural transformations between `V`-functors. The mostly commonly encountered definition of an enriched natural transformation is a collection of morphisms ``` (𝟙_ W) ⟶ (F.obj X ⟶[V] G.obj X) ``` satisfying an appropriate analogue of the naturality square. (c.f. https://ncatlab.org/nlab/show/enriched+natural+transformation) This is the same thing as a natural transformation `F.forget ⟶ G.forget`. We formalize this as `enriched_nat_trans F G`, which is a `Type`. However, there's also something much nicer: with appropriate additional hypotheses, there is a `V`-object `enriched_nat_trans_obj F G` which contains more information, and from which one can recover `enriched_nat_trans F G ≃ (𝟙_ V) ⟶ enriched_nat_trans_obj F G`. Using these as the hom-objects, we can build a `V`-enriched category with objects the `V`-functors. For `enriched_nat_trans_obj` to exist, it suffices to have `V` braided and complete. Before assuming `V` is complete, we assume it is braided and define a presheaf `enriched_nat_trans_yoneda F G` which is isomorphic to the Yoneda embedding of `enriched_nat_trans_obj F G` whether or not that object actually exists. This presheaf has components `(enriched_nat_trans_yoneda F G).obj A` what we call the `A`-graded enriched natural transformations, which are collections of morphisms ``` A ⟶ (F.obj X ⟶[V] G.obj X) ``` satisfying a similar analogue of the naturality square, this time incorporating a half-braiding on `A`. (We actually define `enriched_nat_trans F G` as the special case `A := 𝟙_ V` with the trivial half-braiding, and when defining `enriched_nat_trans_yoneda F G` we use the half-braidings coming from the ambient braiding on `V`.) -/ /-- The type of `A`-graded natural transformations between `V`-functors `F` and `G`. This is the type of morphisms in `V` from `A` to the `V`-object of natural transformations. -/ @[ext, nolint has_nonempty_instance] structure graded_nat_trans (A : center V) (F G : enriched_functor V C D) := (app : Π (X : C), A.1 ⟶ (F.obj X ⟶[V] G.obj X)) (naturality : ∀ (X Y : C), (A.2.β (X ⟶[V] Y)).hom ≫ (F.map X Y ⊗ app Y) ≫ e_comp V _ _ _ = (app X ⊗ G.map X Y) ≫ e_comp V _ _ _) variables [braided_category V] open braided_category /-- A presheaf isomorphic to the Yoneda embedding of the `V`-object of natural transformations from `F` to `G`. -/ @[simps] def enriched_nat_trans_yoneda (F G : enriched_functor V C D) : Vᵒᵖ ⥤ (Type (max u₁ w)) := { obj := λ A, graded_nat_trans ((center.of_braided V).obj (unop A)) F G, map := λ A A' f σ, { app := λ X, f.unop ≫ σ.app X, naturality := λ X Y, begin have p := σ.naturality X Y, dsimp at p ⊢, rw [←id_tensor_comp_tensor_id (f.unop ≫ σ.app Y) _, id_tensor_comp, category.assoc, category.assoc, ←braiding_naturality_assoc, id_tensor_comp_tensor_id_assoc, p, ←tensor_comp_assoc,category.id_comp], end }, } -- TODO assuming `[has_limits C]` construct the actual object of natural transformations -- and show that the functor category is `V`-enriched. end section local attribute [instance] category_of_enriched_category_Type /-- We verify that an enriched functor between `Type v` enriched categories is just the same thing as an honest functor. -/ @[simps] def enriched_functor_Type_equiv_functor {C : Type u₁} [𝒞 : enriched_category (Type v) C] {D : Type u₂} [𝒟 : enriched_category (Type v) D] : enriched_functor (Type v) C D ≃ (C ⥤ D) := { to_fun := λ F, { obj := λ X, F.obj X, map := λ X Y f, F.map X Y f, map_id' := λ X, congr_fun (F.map_id X) punit.star, map_comp' := λ X Y Z f g, congr_fun (F.map_comp X Y Z) ⟨f, g⟩, }, inv_fun := λ F, { obj := λ X, F.obj X, map := λ X Y f, F.map f, map_id' := λ X, by { ext ⟨⟩, exact F.map_id X, }, map_comp' := λ X Y Z, by { ext ⟨f, g⟩, exact F.map_comp f g, }, }, left_inv := λ F, by { cases F, simp, }, right_inv := λ F, by { cases F, simp, }, } /-- We verify that the presheaf representing natural transformations between `Type v`-enriched functors is actually represented by the usual type of natural transformations! -/ def enriched_nat_trans_yoneda_Type_iso_yoneda_nat_trans {C : Type v} [enriched_category (Type v) C] {D : Type v} [enriched_category (Type v) D] (F G : enriched_functor (Type v) C D) : enriched_nat_trans_yoneda F G ≅ yoneda.obj ((enriched_functor_Type_equiv_functor F) ⟶ (enriched_functor_Type_equiv_functor G)) := nat_iso.of_components (λ α, { hom := λ σ x, { app := λ X, σ.app X x, naturality' := λ X Y f, congr_fun (σ.naturality X Y) ⟨x, f⟩, }, inv := λ σ, { app := λ X x, (σ x).app X, naturality := λ X Y, by { ext ⟨x, f⟩, exact ((σ x).naturality f), }, }}) (by tidy) end end category_theory
2d4bde63e4fbfbbfd46686fd9a453f7748a9daa0
2fbe653e4bc441efde5e5d250566e65538709888
/src/topology/algebra/module.lean
11c3af9363423e737cf05066752b467c9c20c918
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
18,481
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import topology.algebra.ring linear_algebra.basic ring_theory.algebra /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open topological_space universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul R M lemma continuous.smul {M₂ : Type*} [topological_space M₂] {f : M₂ → R} {g : M₂ → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map end section variables {R : Type*} {M : Type*} {a : R} [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] set_option class.instance_max_depth 36 /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit ((equiv.units_equiv_ne_zero _).inv_fun ⟨_, ha⟩)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_map R M M₂ := (cont : continuous to_fun) notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_equiv (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 /-- Coerce continuous linear maps to functions. -/ instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨_, λ f, f.to_fun⟩ @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, squash_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ def zero : M →L[R] M₂ := ⟨0, by exact continuous_const⟩ instance: has_zero (M →L[R] M₂) := ⟨zero⟩ instance : inhabited (M →L[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, elim_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[elim_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ instance : has_one (M →L[R] M) := ⟨id⟩ @[simp] lemma id_apply : (id : M →L[R] M) x = x := rfl @[simp, elim_cast] lemma coe_id : ((id : M →L[R] M) : M →ₗ[R] M) = linear_map.id := rfl @[simp, elim_cast] lemma coe_id' : ((id : M →L[R] M) : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [topological_add_group M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, move_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[move_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, move_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, move_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, move_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl end add /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, move_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, move_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp id = f := ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [topological_add_group M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } instance : has_mul (M →L[R] M) := ⟨comp⟩ instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } end general_ring section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, move_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/ def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } set_option class.instance_max_depth 55 instance : is_ring_hom (λ c : R, c • (1 : M₂ →L[R] M₂)) := { map_one := one_smul _ _, map_add := λ _ _, ext $ λ _, add_smul _ _ _, map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ } instance : algebra R (M₂ →L[R] M₂) := { to_fun := λ c, c • 1, smul_def' := λ _ _, rfl, commutes' := λ _ _, ext $ λ _, map_smul _ _ _ } end comm_ring end continuous_linear_map namespace continuous_linear_equiv variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨_, λ f, ((f : M →L[R] M₂) : M → M₂)⟩ @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[squash_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only [], ext x, simp only [coe_fn_coe_base] at h, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x @[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff section variable (M) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M ≃L[R] M := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl M } end /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b @[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) : (e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) : (e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id := continuous_linear_map.ext e.symm_apply_apply end continuous_linear_equiv
592d88ce3dc91e65e2c411043722922349955cd0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/testing/slim_check/sampleable.lean
eafc046d9f07728b584ba296d9b7f006e375f224
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
31,382
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.lazy_list.basic import data.tree import data.int.basic import control.bifunctor import tactic.linarith import testing.slim_check.gen /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat subtype.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, nat.sub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _ /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply nat.sub_le_sub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf, linarith }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; linarith /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default α : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, nat.add_lt_of_lt_sub_left h'⟩) <$> shrink (y - x) } /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - abs x, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + abs y, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
4cd30b1085cb5d5ad8a955fce27e597b23b5ad13
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/modular.lean
79919a734a5577b0ce6d2bc6991c8653198813cb
[ "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
24,605
lean
/- Copyright (c) 2021 Alex Kontorovich and Heather Macbeth and Marc Masdeu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth, Marc Masdeu -/ import analysis.complex.upper_half_plane.basic import linear_algebra.general_linear_group import analysis.matrix /-! # The action of the modular group SL(2, ℤ) on the upper half-plane We define the action of `SL(2,ℤ)` on `ℍ` (via restriction of the `SL(2,ℝ)` action in `analysis.complex.upper_half_plane`). We then define the standard fundamental domain (`modular_group.fd`, `𝒟`) for this action and show (`modular_group.exists_smul_mem_fd`) that any point in `ℍ` can be moved inside `𝒟`. ## Main definitions The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟`: `fd := {z | 1 ≤ (z : ℂ).norm_sq ∧ |z.re| ≤ (1 : ℝ) / 2}` The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`, denoted `𝒟ᵒ`: `fdo := {z | 1 < (z : ℂ).norm_sq ∧ |z.re| < (1 : ℝ) / 2}` These notations are localized in the `modular` locale and can be enabled via `open_locale modular`. ## Main results Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)`: `exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟` If both `z` and `γ • z` are in the open domain `𝒟ᵒ` then `z = γ • z`: `eq_smul_self_of_mem_fdo_mem_fdo {z : ℍ} {g : SL(2,ℤ)} (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z` # Discussion Standard proofs make use of the identity `g • z = a / c - 1 / (c (cz + d))` for `g = [[a, b], [c, d]]` in `SL(2)`, but this requires separate handling of whether `c = 0`. Instead, our proof makes use of the following perhaps novel identity (see `modular_group.smul_eq_lc_row0_add`): `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` where there is no issue of division by zero. Another feature is that we delay until the very end the consideration of special matrices `T=[[1,1],[0,1]]` (see `modular_group.T`) and `S=[[0,-1],[1,0]]` (see `modular_group.S`), by instead using abstract theory on the properness of certain maps (phrased in terms of the filters `filter.cocompact`, `filter.cofinite`, etc) to deduce existence theorems, first to prove the existence of `g` maximizing `(g•z).im` (see `modular_group.exists_max_im`), and then among those, to minimize `|(g•z).re|` (see `modular_group.exists_row_one_eq_and_min_re`). -/ /- Disable these instances as they are not the simp-normal form, and having them disabled ensures we state lemmas in this file without spurious `coe_fn` terms. -/ local attribute [-instance] matrix.special_linear_group.has_coe_to_fun local attribute [-instance] matrix.general_linear_group.has_coe_to_fun open complex (hiding abs_one abs_two abs_mul abs_add) open matrix (hiding mul_smul) matrix.special_linear_group upper_half_plane noncomputable theory local notation `SL(` n `, ` R `)`:= special_linear_group (fin n) R local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) ℤ) _ open_locale upper_half_plane complex_conjugate local attribute [instance] fintype.card_fin_even namespace modular_group variables {g : SL(2, ℤ)} (z : ℍ) section bottom_row /-- The two numbers `c`, `d` in the "bottom_row" of `g=[[*,*],[c,d]]` in `SL(2, ℤ)` are coprime. -/ lemma bottom_row_coprime {R : Type*} [comm_ring R] (g : SL(2, R)) : is_coprime ((↑g : matrix (fin 2) (fin 2) R) 1 0) ((↑g : matrix (fin 2) (fin 2) R) 1 1) := begin use [- (↑g : matrix (fin 2) (fin 2) R) 0 1, (↑g : matrix (fin 2) (fin 2) R) 0 0], rw [add_comm, neg_mul, ←sub_eq_add_neg, ←det_fin_two], exact g.det_coe, end /-- Every pair `![c, d]` of coprime integers is the "bottom_row" of some element `g=[[*,*],[c,d]]` of `SL(2,ℤ)`. -/ lemma bottom_row_surj {R : Type*} [comm_ring R] : set.surj_on (λ g : SL(2, R), @coe _ (matrix (fin 2) (fin 2) R) _ g 1) set.univ {cd | is_coprime (cd 0) (cd 1)} := begin rintros cd ⟨b₀, a, gcd_eqn⟩, let A := of ![![a, -b₀], cd], have det_A_1 : det A = 1, { convert gcd_eqn, simp [A, det_fin_two, (by ring : a * (cd 1) + b₀ * (cd 0) = b₀ * (cd 0) + a * (cd 1))] }, refine ⟨⟨A, det_A_1⟩, set.mem_univ _, _⟩, ext; simp [A] end end bottom_row section tendsto_lemmas open filter continuous_linear_map local attribute [instance] matrix.normed_add_comm_group matrix.normed_space local attribute [simp] coe_smul /-- The function `(c,d) → |cz+d|^2` is proper, that is, preimages of bounded-above sets are finite. -/ lemma tendsto_norm_sq_coprime_pair : filter.tendsto (λ p : fin 2 → ℤ, ((p 0 : ℂ) * z + p 1).norm_sq) cofinite at_top := begin let π₀ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 0, let π₁ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 1, let f : (fin 2 → ℝ) →ₗ[ℝ] ℂ := π₀.smul_right (z:ℂ) + π₁.smul_right 1, have f_def : ⇑f = λ (p : fin 2 → ℝ), (p 0 : ℂ) * ↑z + p 1, { ext1, dsimp only [linear_map.coe_proj, real_smul, linear_map.coe_smul_right, linear_map.add_apply], rw mul_one, }, have : (λ (p : fin 2 → ℤ), norm_sq ((p 0 : ℂ) * ↑z + ↑(p 1))) = norm_sq ∘ f ∘ (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p), { ext1, rw f_def, dsimp only [function.comp], rw [of_real_int_cast, of_real_int_cast], }, rw this, have hf : f.ker = ⊥, { let g : ℂ →ₗ[ℝ] (fin 2 → ℝ) := linear_map.pi ![im_lm, im_lm.comp ((z:ℂ) • (conj_ae : ℂ →ₗ[ℝ] ℂ))], suffices : ((z:ℂ).im⁻¹ • g).comp f = linear_map.id, { exact linear_map.ker_eq_bot_of_inverse this }, apply linear_map.ext, intros c, have hz : (z:ℂ).im ≠ 0 := z.2.ne', rw [linear_map.comp_apply, linear_map.smul_apply, linear_map.id_apply], ext i, dsimp only [g, pi.smul_apply, linear_map.pi_apply, smul_eq_mul], fin_cases i, { show ((z : ℂ).im)⁻¹ * (f c).im = c 0, rw [f_def, add_im, of_real_mul_im, of_real_im, add_zero, mul_left_comm, inv_mul_cancel hz, mul_one], }, { show ((z : ℂ).im)⁻¹ * ((z : ℂ) * conj (f c)).im = c 1, rw [f_def, ring_hom.map_add, ring_hom.map_mul, mul_add, mul_left_comm, mul_conj, conj_of_real, conj_of_real, ← of_real_mul, add_im, of_real_im, zero_add, inv_mul_eq_iff_eq_mul₀ hz], simp only [of_real_im, of_real_re, mul_im, zero_add, mul_zero] } }, have h₁ := (linear_equiv.closed_embedding_of_injective hf).tendsto_cocompact, have h₂ : tendsto (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p) cofinite (cocompact _), { convert tendsto.pi_map_Coprod (λ i, int.tendsto_coe_cofinite), { rw Coprod_cofinite }, { rw Coprod_cocompact } }, exact tendsto_norm_sq_cocompact_at_top.comp (h₁.comp h₂) end /-- Given `coprime_pair` `p=(c,d)`, the matrix `[[a,b],[*,*]]` is sent to `a*c+b*d`. This is the linear map version of this operation. -/ def lc_row0 (p : fin 2 → ℤ) : (matrix (fin 2) (fin 2) ℝ) →ₗ[ℝ] ℝ := ((p 0:ℝ) • linear_map.proj 0 + (p 1:ℝ) • linear_map.proj 1 : (fin 2 → ℝ) →ₗ[ℝ] ℝ).comp (linear_map.proj 0) @[simp] lemma lc_row0_apply (p : fin 2 → ℤ) (g : matrix (fin 2) (fin 2) ℝ) : lc_row0 p g = p 0 * g 0 0 + p 1 * g 0 1 := rfl /-- Linear map sending the matrix [a, b; c, d] to the matrix [ac₀ + bd₀, - ad₀ + bc₀; c, d], for some fixed `(c₀, d₀)`. -/ @[simps] def lc_row0_extend {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : (matrix (fin 2) (fin 2) ℝ) ≃ₗ[ℝ] matrix (fin 2) (fin 2) ℝ := linear_equiv.Pi_congr_right ![begin refine linear_map.general_linear_group.general_linear_equiv ℝ (fin 2 → ℝ) (general_linear_group.to_linear (plane_conformal_matrix (cd 0 : ℝ) (-(cd 1 : ℝ)) _)), norm_cast, rw neg_sq, exact hcd.sq_add_sq_ne_zero end, linear_equiv.refl ℝ (fin 2 → ℝ)] /-- The map `lc_row0` is proper, that is, preimages of cocompact sets are finite in `[[* , *], [c, d]]`.-/ theorem tendsto_lc_row0 {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : tendsto (λ g : {g : SL(2, ℤ) // ↑ₘg 1 = cd}, lc_row0 cd ↑(↑g : SL(2, ℝ))) cofinite (cocompact ℝ) := begin let mB : ℝ → (matrix (fin 2) (fin 2) ℝ) := λ t, of ![![t, (-(1:ℤ):ℝ)], coe ∘ cd], have hmB : continuous mB, { refine continuous_matrix _, simp only [fin.forall_fin_two, mB, continuous_const, continuous_id', of_apply, cons_val_zero, cons_val_one, and_self ] }, refine filter.tendsto.of_tendsto_comp _ (comap_cocompact_le hmB), let f₁ : SL(2, ℤ) → matrix (fin 2) (fin 2) ℝ := λ g, matrix.map (↑g : matrix _ _ ℤ) (coe : ℤ → ℝ), have cocompact_ℝ_to_cofinite_ℤ_matrix : tendsto (λ m : matrix (fin 2) (fin 2) ℤ, matrix.map m (coe : ℤ → ℝ)) cofinite (cocompact _), { simpa only [Coprod_cofinite, Coprod_cocompact] using tendsto.pi_map_Coprod (λ i : fin 2, tendsto.pi_map_Coprod (λ j : fin 2, int.tendsto_coe_cofinite)) }, have hf₁ : tendsto f₁ cofinite (cocompact _) := cocompact_ℝ_to_cofinite_ℤ_matrix.comp subtype.coe_injective.tendsto_cofinite, have hf₂ : closed_embedding (lc_row0_extend hcd) := (lc_row0_extend hcd).to_continuous_linear_equiv.to_homeomorph.closed_embedding, convert hf₂.tendsto_cocompact.comp (hf₁.comp subtype.coe_injective.tendsto_cofinite) using 1, ext ⟨g, rfl⟩ i j : 3, fin_cases i; [fin_cases j, skip], -- the following are proved by `simp`, but it is replaced by `simp only` to avoid timeouts. { simp only [mB, mul_vec, dot_product, fin.sum_univ_two, _root_.coe_coe, coe_matrix_coe, int.coe_cast_ring_hom, lc_row0_apply, function.comp_app, cons_val_zero, lc_row0_extend_apply, linear_map.general_linear_group.coe_fn_general_linear_equiv, general_linear_group.to_linear_apply, coe_plane_conformal_matrix, neg_neg, mul_vec_lin_apply, cons_val_one, head_cons, of_apply] }, { convert congr_arg (λ n : ℤ, (-n:ℝ)) g.det_coe.symm using 1, simp only [f₁, mul_vec, dot_product, fin.sum_univ_two, matrix.det_fin_two, function.comp_app, subtype.coe_mk, lc_row0_extend_apply, cons_val_zero, linear_map.general_linear_group.coe_fn_general_linear_equiv, general_linear_group.to_linear_apply, coe_plane_conformal_matrix, mul_vec_lin_apply, cons_val_one, head_cons, map_apply, neg_mul, int.cast_sub, int.cast_mul, neg_sub, of_apply], ring }, { refl } end /-- This replaces `(g•z).re = a/c + *` in the standard theory with the following novel identity: `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` which does not need to be decomposed depending on whether `c = 0`. -/ lemma smul_eq_lc_row0_add {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) (hg : ↑ₘg 1 = p) : ↑(g • z) = ((lc_row0 p ↑(g : SL(2, ℝ))) : ℂ) / (p 0 ^ 2 + p 1 ^ 2) + ((p 1 : ℂ) * z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1)) := begin have nonZ1 : (p 0 : ℂ) ^ 2 + (p 1) ^ 2 ≠ 0 := by exact_mod_cast hp.sq_add_sq_ne_zero, have : (coe : ℤ → ℝ) ∘ p ≠ 0 := λ h, hp.ne_zero (by ext i; simpa using congr_fun h i), have nonZ2 : (p 0 : ℂ) * z + p 1 ≠ 0 := by simpa using linear_ne_zero _ z this, field_simp [nonZ1, nonZ2, denom_ne_zero, -upper_half_plane.denom, -denom_apply], rw (by simp : (p 1 : ℂ) * z - p 0 = ((p 1) * z - p 0) * ↑(det (↑g : matrix (fin 2) (fin 2) ℤ))), rw [←hg, det_fin_two], simp only [int.coe_cast_ring_hom, coe_matrix_coe, int.cast_mul, of_real_int_cast, map_apply, denom, int.cast_sub, _root_.coe_coe,coe_GL_pos_coe_GL_coe_matrix], ring, end lemma tendsto_abs_re_smul {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) : tendsto (λ g : {g : SL(2, ℤ) // ↑ₘg 1 = p}, |((g : SL(2, ℤ)) • z).re|) cofinite at_top := begin suffices : tendsto (λ g : (λ g : SL(2, ℤ), ↑ₘg 1) ⁻¹' {p}, (((g : SL(2, ℤ)) • z).re)) cofinite (cocompact ℝ), { exact tendsto_norm_cocompact_at_top.comp this }, have : ((p 0 : ℝ) ^ 2 + p 1 ^ 2)⁻¹ ≠ 0, { apply inv_ne_zero, exact_mod_cast hp.sq_add_sq_ne_zero }, let f := homeomorph.mul_right₀ _ this, let ff := homeomorph.add_right (((p 1:ℂ)* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, convert ((f.trans ff).closed_embedding.tendsto_cocompact).comp (tendsto_lc_row0 hp), ext g, change ((g : SL(2, ℤ)) • z).re = (lc_row0 p ↑(↑g : SL(2, ℝ))) / (p 0 ^ 2 + p 1 ^ 2) + (((p 1:ℂ )* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, exact_mod_cast (congr_arg complex.re (smul_eq_lc_row0_add z hp g.2)) end end tendsto_lemmas section fundamental_domain local attribute [simp] coe_smul re_smul /-- For `z : ℍ`, there is a `g : SL(2,ℤ)` maximizing `(g•z).im` -/ lemma exists_max_im : ∃ g : SL(2, ℤ), ∀ g' : SL(2, ℤ), (g' • z).im ≤ (g • z).im := begin classical, let s : set (fin 2 → ℤ) := {cd | is_coprime (cd 0) (cd 1)}, have hs : s.nonempty := ⟨![1, 1], is_coprime_one_left⟩, obtain ⟨p, hp_coprime, hp⟩ := filter.tendsto.exists_within_forall_le hs (tendsto_norm_sq_coprime_pair z), obtain ⟨g, -, hg⟩ := bottom_row_surj hp_coprime, refine ⟨g, λ g', _⟩, rw [special_linear_group.im_smul_eq_div_norm_sq, special_linear_group.im_smul_eq_div_norm_sq, div_le_div_left], { simpa [← hg] using hp (↑ₘg' 1) (bottom_row_coprime g') }, { exact z.im_pos }, { exact norm_sq_denom_pos g' z }, { exact norm_sq_denom_pos g z }, end /-- Given `z : ℍ` and a bottom row `(c,d)`, among the `g : SL(2,ℤ)` with this bottom row, minimize `|(g•z).re|`. -/ lemma exists_row_one_eq_and_min_re {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : ∃ g : SL(2,ℤ), ↑ₘg 1 = cd ∧ (∀ g' : SL(2,ℤ), ↑ₘg 1 = ↑ₘg' 1 → |(g • z).re| ≤ |(g' • z).re|) := begin haveI : nonempty {g : SL(2, ℤ) // ↑ₘg 1 = cd} := let ⟨x, hx⟩ := bottom_row_surj hcd in ⟨⟨x, hx.2⟩⟩, obtain ⟨g, hg⟩ := filter.tendsto.exists_forall_le (tendsto_abs_re_smul z hcd), refine ⟨g, g.2, _⟩, { intros g1 hg1, have : g1 ∈ ((λ g : SL(2, ℤ), ↑ₘg 1) ⁻¹' {cd}), { rw [set.mem_preimage, set.mem_singleton_iff], exact eq.trans hg1.symm (set.mem_singleton_iff.mp (set.mem_preimage.mp g.2)) }, exact hg ⟨g1, this⟩ }, end /-- The matrix `T = [[1,1],[0,1]]` as an element of `SL(2,ℤ)` -/ def T : SL(2,ℤ) := ⟨!![1, 1; 0, 1], by norm_num [matrix.det_fin_two_of]⟩ /-- The matrix `S = [[0,-1],[1,0]]` as an element of `SL(2,ℤ)` -/ def S : SL(2,ℤ) := ⟨!![0, -1; 1, 0], by norm_num [matrix.det_fin_two_of]⟩ lemma coe_S : ↑ₘS = !![0, -1; 1, 0] := rfl lemma coe_T : ↑ₘT = !![1, 1; 0, 1] := rfl lemma coe_T_inv : ↑ₘ(T⁻¹) = !![1, -1; 0, 1] := by simp [coe_inv, coe_T, adjugate_fin_two] lemma coe_T_zpow (n : ℤ) : ↑ₘ(T ^ n) = !![1, n; 0, 1] := begin induction n using int.induction_on with n h n h, { rw [zpow_zero, coe_one, matrix.one_fin_two] }, { simp_rw [zpow_add, zpow_one, coe_mul, h, coe_T, matrix.mul_fin_two], congrm !![_, _; _, _], rw [mul_one, mul_one, add_comm] }, { simp_rw [zpow_sub, zpow_one, coe_mul, h, coe_T_inv, matrix.mul_fin_two], congrm !![_, _; _, _]; ring }, end @[simp] lemma T_pow_mul_apply_one (n : ℤ) (g : SL(2, ℤ)) : ↑ₘ(T ^ n * g) 1 = ↑ₘg 1 := by simp [coe_T_zpow, matrix.mul, matrix.dot_product, fin.sum_univ_succ] @[simp] lemma T_mul_apply_one (g : SL(2, ℤ)) : ↑ₘ(T * g) 1 = ↑ₘg 1 := by simpa using T_pow_mul_apply_one 1 g @[simp] lemma T_inv_mul_apply_one (g : SL(2, ℤ)) : ↑ₘ(T⁻¹ * g) 1 = ↑ₘg 1 := by simpa using T_pow_mul_apply_one (-1) g lemma coe_T_zpow_smul_eq {n : ℤ} : (↑((T^n) • z) : ℂ) = z + n := by simp [coe_T_zpow] lemma re_T_zpow_smul (n : ℤ) : ((T^n) • z).re = z.re + n := by rw [←coe_re, coe_T_zpow_smul_eq, add_re, int_cast_re, coe_re] lemma im_T_zpow_smul (n : ℤ) : ((T^n) • z).im = z.im := by rw [←coe_im, coe_T_zpow_smul_eq, add_im, int_cast_im, add_zero, coe_im] lemma re_T_smul : (T • z).re = z.re + 1 := by simpa using re_T_zpow_smul z 1 lemma im_T_smul : (T • z).im = z.im := by simpa using im_T_zpow_smul z 1 lemma re_T_inv_smul : (T⁻¹ • z).re = z.re - 1 := by simpa using re_T_zpow_smul z (-1) lemma im_T_inv_smul : (T⁻¹ • z).im = z.im := by simpa using im_T_zpow_smul z (-1) variables {z} -- If instead we had `g` and `T` of type `PSL(2, ℤ)`, then we could simply state `g = T^n`. lemma exists_eq_T_zpow_of_c_eq_zero (hc : ↑ₘg 1 0 = 0) : ∃ (n : ℤ), ∀ (z : ℍ), g • z = T^n • z := begin have had := g.det_coe, replace had : ↑ₘg 0 0 * ↑ₘg 1 1 = 1, { rw [det_fin_two, hc] at had, linarith, }, rcases int.eq_one_or_neg_one_of_mul_eq_one' had with ⟨ha, hd⟩ | ⟨ha, hd⟩, { use ↑ₘg 0 1, suffices : g = T^(↑ₘg 0 1), { intros z, conv_lhs { rw this, }, }, ext i j, fin_cases i; fin_cases j; simp [ha, hc, hd, coe_T_zpow], }, { use -↑ₘg 0 1, suffices : g = -T^(-↑ₘg 0 1), { intros z, conv_lhs { rw [this, SL_neg_smul], }, }, ext i j, fin_cases i; fin_cases j; simp [ha, hc, hd, coe_T_zpow], }, end /- If `c = 1`, then `g` factorises into a product terms involving only `T` and `S`. -/ lemma g_eq_of_c_eq_one (hc : ↑ₘg 1 0 = 1) : g = T^(↑ₘg 0 0) * S * T^(↑ₘg 1 1) := begin have hg := g.det_coe.symm, replace hg : ↑ₘg 0 1 = ↑ₘg 0 0 * ↑ₘg 1 1 - 1, { rw [det_fin_two, hc] at hg, linarith, }, refine subtype.ext _, conv_lhs { rw matrix.eta_fin_two ↑ₘg }, rw [hc, hg], simp only [coe_mul, coe_T_zpow, coe_S, mul_fin_two], congrm !![_, _; _, _]; ring end /-- If `1 < |z|`, then `|S • z| < 1`. -/ lemma norm_sq_S_smul_lt_one (h: 1 < norm_sq z) : norm_sq ↑(S • z) < 1 := by simpa [coe_S] using (inv_lt_inv z.norm_sq_pos zero_lt_one).mpr h /-- If `|z| < 1`, then applying `S` strictly decreases `im`. -/ lemma im_lt_im_S_smul (h: norm_sq z < 1) : z.im < (S • z).im := begin have : z.im < z.im / norm_sq (z:ℂ), { have imz : 0 < z.im := im_pos z, apply (lt_div_iff z.norm_sq_pos).mpr, nlinarith }, convert this, simp only [special_linear_group.im_smul_eq_div_norm_sq], field_simp [norm_sq_denom_ne_zero, norm_sq_ne_zero, S] end /-- The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/ def fd : set ℍ := {z | 1 ≤ (z : ℂ).norm_sq ∧ |z.re| ≤ (1 : ℝ) / 2} /-- The standard open fundamental domain of the action of `SL(2,ℤ)` on `ℍ`. -/ def fdo : set ℍ := {z | 1 < (z : ℂ).norm_sq ∧ |z.re| < (1 : ℝ) / 2} localized "notation (name := modular_group.fd) `𝒟` := modular_group.fd" in modular localized "notation (name := modular_group.fdo) `𝒟ᵒ` := modular_group.fdo" in modular lemma abs_two_mul_re_lt_one_of_mem_fdo (h : z ∈ 𝒟ᵒ) : |2 * z.re| < 1 := begin rw [abs_mul, abs_two, ← lt_div_iff' (@two_pos ℝ _ _)], exact h.2, end lemma three_lt_four_mul_im_sq_of_mem_fdo (h : z ∈ 𝒟ᵒ) : 3 < 4 * z.im^2 := begin have : 1 < z.re * z.re + z.im * z.im := by simpa [complex.norm_sq_apply] using h.1, have := h.2, cases abs_cases z.re; nlinarith, end /-- If `z ∈ 𝒟ᵒ`, and `n : ℤ`, then `|z + n| > 1`. -/ lemma one_lt_norm_sq_T_zpow_smul (hz : z ∈ 𝒟ᵒ) (n : ℤ) : 1 < norm_sq (((T^n) • z) : ℍ) := begin have hz₁ : 1 < z.re * z.re + z.im * z.im := hz.1, have hzn := int.nneg_mul_add_sq_of_abs_le_one n (abs_two_mul_re_lt_one_of_mem_fdo hz).le, have : 1 < (z.re + ↑n) * (z.re + ↑n) + z.im * z.im, { linarith, }, simpa [coe_T_zpow, norm_sq], end lemma eq_zero_of_mem_fdo_of_T_zpow_mem_fdo {n : ℤ} (hz : z ∈ 𝒟ᵒ) (hg : (T^n) • z ∈ 𝒟ᵒ) : n = 0 := begin suffices : |(n : ℝ)| < 1, { rwa [← int.cast_abs, ← int.cast_one, int.cast_lt, int.abs_lt_one_iff] at this, }, have h₁ := hz.2, have h₂ := hg.2, rw [re_T_zpow_smul] at h₂, calc |(n : ℝ)| ≤ |z.re| + |z.re + (n : ℝ)| : abs_add' (n : ℝ) z.re ... < 1/2 + 1/2 : add_lt_add h₁ h₂ ... = 1 : add_halves 1, end /-- Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)` -/ lemma exists_smul_mem_fd (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟 := begin -- obtain a g₀ which maximizes im (g • z), obtain ⟨g₀, hg₀⟩ := exists_max_im z, -- then among those, minimize re obtain ⟨g, hg, hg'⟩ := exists_row_one_eq_and_min_re z (bottom_row_coprime g₀), refine ⟨g, _⟩, -- `g` has same max im property as `g₀` have hg₀' : ∀ (g' : SL(2,ℤ)), (g' • z).im ≤ (g • z).im, { have hg'' : (g • z).im = (g₀ • z).im, { rw [special_linear_group.im_smul_eq_div_norm_sq, special_linear_group.im_smul_eq_div_norm_sq, denom_apply, denom_apply, hg]}, simpa only [hg''] using hg₀ }, split, { -- Claim: `1 ≤ ⇑norm_sq ↑(g • z)`. If not, then `S•g•z` has larger imaginary part contrapose! hg₀', refine ⟨S * g, _⟩, rw mul_smul, exact im_lt_im_S_smul hg₀' }, { show |(g • z).re| ≤ 1 / 2, -- if not, then either `T` or `T'` decrease |Re|. rw abs_le, split, { contrapose! hg', refine ⟨T * g, (T_mul_apply_one _).symm, _⟩, rw [mul_smul, re_T_smul], cases abs_cases ((g • z).re + 1); cases abs_cases (g • z).re; linarith }, { contrapose! hg', refine ⟨T⁻¹ * g, (T_inv_mul_apply_one _).symm, _⟩, rw [mul_smul, re_T_inv_smul], cases abs_cases ((g • z).re - 1); cases abs_cases (g • z).re; linarith } } end section unique_representative variables {z} /-- An auxiliary result en route to `modular_group.c_eq_zero`. -/ lemma abs_c_le_one (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : |↑ₘg 1 0| ≤ 1 := begin let c' : ℤ := ↑ₘg 1 0, let c : ℝ := (c' : ℝ), suffices : 3 * c^2 < 4, { rw [← int.cast_pow, ← int.cast_three, ← int.cast_four, ← int.cast_mul, int.cast_lt] at this, replace this : c' ^ 2 ≤ 1 ^ 2, { linarith, }, rwa [sq_le_sq, abs_one] at this }, suffices : c ≠ 0 → 9 * c^4 < 16, { rcases eq_or_ne c 0 with hc | hc, { rw hc, norm_num, }, { refine (abs_lt_of_sq_lt_sq' _ (by norm_num)).2, specialize this hc, linarith, }, }, intros hc, replace hc : 0 < c^4, { rw pow_bit0_pos_iff; trivial, }, have h₁ := mul_lt_mul_of_pos_right (mul_lt_mul'' (three_lt_four_mul_im_sq_of_mem_fdo hg) (three_lt_four_mul_im_sq_of_mem_fdo hz) (by linarith) (by linarith)) hc, have h₂ : (c * z.im) ^ 4 / norm_sq (denom ↑g z) ^ 2 ≤ 1 := div_le_one_of_le (pow_four_le_pow_two_of_pow_two_le (upper_half_plane.c_mul_im_sq_le_norm_sq_denom z g)) (sq_nonneg _), let nsq := norm_sq (denom g z), calc 9 * c^4 < c^4 * z.im^2 * (g • z).im^2 * 16 : by linarith ... = c^4 * z.im^4 / nsq^2 * 16 : by { rw [special_linear_group.im_smul_eq_div_norm_sq, div_pow], ring, } ... ≤ 16 : by { rw ← mul_pow, linarith, }, end /-- An auxiliary result en route to `modular_group.eq_smul_self_of_mem_fdo_mem_fdo`. -/ lemma c_eq_zero (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : ↑ₘg 1 0 = 0 := begin have hp : ∀ {g' : SL(2, ℤ)} (hg' : g' • z ∈ 𝒟ᵒ), ↑ₘg' 1 0 ≠ 1, { intros, by_contra hc, let a := ↑ₘg' 0 0, let d := ↑ₘg' 1 1, have had : T^(-a) * g' = S * T^d, { rw g_eq_of_c_eq_one hc, group, }, let w := T^(-a) • (g' • z), have h₁ : w = S • (T^d • z), { simp only [w, ← mul_smul, had], }, replace h₁ : norm_sq w < 1 := h₁.symm ▸ norm_sq_S_smul_lt_one (one_lt_norm_sq_T_zpow_smul hz d), have h₂ : 1 < norm_sq w := one_lt_norm_sq_T_zpow_smul hg' (-a), linarith, }, have hn : ↑ₘg 1 0 ≠ -1, { intros hc, replace hc : ↑ₘ(-g) 1 0 = 1, { simp [eq_neg_of_eq_neg hc], }, replace hg : (-g) • z ∈ 𝒟ᵒ := (SL_neg_smul g z).symm ▸ hg, exact hp hg hc, }, specialize hp hg, rcases (int.abs_le_one_iff.mp $ abs_c_le_one hz hg); tauto, end /-- Second Main Fundamental Domain Lemma: if both `z` and `g • z` are in the open domain `𝒟ᵒ`, where `z : ℍ` and `g : SL(2,ℤ)`, then `z = g • z`. -/ lemma eq_smul_self_of_mem_fdo_mem_fdo (hz : z ∈ 𝒟ᵒ) (hg : g • z ∈ 𝒟ᵒ) : z = g • z := begin obtain ⟨n, hn⟩ := exists_eq_T_zpow_of_c_eq_zero (c_eq_zero hz hg), rw hn at hg ⊢, simp [eq_zero_of_mem_fdo_of_T_zpow_mem_fdo hz hg, one_smul], end end unique_representative end fundamental_domain end modular_group
a8e539c3907f9b71ae11ecd8689b035f180fc8a2
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.10.lean
e52225bdf906f48c7925d1353fa65674637935e1
[]
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
1,331
lean
/- page 80 -/ import standard import standard namespace hide -- BEGIN inductive empty : Type inductive unit : Type := star : unit inductive bool : Type := | ff : bool | tt : bool -- END /- introduction and elimination rules for these - empty - no introduction rule - the elimination rule lets us produce a value of anything from a value of type empty: -/ theorem empty_elim : ∀ A : Type, empty → A := λ (A : Type) (e : empty), empty.cases_on (λ e, A) e /- - unit - one (always applicable) introduction rule (star) - no elimination rule - bool - two introduction rules (always applicable) - elimination rule provides "if / then / else" -/ open hide.bool definition band (b1 b2 : bool) : bool := bool.cases_on b1 ff b2 definition bor (b1 b2 : bool) : bool := bool.cases_on b1 b2 tt definition bnot (b : bool) : bool := bool.cases_on b tt ff variables a b : bool example : ff = (band ff ff) := rfl eval bnot (band ff ff) eval bor (bnot ff) (bnot ff) theorem demorgan1 : bnot (band a b) = bor (bnot a) (bnot b) := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem demorgan2 : bnot (bor a b) = band (bnot a) (bnot b) := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) end hide
053f19a7ccfd3b883663179144e286f232c033bc
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/tactic/fix_by_cases.lean
f35bd0637c3ff7f5a559a5f578d940125fd65c40
[ "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
1,013
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ /-! # Fix the `by_cases` tactic The core `by_cases` tactic has several bugs: - It only works if the proposition is decidable. - It sometimes unfolds the proposition. We override the `by_cases` tactic with a correct implementation here. -/ namespace tactic /-- Do not use this function directly, use `tactic.by_cases`. -/ meta def by_cases' (e : expr) (h : name) : tactic unit := do dec_e ← mk_app ``decidable [e] <|> fail "by_cases tactic failed, type is not a proposition", inst ← mk_instance dec_e <|> pure `(classical.prop_decidable %%e), tgt ← target, expr.sort tgt_u ← infer_type tgt >>= whnf, g1 ← mk_meta_var (e.imp tgt), g2 ← mk_meta_var (`(¬ %%e).imp tgt), focus1 $ do exact $ expr.const ``dite [tgt_u] e inst tgt g1 g2, set_goals [g1, g2], all_goals' $ intro h >> skip attribute [vm_override by_cases'] by_cases end tactic
c9eac712e8a1a863acb1cac8d5f57b94d723f9a4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/game/impartial.lean
f310757f0eaf48a0dc3dd25852a407de609d2feb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,897
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import set_theory.game.basic import tactic.nth_rewrite /-! # Basic definitions about impartial (pre-)games We will define an impartial game, one in which left and right can make exactly the same moves. Our definition differs slightly by saying that the game is always equivalent to its negative, no matter what moves are played. This allows for games such as poker-nim to be classifed as impartial. -/ universe u open_locale pgame namespace pgame /-- The definition for a impartial game, defined using Conway induction. -/ def impartial_aux : pgame → Prop | G := G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j) using_well_founded { dec_tac := pgame_wf_tac } lemma impartial_aux_def {G : pgame} : G.impartial_aux ↔ G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j) := by rw impartial_aux /-- A typeclass on impartial games. -/ class impartial (G : pgame) : Prop := (out : impartial_aux G) lemma impartial_iff_aux {G : pgame} : G.impartial ↔ G.impartial_aux := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma impartial_def {G : pgame} : G.impartial ↔ G ≈ -G ∧ (∀ i, impartial (G.move_left i)) ∧ ∀ j, impartial (G.move_right j) := by simpa only [impartial_iff_aux] using impartial_aux_def namespace impartial instance impartial_zero : impartial 0 := by { rw impartial_def, dsimp, simp } instance impartial_star : impartial star := by { rw impartial_def, simpa using impartial.impartial_zero } lemma neg_equiv_self (G : pgame) [h : G.impartial] : G ≈ -G := (impartial_def.1 h).1 @[simp] lemma mk_neg_equiv_self (G : pgame) [h : G.impartial] : -⟦G⟧ = ⟦G⟧ := quot.sound (neg_equiv_self G).symm instance move_left_impartial {G : pgame} [h : G.impartial] (i : G.left_moves) : (G.move_left i).impartial := (impartial_def.1 h).2.1 i instance move_right_impartial {G : pgame} [h : G.impartial] (j : G.right_moves) : (G.move_right j).impartial := (impartial_def.1 h).2.2 j theorem impartial_congr : ∀ {G H : pgame} (e : G ≡r H) [G.impartial], H.impartial | G H := λ e, begin introI h, exact impartial_def.2 ⟨e.symm.equiv.trans ((neg_equiv_self G).trans (neg_equiv_neg_iff.2 e.equiv)), λ i, impartial_congr (e.move_left_symm i), λ j, impartial_congr (e.move_right_symm j)⟩ end using_well_founded { dec_tac := pgame_wf_tac } instance impartial_add : ∀ (G H : pgame) [G.impartial] [H.impartial], (G + H).impartial | G H := begin introsI hG hH, rw impartial_def, refine ⟨(add_congr (neg_equiv_self _) (neg_equiv_self _)).trans (neg_add_relabelling _ _).equiv.symm, λ k, _, λ k, _⟩, { apply left_moves_add_cases k, all_goals { intro i, simp only [add_move_left_inl, add_move_left_inr], apply impartial_add } }, { apply right_moves_add_cases k, all_goals { intro i, simp only [add_move_right_inl, add_move_right_inr], apply impartial_add } } end using_well_founded { dec_tac := pgame_wf_tac } instance impartial_neg : ∀ (G : pgame) [G.impartial], (-G).impartial | G := begin introI hG, rw impartial_def, refine ⟨_, λ i, _, λ i, _⟩, { rw neg_neg, exact (neg_equiv_self G).symm }, { rw move_left_neg', apply impartial_neg }, { rw move_right_neg', apply impartial_neg } end using_well_founded { dec_tac := pgame_wf_tac } variables (G : pgame) [impartial G] lemma nonpos : ¬ 0 < G := λ h, begin have h' := neg_lt_neg_iff.2 h, rw [neg_zero, lt_congr_left (neg_equiv_self G).symm] at h', exact (h.trans h').false end lemma nonneg : ¬ G < 0 := λ h, begin have h' := neg_lt_neg_iff.2 h, rw [neg_zero, lt_congr_right (neg_equiv_self G).symm] at h', exact (h.trans h').false end /-- In an impartial game, either the first player always wins, or the second player always wins. -/ lemma equiv_or_fuzzy_zero : G ≈ 0 ∨ G ‖ 0 := begin rcases lt_or_equiv_or_gt_or_fuzzy G 0 with h | h | h | h, { exact ((nonneg G) h).elim }, { exact or.inl h }, { exact ((nonpos G) h).elim }, { exact or.inr h } end @[simp] lemma not_equiv_zero_iff : ¬ G ≈ 0 ↔ G ‖ 0 := ⟨(equiv_or_fuzzy_zero G).resolve_left, fuzzy.not_equiv⟩ @[simp] lemma not_fuzzy_zero_iff : ¬ G ‖ 0 ↔ G ≈ 0 := ⟨(equiv_or_fuzzy_zero G).resolve_right, equiv.not_fuzzy⟩ lemma add_self : G + G ≈ 0 := (add_congr_left (neg_equiv_self G)).trans (add_left_neg_equiv G) @[simp] lemma mk_add_self : ⟦G⟧ + ⟦G⟧ = 0 := quot.sound (add_self G) /-- This lemma doesn't require `H` to be impartial. -/ lemma equiv_iff_add_equiv_zero (H : pgame) : H ≈ G ↔ H + G ≈ 0 := by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_right_cancel_iff _ _ (-⟦G⟧)], simpa } /-- This lemma doesn't require `H` to be impartial. -/ lemma equiv_iff_add_equiv_zero' (H : pgame) : G ≈ H ↔ G + H ≈ 0 := by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_left_cancel_iff _ _ (-⟦G⟧), eq_comm], simpa } lemma le_zero_iff {G : pgame} [G.impartial] : G ≤ 0 ↔ 0 ≤ G := by rw [←zero_le_neg_iff, le_congr_right (neg_equiv_self G)] lemma lf_zero_iff {G : pgame} [G.impartial] : G ⧏ 0 ↔ 0 ⧏ G := by rw [←zero_lf_neg_iff, lf_congr_right (neg_equiv_self G)] lemma equiv_zero_iff_le: G ≈ 0 ↔ G ≤ 0 := ⟨and.left, λ h, ⟨h, le_zero_iff.1 h⟩⟩ lemma fuzzy_zero_iff_lf : G ‖ 0 ↔ G ⧏ 0 := ⟨and.left, λ h, ⟨h, lf_zero_iff.1 h⟩⟩ lemma equiv_zero_iff_ge : G ≈ 0 ↔ 0 ≤ G := ⟨and.right, λ h, ⟨le_zero_iff.2 h, h⟩⟩ lemma fuzzy_zero_iff_gf : G ‖ 0 ↔ 0 ⧏ G := ⟨and.right, λ h, ⟨lf_zero_iff.2 h, h⟩⟩ lemma forall_left_moves_fuzzy_iff_equiv_zero : (∀ i, G.move_left i ‖ 0) ↔ G ≈ 0 := begin refine ⟨λ hb, _, λ hp i, _⟩, { rw [equiv_zero_iff_le G, le_zero_lf], exact λ i, (hb i).1 }, { rw fuzzy_zero_iff_lf, exact hp.1.move_left_lf i } end lemma forall_right_moves_fuzzy_iff_equiv_zero : (∀ j, G.move_right j ‖ 0) ↔ G ≈ 0 := begin refine ⟨λ hb, _, λ hp i, _⟩, { rw [equiv_zero_iff_ge G, zero_le_lf], exact λ i, (hb i).2 }, { rw fuzzy_zero_iff_gf, exact hp.2.lf_move_right i } end lemma exists_left_move_equiv_iff_fuzzy_zero : (∃ i, G.move_left i ≈ 0) ↔ G ‖ 0 := begin refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_gf G).2 (lf_of_le_move_left hi.2), λ hn, _⟩, rw [fuzzy_zero_iff_gf G, zero_lf_le] at hn, cases hn with i hi, exact ⟨i, (equiv_zero_iff_ge _).2 hi⟩ end lemma exists_right_move_equiv_iff_fuzzy_zero : (∃ j, G.move_right j ≈ 0) ↔ G ‖ 0 := begin refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_lf G).2 (lf_of_move_right_le hi.1), λ hn, _⟩, rw [fuzzy_zero_iff_lf G, lf_zero_le] at hn, cases hn with i hi, exact ⟨i, (equiv_zero_iff_le _).2 hi⟩ end end impartial end pgame
f2a2ead51907b706c97ff0dbd4cf767773681d8a
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/ring_theory/algebra.lean
9b230ebe2cea9b08e8b57eea8edbeb9af81b52d1
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
31,718
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import data.matrix.basic import linear_algebra.tensor_product import algebra.commute import data.equiv.ring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras (`map`, `comap`). ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ noncomputable theory universes u v w u₁ v₁ open_locale tensor_product section prio -- We set this priority to 0 later in this file set_option default_priority 200 -- see Note [default priority] /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] end semiring -- TODO (semimodule linear maps): once we have them, port next section to semirings section ring variables [comm_ring R] [ring A] [algebra R A] /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := ring_hom.to_algebra ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end ring end algebra instance module.endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } instance matrix_algebra (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by { ext, simp [mul_assoc] }, map_zero' := zero_smul _ _, map_add' := λ _ _, add_smul _ _ _, commutes' := by { intros, simp }, smul_def' := by { intros, simp } } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_inj.comp coe_ring_hom_inj theorem coe_add_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_inj.comp coe_ring_hom_inj @[ext] theorem ext ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.sum f) = s.sum (λx, φ (f x)) := φ.to_ring_hom.map_sum f s section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.prod f) = s.prod (λx, φ (f x)) := φ.to_ring_hom.map_prod f s end comm_semiring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl @[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩ @[simp, norm_cast] lemma coe_to_alg_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map R S r • x : A), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map R S r) ..φ } end alg_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, (commute.cast_int_left x r.1).div_left (commute.cast_nat_left x r.2) end rat /-- A subalgebra is a subring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le' : set.range (algebra_map R A) ≤ carrier) namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ lemma range_le (S : subalgebra R A) : set.range (algebra_map R A) ≤ S := S.range_le' instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ (S : set A)⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T := ⟨λ h x, by rw h, ext⟩ variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance : inhabited S := ⟨0⟩ instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R A).cod_restrict S $ λ x, S.range_le ⟨x, rfl⟩ } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := subtype.val }; intros; refl /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, (S : set A) ≤ (T : set A), le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } /-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/ def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } /-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`, then `T` is an `R`-subalgebra of `A`. -/ def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map R A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } lemma mul_mem (A' : subalgebra R A) (x y : A) : x ∈ A' → y ∈ A' → x * y ∈ A' := @is_submonoid.mul_mem A _ A' _ x y end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := begin haveI : is_subring (set.range φ) := show is_subring (set.range φ.to_ring_hom), by apply_instance, exact ⟨set.range φ, λ y ⟨r, hr⟩, ⟨algebra_map R A r, hr ▸ φ.commutes r⟩⟩ end end alg_hom namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] instance id : algebra R R := (ring_hom.id R).to_algebra namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace algebra variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map R A) ∪ s), range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl end algebra section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- CRing ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := { commutes' := λ x y, commute.cast_int_left _ _, smul_def' := λ _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } variables {R} /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := S, range_le' := by { rintros _ ⟨i, rfl⟩, rw [ring_hom.eq_int_cast, ← gsmul_one], exact is_add_subgroup.gsmul_mem is_submonoid.one_mem } } @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : ↑(span ℤ s) = add_group.closure s := set.subset.antisymm (λ x hx, span_induction hx (λ _, add_group.mem_closure) is_add_submonoid.zero_mem (λ a b ha hb, is_add_submonoid.add_mem ha hb) (λ n a ha, by { exact is_add_subgroup.gsmul_mem ha })) (add_group.closure_subset subset_span) @[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] : (↑(span ℤ s) : set R) = s := by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup] end span_int end int section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S] variables (E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict_scalars' R S E`. We do not register this as an instance as `S` can not be inferred. -/ def module.restrict_scalars' : module R E := { smul := λ c x, (algebra_map R S c) • x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`. -/ @[nolint unused_arguments] def module.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] : inhabited (module.restrict_scalars R S E) := I instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] : add_comm_group (module.restrict_scalars R S E) := I instance : module R (module.restrict_scalars R S E) := (module.restrict_scalars' R S E : module R E) lemma module.restrict_scalars_smul_def (c : R) (x : module.restrict_scalars R S E) : c • x = ((algebra_map R S c) • x : E) := rfl /-- `module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`. Unfortunately these structures are not generally definitionally equal: the `R`-module structure on `S` is part of the data of `S`, while the `R`-module structure on `module.restrict_scalars R S S` comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`. The field `algebra.smul_def'` gives the equation we need here. -/ def algebra.restrict_scalars_equiv : (module.restrict_scalars R S S) ≃ₗ[R] S := { to_fun := λ s, s, inv_fun := λ s, s, left_inv := λ s, rfl, right_inv := λ s, rfl, add := λ x y, rfl, smul := λ c x, (algebra.smul_def' _ _).symm, } @[simp] lemma algebra.restrict_scalars_equiv_apply (s : S) : algebra.restrict_scalars_equiv R S s = s := rfl @[simp] lemma algebra.restrict_scalars_equiv_symm_apply (s : S) : (algebra.restrict_scalars_equiv R S).symm s = s := rfl variables {S E} open module /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ @[simps] def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) := { carrier := V.carrier, zero := V.zero, smul := λ c e h, V.smul _ h, add := λ x y hx hy, V.add hx hy, } @[simp] lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) : e ∈ V.restrict_scalars R ↔ e ∈ V := iff.refl _ @[simp] lemma submodule.restrict_scalars_bot : submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ := rfl @[simp] lemma submodule.restrict_scalars_top : submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ := rfl /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E →ₗ[S] F) : (restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) := { to_fun := f.to_fun, add := λx y, f.map_add x y, smul := λc x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) : (f.restrict_scalars R : E → F) = f := rfl @[simp] lemma restrict_scalars_ker (f : E →ₗ[S] F) : (f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker := rfl end restrict_scalars /-! When `V` and `W` are `S`-modules, for some `R`-algebra `S`, the collection of `S`-linear maps from `V` to `W` forms an `R`-module. (But not generally an `S`-module, because `S` may be non-commutative.) -/ section module_of_linear_maps variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S] (V : Type*) [add_comm_group V] [module S V] (W : Type*) [add_comm_group W] [module S W] /-- For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define `(r • f) v = f (r • v)`. -/ def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) := { smul := λ r f, { to_fun := λ v, f ((algebra_map R S r) • v), add := λ x y, by simp [smul_add], smul := λ s v, by simp [smul_smul, algebra.commutes], } } local attribute [instance] linear_map_algebra_has_scalar /-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/ def linear_map_algebra_module : module R (V →ₗ[S] W) := { one_smul := λ f, begin ext v, dsimp [(•)], simp, end, mul_smul := λ r r' f, begin ext v, dsimp [(•)], rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul, smul_smul, algebra.commutes], end, smul_zero := λ r, by { ext v, dsimp [(•)], refl, }, smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], }, zero_smul := λ f, by { ext v, dsimp [(•)], simp, }, add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, } local attribute [instance] linear_map_algebra_module variables {R S V W} @[simp] lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) : (c • f) v = (c • (f v) : module.restrict_scalars R S W) := begin erw [linear_map.map_smul], refl, end end module_of_linear_maps
ef4b6f9afdd7a1f0811680fb85ed96c165ee397e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/probability/martingale/upcrossing.lean
a333845c99b71c2fb25cd795ed5ddf517ff0fd41
[ "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
41,412
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.process.hitting_time import probability.martingale.basic /-! # Doob's upcrossing estimate Given a discrete real-valued submartingale $(f_n)_{n \in \mathbb{N}}$, denoting $U_N(a, b)$ the number of times $f_n$ crossed from below $a$ to above $b$ before time $N$, Doob's upcrossing estimate (also known as Doob's inequality) states that $$(b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(f_N - a)^+].$$ Doob's upcrossing estimate is an important inequality and is central in proving the martingale convergence theorems. ## Main definitions * `measure_theory.upper_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing above `b` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.lower_crossing_time a b f N n`: is the stopping time corresponding to `f` crossing below `a` the `n`-th time before time `N` (if this does not occur then the value is taken to be `N`). * `measure_theory.upcrossing_strat a b f N`: is the predictable process which is 1 if `n` is between a consecutive pair of lower and upper crossing and is 0 otherwise. Intuitively one might think of the `upcrossing_strat` as the strategy of buying 1 share whenever the process crosses below `a` for the first time after selling and selling 1 share whenever the process crosses above `b` for the first time after buying. * `measure_theory.upcrossings_before a b f N`: is the number of times `f` crosses from below `a` to above `b` before time `N`. * `measure_theory.upcrossings a b f`: is the number of times `f` crosses from below `a` to above `b`. This takes value in `ℝ≥0∞` and so is allowed to be `∞`. ## Main results * `measure_theory.adapted.is_stopping_time_upper_crossing_time`: `upper_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.adapted.is_stopping_time_lower_crossing_time`: `lower_crossing_time` is a stopping time whenever the process it is associated to is adapted. * `measure_theory.submartingale.mul_integral_upcrossings_before_le_integral_pos_part`: Doob's upcrossing estimate. * `measure_theory.submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part`: the inequality obtained by taking the supremum on both sides of Doob's upcrossing estimate. ### References We mostly follow the proof from [Kallenberg, *Foundations of modern probability*][kallenberg2021] -/ open topological_space filter open_locale nnreal ennreal measure_theory probability_theory big_operators topological_space namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} /-! ## Proof outline In this section, we will denote $U_N(a, b)$ the number of upcrossings of $(f_n)$ from below $a$ to above $b$ before time $N$. To define $U_N(a, b)$, we will construct two stopping times corresponding to when $(f_n)$ crosses below $a$ and above $b$. Namely, we define $$ \sigma_n := \inf \{n \ge \tau_n \mid f_n \le a\} \wedge N; $$ $$ \tau_{n + 1} := \inf \{n \ge \sigma_n \mid f_n \ge b\} \wedge N. $$ These are `lower_crossing_time` and `upper_crossing_time` in our formalization which are defined using `measure_theory.hitting` allowing us to specify a starting and ending time. Then, we may simply define $U_N(a, b) := \sup \{n \mid \tau_n < N\}$. Fixing $a < b \in \mathbb{R}$, we will first prove the theorem in the special case that $0 \le f_0$ and $a \le f_N$. In particular, we will show $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[f_N]. $$ This is `measure_theory.integral_mul_upcrossings_before_le_integral` in our formalization. To prove this, we use the fact that given a non-negative, bounded, predictable process $(C_n)$ (i.e. $(C_{n + 1})$ is adapted), $(C \bullet f)_n := \sum_{k \le n} C_{k + 1}(f_{k + 1} - f_k)$ is a submartingale if $(f_n)$ is. Define $C_n := \sum_{k \le n} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)$. It is easy to see that $(1 - C_n)$ is non-negative, bounded and predictable, and hence, given a submartingale $(f_n)$, $(1 - C) \bullet f$ is also a submartingale. Thus, by the submartingale property, $0 \le \mathbb{E}[((1 - C) \bullet f)_0] \le \mathbb{E}[((1 - C) \bullet f)_N]$ implying $$ \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[(1 \bullet f)_N] = \mathbb{E}[f_N] - \mathbb{E}[f_0]. $$ Furthermore, \begin{align} (C \bullet f)_N & = \sum_{n \le N} \sum_{k \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} \sum_{n \le N} \mathbf{1}_{[\sigma_k, \tau_{k + 1})}(n)(f_{n + 1} - f_n)\\ & = \sum_{k \le N} (f_{\sigma_k + 1} - f_{\sigma_k} + f_{\sigma_k + 2} - f_{\sigma_k + 1} + \cdots + f_{\tau_{k + 1}} - f_{\tau_{k + 1} - 1})\\ & = \sum_{k \le N} (f_{\tau_{k + 1}} - f_{\sigma_k}) \ge \sum_{k < U_N(a, b)} (b - a) = (b - a) U_N(a, b) \end{align} where the inequality follows since for all $k < U_N(a, b)$, $f_{\tau_{k + 1}} - f_{\sigma_k} \ge b - a$ while for all $k > U_N(a, b)$, $f_{\tau_{k + 1}} = f_{\sigma_k} = f_N$ and $f_{\tau_{U_N(a, b) + 1}} - f_{\sigma_{U_N(a, b)}} = f_N - a \ge 0$. Hence, we have $$ (b - a) \mathbb{E}[U_N(a, b)] \le \mathbb{E}[(C \bullet f)_N] \le \mathbb{E}[f_N] - \mathbb{E}[f_0] \le \mathbb{E}[f_N], $$ as required. To obtain the general case, we simply apply the above to $((f_n - a)^+)_n$. -/ /-- `lower_crossing_time_aux a f c N` is the first time `f` reached below `a` after time `c` before time `N`. -/ noncomputable def lower_crossing_time_aux [preorder ι] [has_Inf ι] (a : ℝ) (f : ι → Ω → ℝ) (c N : ι) : Ω → ι := hitting f (set.Iic a) c N /-- `upper_crossing_time a b f N n` is the first time before time `N`, `f` reaches above `b` after `f` reached below `a` for the `n - 1`-th time. -/ noncomputable def upper_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) : ℕ → Ω → ι | 0 := ⊥ | (n + 1) := λ ω, hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time n ω) N ω) N ω /-- `lower_crossing_time a b f N n` is the first time before time `N`, `f` reaches below `a` after `f` reached above `b` for the `n`-th time. -/ noncomputable def lower_crossing_time [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (n : ℕ) : Ω → ι := λ ω, hitting f (set.Iic a) (upper_crossing_time a b f N n ω) N ω section variables [preorder ι] [order_bot ι] [has_Inf ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} @[simp] lemma upper_crossing_time_zero : upper_crossing_time a b f N 0 = ⊥ := rfl @[simp] lemma lower_crossing_time_zero : lower_crossing_time a b f N 0 = hitting f (set.Iic a) ⊥ N := rfl lemma upper_crossing_time_succ : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time_aux a f (upper_crossing_time a b f N n ω) N ω) N ω := by rw upper_crossing_time lemma upper_crossing_time_succ_eq (ω : Ω) : upper_crossing_time a b f N (n + 1) ω = hitting f (set.Ici b) (lower_crossing_time a b f N n ω) N ω := begin simp only [upper_crossing_time_succ], refl, end end section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot ι] variables {a b : ℝ} {f : ι → Ω → ℝ} {N : ι} {n m : ℕ} {ω : Ω} lemma upper_crossing_time_le : upper_crossing_time a b f N n ω ≤ N := begin cases n, { simp only [upper_crossing_time_zero, pi.bot_apply, bot_le] }, { simp only [upper_crossing_time_succ, hitting_le] }, end @[simp] lemma upper_crossing_time_zero' : upper_crossing_time a b f ⊥ n ω = ⊥ := eq_bot_iff.2 upper_crossing_time_le lemma lower_crossing_time_le : lower_crossing_time a b f N n ω ≤ N := by simp only [lower_crossing_time, hitting_le ω] lemma upper_crossing_time_le_lower_crossing_time : upper_crossing_time a b f N n ω ≤ lower_crossing_time a b f N n ω := by simp only [lower_crossing_time, le_hitting upper_crossing_time_le ω] lemma lower_crossing_time_le_upper_crossing_time_succ : lower_crossing_time a b f N n ω ≤ upper_crossing_time a b f N (n + 1) ω := begin rw upper_crossing_time_succ, exact le_hitting lower_crossing_time_le ω, end lemma lower_crossing_time_mono (hnm : n ≤ m) : lower_crossing_time a b f N n ω ≤ lower_crossing_time a b f N m ω := begin suffices : monotone (λ n, lower_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans lower_crossing_time_le_upper_crossing_time_succ upper_crossing_time_le_lower_crossing_time) end lemma upper_crossing_time_mono (hnm : n ≤ m) : upper_crossing_time a b f N n ω ≤ upper_crossing_time a b f N m ω := begin suffices : monotone (λ n, upper_crossing_time a b f N n ω), { exact this hnm }, exact monotone_nat_of_le_succ (λ n, le_trans upper_crossing_time_le_lower_crossing_time lower_crossing_time_le_upper_crossing_time_succ), end end conditionally_complete_linear_order_bot variables {a b : ℝ} {f : ℕ → Ω → ℝ} {N : ℕ} {n m : ℕ} {ω : Ω} lemma stopped_value_lower_crossing_time (h : lower_crossing_time a b f N n ω ≠ N) : stopped_value f (lower_crossing_time a b f N n) ω ≤ a := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne lower_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 lower_crossing_time_le⟩, hj₂⟩, end lemma stopped_value_upper_crossing_time (h : upper_crossing_time a b f N (n + 1) ω ≠ N) : b ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω := begin obtain ⟨j, hj₁, hj₂⟩ := (hitting_le_iff_of_lt _ (lt_of_le_of_ne upper_crossing_time_le h)).1 le_rfl, exact stopped_value_hitting_mem ⟨j, ⟨hj₁.1, le_trans hj₁.2 (hitting_le _)⟩, hj₂⟩, end lemma upper_crossing_time_lt_lower_crossing_time (hab : a < b) (hn : lower_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N (n + 1) ω < lower_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne upper_crossing_time_le_lower_crossing_time (λ h, not_le.2 hab $ le_trans _ (stopped_value_lower_crossing_time hn)), simp only [stopped_value], rw ← h, exact stopped_value_upper_crossing_time (h.symm ▸ hn), end lemma lower_crossing_time_lt_upper_crossing_time (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : lower_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := begin refine lt_of_le_of_ne lower_crossing_time_le_upper_crossing_time_succ (λ h, not_le.2 hab $ le_trans (stopped_value_upper_crossing_time hn) _), simp only [stopped_value], rw ← h, exact stopped_value_lower_crossing_time (h.symm ▸ hn), end lemma upper_crossing_time_lt_succ (hab : a < b) (hn : upper_crossing_time a b f N (n + 1) ω ≠ N) : upper_crossing_time a b f N n ω < upper_crossing_time a b f N (n + 1) ω := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time (lower_crossing_time_lt_upper_crossing_time hab hn) lemma lower_crossing_time_stabilize (hnm : n ≤ m) (hn : lower_crossing_time a b f N n ω = N) : lower_crossing_time a b f N m ω = N := le_antisymm lower_crossing_time_le (le_trans (le_of_eq hn.symm) (lower_crossing_time_mono hnm)) lemma upper_crossing_time_stabilize (hnm : n ≤ m) (hn : upper_crossing_time a b f N n ω = N) : upper_crossing_time a b f N m ω = N := le_antisymm upper_crossing_time_le (le_trans (le_of_eq hn.symm) (upper_crossing_time_mono hnm)) lemma lower_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ lower_crossing_time a b f N n ω) : lower_crossing_time a b f N m ω = N := lower_crossing_time_stabilize hnm (le_antisymm lower_crossing_time_le hn) lemma upper_crossing_time_stabilize' (hnm : n ≤ m) (hn : N ≤ upper_crossing_time a b f N n ω) : upper_crossing_time a b f N m ω = N := upper_crossing_time_stabilize hnm (le_antisymm upper_crossing_time_le hn) -- `upper_crossing_time_bound_eq` provides an explicit bound lemma exists_upper_crossing_time_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : ∃ n, upper_crossing_time a b f N n ω = N := begin by_contra h, push_neg at h, have : strict_mono (λ n, upper_crossing_time a b f N n ω) := strict_mono_nat_of_lt_succ (λ n, upper_crossing_time_lt_succ hab (h _)), obtain ⟨_, ⟨k, rfl⟩, hk⟩ : ∃ m (hm : m ∈ set.range (λ n, upper_crossing_time a b f N n ω)), N < m := ⟨upper_crossing_time a b f N (N + 1) ω, ⟨N + 1, rfl⟩, lt_of_lt_of_le (N.lt_succ_self) (strict_mono.id_le this (N + 1))⟩, exact not_le.2 hk upper_crossing_time_le end lemma upper_crossing_time_lt_bdd_above (hab : a < b) : bdd_above {n | upper_crossing_time a b f N n ω < N} := begin obtain ⟨k, hk⟩ := exists_upper_crossing_time_eq f N ω hab, refine ⟨k, λ n (hn : upper_crossing_time a b f N n ω < N), _⟩, by_contra hn', exact hn.ne (upper_crossing_time_stabilize (not_le.1 hn').le hk) end lemma upper_crossing_time_lt_nonempty (hN : 0 < N) : {n | upper_crossing_time a b f N n ω < N}.nonempty := ⟨0, hN⟩ lemma upper_crossing_time_bound_eq (f : ℕ → Ω → ℝ) (N : ℕ) (ω : Ω) (hab : a < b) : upper_crossing_time a b f N N ω = N := begin by_cases hN' : N < nat.find (exists_upper_crossing_time_eq f N ω hab), { refine le_antisymm upper_crossing_time_le _, have hmono : strict_mono_on (λ n, upper_crossing_time a b f N n ω) (set.Iic (nat.find (exists_upper_crossing_time_eq f N ω hab)).pred), { refine strict_mono_on_Iic_of_lt_succ (λ m hm, upper_crossing_time_lt_succ hab _), rw nat.lt_pred_iff at hm, convert nat.find_min _ hm }, convert strict_mono_on.Iic_id_le hmono N (nat.le_pred_of_lt hN') }, { rw not_lt at hN', exact upper_crossing_time_stabilize hN' (nat.find_spec (exists_upper_crossing_time_eq f N ω hab)) } end lemma upper_crossing_time_eq_of_bound_le (hab : a < b) (hn : N ≤ n) : upper_crossing_time a b f N n ω = N := le_antisymm upper_crossing_time_le ((le_trans (upper_crossing_time_bound_eq f N ω hab).symm.le (upper_crossing_time_mono hn))) variables {ℱ : filtration ℕ m0} lemma adapted.is_stopping_time_crossing (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) ∧ is_stopping_time ℱ (lower_crossing_time a b f N n) := begin induction n with k ih, { refine ⟨is_stopping_time_const _ 0, _⟩, simp [hitting_is_stopping_time hf measurable_set_Iic] }, { obtain ⟨ih₁, ih₂⟩ := ih, have : is_stopping_time ℱ (upper_crossing_time a b f N (k + 1)), { intro n, simp_rw upper_crossing_time_succ_eq, exact is_stopping_time_hitting_is_stopping_time ih₂ (λ _, lower_crossing_time_le) measurable_set_Ici hf _ }, refine ⟨this, _⟩, { intro n, exact is_stopping_time_hitting_is_stopping_time this (λ _, upper_crossing_time_le) measurable_set_Iic hf _ } } end lemma adapted.is_stopping_time_upper_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (upper_crossing_time a b f N n) := hf.is_stopping_time_crossing.1 lemma adapted.is_stopping_time_lower_crossing_time (hf : adapted ℱ f) : is_stopping_time ℱ (lower_crossing_time a b f N n) := hf.is_stopping_time_crossing.2 /-- `upcrossing_strat a b f N n` is 1 if `n` is between a consecutive pair of lower and upper crossings and is 0 otherwise. `upcrossing_strat` is shifted by one index so that it is adapted rather than predictable. -/ noncomputable def upcrossing_strat (a b : ℝ) (f : ℕ → Ω → ℝ) (N n : ℕ) (ω : Ω) : ℝ := ∑ k in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator 1 n lemma upcrossing_strat_nonneg : 0 ≤ upcrossing_strat a b f N n ω := finset.sum_nonneg (λ i hi, set.indicator_nonneg (λ ω hω, zero_le_one) _) lemma upcrossing_strat_le_one : upcrossing_strat a b f N n ω ≤ 1 := begin rw [upcrossing_strat, ← set.indicator_finset_bUnion_apply], { exact set.indicator_le_self' (λ _ _, zero_le_one) _ }, { intros i hi j hj hij, rw set.Ico_disjoint_Ico, obtain (hij' | hij') := lt_or_gt_of_ne hij, { rw [min_eq_left ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_right (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) }, { rw gt_iff_lt at hij', rw [min_eq_right ((upper_crossing_time_mono (nat.succ_le_succ hij'.le)) : upper_crossing_time a b f N _ ω ≤ upper_crossing_time a b f N _ ω), max_eq_left (lower_crossing_time_mono hij'.le : lower_crossing_time a b f N _ _ ≤ lower_crossing_time _ _ _ _ _ _)], refine le_trans upper_crossing_time_le_lower_crossing_time (lower_crossing_time_mono (nat.succ_le_of_lt hij')) } } end lemma adapted.upcrossing_strat_adapted (hf : adapted ℱ f) : adapted ℱ (upcrossing_strat a b f N) := begin intro n, change strongly_measurable[ℱ n] (λ ω, ∑ k in finset.range N, ({n | lower_crossing_time a b f N k ω ≤ n} ∩ {n | n < upper_crossing_time a b f N (k + 1) ω}).indicator 1 n), refine finset.strongly_measurable_sum _ (λ i hi, strongly_measurable_const.indicator ((hf.is_stopping_time_lower_crossing_time n).inter _)), simp_rw ← not_le, exact (hf.is_stopping_time_upper_crossing_time n).compl, end lemma submartingale.sum_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)) ℱ μ := hf.sum_mul_sub hf.adapted.upcrossing_strat_adapted (λ _ _, upcrossing_strat_le_one) (λ _ _, upcrossing_strat_nonneg) lemma submartingale.sum_sub_upcrossing_strat_mul [is_finite_measure μ] (hf : submartingale f ℱ μ) (a b : ℝ) (N : ℕ) : submartingale (λ n : ℕ, ∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)) ℱ μ := begin refine hf.sum_mul_sub (λ n, (adapted_const ℱ 1 n).sub (hf.adapted.upcrossing_strat_adapted n)) (_ : ∀ n ω, (1 - upcrossing_strat a b f N n) ω ≤ 1) _, { exact λ n ω, sub_le_self _ upcrossing_strat_nonneg }, { intros n ω, simp [upcrossing_strat_le_one] } end lemma submartingale.sum_mul_upcrossing_strat_le [is_finite_measure μ] (hf : submartingale f ℱ μ) : μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)] ≤ μ[f n] - μ[f 0] := begin have h₁ : (0 : ℝ) ≤ μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)], { have := (hf.sum_sub_upcrossing_strat_mul a b N).set_integral_le (zero_le n) measurable_set.univ, rw [integral_univ, integral_univ] at this, refine le_trans _ this, simp only [finset.range_zero, finset.sum_empty, integral_zero'] }, have h₂ : μ[∑ k in finset.range n, (1 - upcrossing_strat a b f N k) * (f (k + 1) - f k)] = μ[∑ k in finset.range n, (f (k + 1) - f k)] - μ[∑ k in finset.range n, upcrossing_strat a b f N k * (f (k + 1) - f k)], { simp only [sub_mul, one_mul, finset.sum_sub_distrib, pi.sub_apply, finset.sum_apply, pi.mul_apply], refine integral_sub (integrable.sub (integrable_finset_sum _ (λ i hi, hf.integrable _)) (integrable_finset_sum _ (λ i hi, hf.integrable _))) _, convert (hf.sum_upcrossing_strat_mul a b N).integrable n, ext, simp }, rw [h₂, sub_nonneg] at h₁, refine le_trans h₁ _, simp_rw [finset.sum_range_sub, integral_sub' (hf.integrable _) (hf.integrable _)], end /-- The number of upcrossings (strictly) before time `N`. -/ noncomputable def upcrossings_before [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (N : ι) (ω : Ω) : ℕ := Sup {n | upper_crossing_time a b f N n ω < N} @[simp] lemma upcrossings_before_bot [preorder ι] [order_bot ι] [has_Inf ι] {a b : ℝ} {f : ι → Ω → ℝ} {ω : Ω} : upcrossings_before a b f ⊥ ω = ⊥ := by simp [upcrossings_before] lemma upcrossings_before_zero : upcrossings_before a b f 0 ω = 0 := by simp [upcrossings_before] @[simp] lemma upcrossings_before_zero' : upcrossings_before a b f 0 = 0 := by { ext ω, exact upcrossings_before_zero } lemma upper_crossing_time_lt_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n ≤ upcrossings_before a b f N ω) : upper_crossing_time a b f N n ω < N := begin have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := (upper_crossing_time_lt_nonempty hN).cSup_mem ((order_bot.bdd_below _).finite_of_bdd_above (upper_crossing_time_lt_bdd_above hab)), exact lt_of_le_of_lt (upper_crossing_time_mono hn) this, end lemma upper_crossing_time_eq_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : upper_crossing_time a b f N n ω = N := begin refine le_antisymm upper_crossing_time_le (not_lt.1 _), convert not_mem_of_cSup_lt hn (upper_crossing_time_lt_bdd_above hab), end lemma upcrossings_before_le (f : ℕ → Ω → ℝ) (ω : Ω) (hab : a < b) : upcrossings_before a b f N ω ≤ N := begin by_cases hN : N = 0, { subst hN, rw upcrossings_before_zero }, { refine cSup_le ⟨0, zero_lt_iff.2 hN⟩ (λ n (hn : _ < _), _), by_contra hnN, exact hn.ne (upper_crossing_time_eq_of_bound_le hab (not_le.1 hnN).le) }, end lemma crossing_eq_crossing_of_lower_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : lower_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have h' : upper_crossing_time a b f N n ω < N := lt_of_le_of_lt upper_crossing_time_le_lower_crossing_time h, induction n with k ih, { simp only [nat.nat_zero_eq_zero, upper_crossing_time_zero, bot_eq_zero', eq_self_iff_true, lower_crossing_time_zero, true_and, eq_comm], refine hitting_eq_hitting_of_exists hNM _, simp only [lower_crossing_time, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, { specialize ih (lt_of_le_of_lt (lower_crossing_time_mono (nat.le_succ _)) h) (lt_of_le_of_lt (upper_crossing_time_mono (nat.le_succ _)) h'), have : upper_crossing_time a b f M k.succ ω = upper_crossing_time a b f N k.succ ω, { simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h' ⊢, obtain ⟨j, hj₁, hj₂⟩ := h', rw [eq_comm, ih.2], exact hitting_eq_hitting_of_exists hNM ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ }, refine ⟨this, _⟩, simp only [lower_crossing_time, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, rw [lower_crossing_time, hitting_lt_iff _ le_rfl] at h, swap, { apply_instance }, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ } end lemma crossing_eq_crossing_of_upper_crossing_time_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N (n + 1) ω < N) : upper_crossing_time a b f M (n + 1) ω = upper_crossing_time a b f N (n + 1) ω ∧ lower_crossing_time a b f M n ω = lower_crossing_time a b f N n ω := begin have := (crossing_eq_crossing_of_lower_crossing_time_lt hNM (lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ h)).2, refine ⟨_, this⟩, rw [upper_crossing_time_succ_eq, upper_crossing_time_succ_eq, eq_comm, this], refine hitting_eq_hitting_of_exists hNM _, simp only [upper_crossing_time_succ_eq, hitting_lt_iff] at h, obtain ⟨j, hj₁, hj₂⟩ := h, exact ⟨j, ⟨hj₁.1, hj₁.2.le⟩, hj₂⟩ end lemma upper_crossing_time_eq_upper_crossing_time_of_lt {M : ℕ} (hNM : N ≤ M) (h : upper_crossing_time a b f N n ω < N) : upper_crossing_time a b f M n ω = upper_crossing_time a b f N n ω := begin cases n, { simp }, { exact (crossing_eq_crossing_of_upper_crossing_time_lt hNM h).1 } end lemma upcrossings_before_mono (hab : a < b) : monotone (λ N ω, upcrossings_before a b f N ω) := begin intros N M hNM ω, simp only [upcrossings_before], by_cases hemp : {n : ℕ | upper_crossing_time a b f N n ω < N}.nonempty, { refine cSup_le_cSup (upper_crossing_time_lt_bdd_above hab) hemp (λ n hn, _), rw [set.mem_set_of_eq, upper_crossing_time_eq_upper_crossing_time_of_lt hNM hn], exact lt_of_lt_of_le hn hNM }, { rw set.not_nonempty_iff_eq_empty at hemp, simp [hemp, cSup_empty, bot_eq_zero', zero_le'] } end lemma upcrossings_before_lt_of_exists_upcrossing (hab : a < b) {N₁ N₂ : ℕ} (hN₁: N ≤ N₁) (hN₁': f N₁ ω < a) (hN₂: N₁ ≤ N₂) (hN₂': b < f N₂ ω) : upcrossings_before a b f N ω < upcrossings_before a b f (N₂ + 1) ω := begin refine lt_of_lt_of_le (nat.lt_succ_self _) (le_cSup (upper_crossing_time_lt_bdd_above hab) _), rw [set.mem_set_of_eq, upper_crossing_time_succ_eq, hitting_lt_iff _ le_rfl], swap, { apply_instance }, { refine ⟨N₂, ⟨_, nat.lt_succ_self _⟩, hN₂'.le⟩, rw [lower_crossing_time, hitting_le_iff_of_lt _ (nat.lt_succ_self _)], refine ⟨N₁, ⟨le_trans _ hN₁, hN₂⟩, hN₁'.le⟩, by_cases hN : 0 < N, { have : upper_crossing_time a b f N (upcrossings_before a b f N ω) ω < N := nat.Sup_mem (upper_crossing_time_lt_nonempty hN) (upper_crossing_time_lt_bdd_above hab), rw upper_crossing_time_eq_upper_crossing_time_of_lt (hN₁.trans (hN₂.trans $ nat.le_succ _)) this, exact this.le }, { rw [not_lt, le_zero_iff] at hN, rw [hN, upcrossings_before_zero, upper_crossing_time_zero], refl } }, end lemma lower_crossing_time_lt_of_lt_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : lower_crossing_time a b f N n ω < N := lt_of_le_of_lt lower_crossing_time_le_upper_crossing_time_succ (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn) lemma le_sub_of_le_upcrossings_before (hN : 0 < N) (hab : a < b) (hn : n < upcrossings_before a b f N ω) : b - a ≤ stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω := sub_le_sub (stopped_value_upper_crossing_time (upper_crossing_time_lt_of_le_upcrossings_before hN hab hn).ne) (stopped_value_lower_crossing_time (lower_crossing_time_lt_of_lt_upcrossings_before hN hab hn).ne) lemma sub_eq_zero_of_upcrossings_before_lt (hab : a < b) (hn : upcrossings_before a b f N ω < n) : stopped_value f (upper_crossing_time a b f N (n + 1)) ω - stopped_value f (lower_crossing_time a b f N n) ω = 0 := begin have : N ≤ upper_crossing_time a b f N n ω, { rw upcrossings_before at hn, rw ← not_lt, exact λ h, not_le.2 hn (le_cSup (upper_crossing_time_lt_bdd_above hab) h) }, simp [stopped_value, upper_crossing_time_stabilize' (nat.le_succ n) this, lower_crossing_time_stabilize' le_rfl (le_trans this upper_crossing_time_le_lower_crossing_time)] end lemma mul_upcrossings_before_le (hf : a ≤ f N ω) (hab : a < b) : (b - a) * upcrossings_before a b f N ω ≤ ∑ k in finset.range N, upcrossing_strat a b f N k ω * (f (k + 1) - f k) ω := begin classical, by_cases hN : N = 0, { simp [hN] }, simp_rw [upcrossing_strat, finset.sum_mul, ← set.indicator_mul_left, pi.one_apply, pi.sub_apply, one_mul], rw finset.sum_comm, have h₁ : ∀ k, ∑ n in finset.range N, (set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)).indicator (λ m, f (m + 1) ω - f m ω) n = stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω, { intro k, rw [finset.sum_indicator_eq_sum_filter, (_ : (finset.filter (λ i, i ∈ set.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)) (finset.range N)) = finset.Ico (lower_crossing_time a b f N k ω) (upper_crossing_time a b f N (k + 1) ω)), finset.sum_Ico_eq_add_neg _ lower_crossing_time_le_upper_crossing_time_succ, finset.sum_range_sub (λ n, f n ω), finset.sum_range_sub (λ n, f n ω), neg_sub, sub_add_sub_cancel], { refl }, { ext i, simp only [set.mem_Ico, finset.mem_filter, finset.mem_range, finset.mem_Ico, and_iff_right_iff_imp, and_imp], exact λ _ h, lt_of_lt_of_le h upper_crossing_time_le } }, simp_rw [h₁], have h₂ : ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω), { calc ∑ k in finset.range (upcrossings_before a b f N ω), (b - a) ≤ ∑ k in finset.range (upcrossings_before a b f N ω), (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum (λ i hi, le_sub_of_le_upcrossings_before (zero_lt_iff.2 hN) hab _), rwa finset.mem_range at hi, end ...≤ ∑ k in finset.range N, (stopped_value f (upper_crossing_time a b f N (k + 1)) ω - stopped_value f (lower_crossing_time a b f N k) ω) : begin refine finset.sum_le_sum_of_subset_of_nonneg (finset.range_subset.2 (upcrossings_before_le f ω hab)) (λ i _ hi, _), by_cases hi' : i = upcrossings_before a b f N ω, { subst hi', simp only [stopped_value], rw upper_crossing_time_eq_of_upcrossings_before_lt hab (nat.lt_succ_self _), by_cases heq : lower_crossing_time a b f N (upcrossings_before a b f N ω) ω = N, { rw [heq, sub_self] }, { rw sub_nonneg, exact le_trans (stopped_value_lower_crossing_time heq) hf } }, { rw sub_eq_zero_of_upcrossings_before_lt hab, rw [finset.mem_range, not_lt] at hi, exact lt_of_le_of_ne hi (ne.symm hi') }, end }, refine le_trans _ h₂, rw [finset.sum_const, finset.card_range, nsmul_eq_mul, mul_comm], end lemma integral_mul_upcrossings_before_le_integral [is_finite_measure μ] (hf : submartingale f ℱ μ) (hfN : ∀ ω, a ≤ f N ω) (hfzero : 0 ≤ f 0) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[f N] := calc (b - a) * μ[upcrossings_before a b f N] ≤ μ[∑ k in finset.range N, upcrossing_strat a b f N k * (f (k + 1) - f k)] : begin rw ← integral_mul_left, refine integral_mono_of_nonneg _ ((hf.sum_upcrossing_strat_mul a b N).integrable N) _, { exact eventually_of_forall (λ ω, mul_nonneg (sub_nonneg.2 hab.le) (nat.cast_nonneg _)) }, { refine eventually_of_forall (λ ω, _), simpa using mul_upcrossings_before_le (hfN ω) hab }, end ...≤ μ[f N] - μ[f 0] : hf.sum_mul_upcrossing_strat_le ...≤ μ[f N] : (sub_le_self_iff _).2 (integral_nonneg hfzero) lemma crossing_pos_eq (hab : a < b) : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = upper_crossing_time a b f N n ∧ lower_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N n = lower_crossing_time a b f N n := begin have hab' : 0 < b - a := sub_pos.2 hab, have hf : ∀ ω i, b - a ≤ (f i ω - a)⁺ ↔ b ≤ f i ω, { intros i ω, refine ⟨λ h, _, λ h, _⟩, { rwa [← sub_le_sub_iff_right a, ← lattice_ordered_comm_group.pos_eq_self_of_pos_pos (lt_of_lt_of_le hab' h)] }, { rw ← sub_le_sub_iff_right a at h, rwa lattice_ordered_comm_group.pos_of_nonneg _ (le_trans hab'.le h) } }, have hf' : ∀ ω i, (f i ω - a)⁺ ≤ 0 ↔ f i ω ≤ a, { intros ω i, rw [lattice_ordered_comm_group.pos_nonpos_iff, sub_nonpos] }, induction n with k ih, { refine ⟨rfl, _⟩, simp only [lower_crossing_time_zero, hitting, set.mem_Icc, set.mem_Iic], ext ω, split_ifs with h₁ h₂ h₂, { simp_rw [hf'] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, { have : upper_crossing_time 0 (b - a) (λ n ω, (f n ω - a)⁺) N (k + 1) = upper_crossing_time a b f N (k + 1), { ext ω, simp only [upper_crossing_time_succ_eq, ← ih.2, hitting, set.mem_Ici, tsub_le_iff_right], split_ifs with h₁ h₂ h₂, { simp_rw [← sub_le_iff_le_add, hf ω] }, { simp_rw [set.mem_Ici, ← hf _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Ici, hf _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } }, refine ⟨this, _⟩, ext ω, simp only [lower_crossing_time, this, hitting, set.mem_Iic], split_ifs with h₁ h₂ h₂, { simp_rw [hf' ω] }, { simp_rw [set.mem_Iic, ← hf' _ _] at h₂, exact false.elim (h₂ h₁) }, { simp_rw [set.mem_Iic, hf' _ _] at h₁, exact false.elim (h₁ h₂) }, { refl } } end lemma upcrossings_before_pos_eq (hab : a < b) : upcrossings_before 0 (b - a) (λ n ω, (f n ω - a)⁺) N ω = upcrossings_before a b f N ω := by simp_rw [upcrossings_before, (crossing_pos_eq hab).1] lemma mul_integral_upcrossings_before_le_integral_pos_part_aux [is_finite_measure μ] (hf : submartingale f ℱ μ) (hab : a < b) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin refine le_trans (le_of_eq _) (integral_mul_upcrossings_before_le_integral (hf.sub_martingale (martingale_const _ _ _)).pos (λ ω, lattice_ordered_comm_group.pos_nonneg _) (λ ω, lattice_ordered_comm_group.pos_nonneg _) (sub_pos.2 hab)), simp_rw [sub_zero, ← upcrossings_before_pos_eq hab], refl, end /-- **Doob's upcrossing estimate**: given a real valued discrete submartingale `f` and real values `a` and `b`, we have `(b - a) * 𝔼[upcrossings_before a b f N] ≤ 𝔼[(f N - a)⁺]` where `upcrossings_before a b f N` is the number of times the process `f` crossed from below `a` to above `b` before the time `N`. -/ theorem submartingale.mul_integral_upcrossings_before_le_integral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) (N : ℕ) : (b - a) * μ[upcrossings_before a b f N] ≤ μ[λ ω, (f N ω - a)⁺] := begin by_cases hab : a < b, { exact mul_integral_upcrossings_before_le_integral_pos_part_aux hf hab }, { rw [not_lt, ← sub_nonpos] at hab, exact le_trans (mul_nonpos_of_nonpos_of_nonneg hab (integral_nonneg (λ ω, nat.cast_nonneg _))) (integral_nonneg (λ ω, lattice_ordered_comm_group.pos_nonneg _)) } end /-! ### Variant of the upcrossing estimate Now, we would like to prove a variant of the upcrossing estimate obtained by taking the supremum over $N$ of the original upcrossing estimate. Namely, we want the inequality $$ (b - a) \sup_N \mathbb{E}[U_N(a, b)] \le \sup_N \mathbb{E}[f_N]. $$ This inequality is central for the martingale convergence theorem as it provides a uniform bound for the upcrossings. We note that on top of taking the supremum on both sides of the inequality, we had also used the monotone convergence theorem on the left hand side to take the supremum outside of the integral. To do this, we need to make sure $U_N(a, b)$ is measurable and integrable. Integrability is easy to check as $U_N(a, b) ≤ N$ and so it suffices to show measurability. Indeed, by noting that $$ U_N(a, b) = \sum_{i = 1}^N \mathbf{1}_{\{U_N(a, b) < N\}} $$ $U_N(a, b)$ is measurable as $\{U_N(a, b) < N\}$ is a measurable set since $U_N(a, b)$ is a stopping time. -/ lemma upcrossings_before_eq_sum (hab : a < b) : upcrossings_before a b f N ω = ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i := begin by_cases hN : N = 0, { simp [hN] }, rw ← finset.sum_Ico_consecutive _ (nat.succ_le_succ zero_le') (nat.succ_le_succ (upcrossings_before_le f ω hab)), have h₁ : ∀ k ∈ finset.Ico 1 (upcrossings_before a b f N ω + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 1, { rintro k hk, rw finset.mem_Ico at hk, rw set.indicator_of_mem, { refl }, { exact upper_crossing_time_lt_of_le_upcrossings_before (zero_lt_iff.2 hN) hab (nat.lt_succ_iff.1 hk.2) } }, have h₂ : ∀ k ∈ finset.Ico (upcrossings_before a b f N ω + 1) (N + 1), {n : ℕ | upper_crossing_time a b f N n ω < N}.indicator 1 k = 0, { rintro k hk, rw [finset.mem_Ico, nat.succ_le_iff] at hk, rw set.indicator_of_not_mem, simp only [set.mem_set_of_eq, not_lt], exact (upper_crossing_time_eq_of_upcrossings_before_lt hab hk.1).symm.le }, rw [finset.sum_congr rfl h₁, finset.sum_congr rfl h₂, finset.sum_const, finset.sum_const, smul_eq_mul, mul_one, smul_eq_mul, mul_zero, nat.card_Ico, nat.add_succ_sub_one, add_zero, add_zero], end lemma adapted.measurable_upcrossings_before (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings_before a b f N) := begin have : upcrossings_before a b f N = λ ω, ∑ i in finset.Ico 1 (N + 1), {n | upper_crossing_time a b f N n ω < N}.indicator 1 i, { ext ω, exact upcrossings_before_eq_sum hab }, rw this, exact finset.measurable_sum _ (λ i hi, measurable.indicator measurable_const $ ℱ.le N _ (hf.is_stopping_time_upper_crossing_time.measurable_set_lt_of_pred N)) end lemma adapted.integrable_upcrossings_before [is_finite_measure μ] (hf : adapted ℱ f) (hab : a < b) : integrable (λ ω, (upcrossings_before a b f N ω : ℝ)) μ := begin have : ∀ᵐ ω ∂μ, ‖(upcrossings_before a b f N ω : ℝ)‖ ≤ N, { refine eventually_of_forall (λ ω, _), rw [real.norm_eq_abs, nat.abs_cast, nat.cast_le], refine upcrossings_before_le _ _ hab }, exact ⟨measurable.ae_strongly_measurable (measurable_from_top.comp (hf.measurable_upcrossings_before hab)), has_finite_integral_of_bounded this⟩ end /-- The number of upcrossings of a realization of a stochastic process (`upcrossing` takes value in `ℝ≥0∞` and so is allowed to be `∞`). -/ noncomputable def upcrossings [preorder ι] [order_bot ι] [has_Inf ι] (a b : ℝ) (f : ι → Ω → ℝ) (ω : Ω) : ℝ≥0∞ := ⨆ N, (upcrossings_before a b f N ω : ℝ≥0∞) lemma adapted.measurable_upcrossings (hf : adapted ℱ f) (hab : a < b) : measurable (upcrossings a b f) := measurable_supr (λ N, measurable_from_top.comp (hf.measurable_upcrossings_before hab)) lemma upcrossings_lt_top_iff : upcrossings a b f ω < ∞ ↔ ∃ k, ∀ N, upcrossings_before a b f N ω ≤ k := begin have : upcrossings a b f ω < ∞ ↔ ∃ k : ℝ≥0, upcrossings a b f ω ≤ k, { split, { intro h, lift upcrossings a b f ω to ℝ≥0 using h.ne with r hr, exact ⟨r, le_rfl⟩ }, { rintro ⟨k, hk⟩, exact lt_of_le_of_lt hk ennreal.coe_lt_top } }, simp_rw [this, upcrossings, supr_le_iff], split; rintro ⟨k, hk⟩, { obtain ⟨m, hm⟩ := exists_nat_ge k, refine ⟨m, λ N, ennreal.coe_nat_le_coe_nat.1 ((hk N).trans _)⟩, rwa [← ennreal.coe_nat, ennreal.coe_le_coe] }, { refine ⟨k, λ N, _⟩, simp only [ennreal.coe_nat, ennreal.coe_nat_le_coe_nat, hk N] } end /-- A variant of Doob's upcrossing estimate obtained by taking the supremum on both sides. -/ lemma submartingale.mul_lintegral_upcrossings_le_lintegral_pos_part [is_finite_measure μ] (a b : ℝ) (hf : submartingale f ℱ μ) : ennreal.of_real (b - a) * ∫⁻ ω, upcrossings a b f ω ∂μ ≤ ⨆ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ := begin by_cases hab : a < b, { simp_rw [upcrossings], have : ∀ N, ∫⁻ ω, ennreal.of_real ((f N ω - a)⁺) ∂μ = ennreal.of_real (∫ ω, (f N ω - a)⁺ ∂μ), { intro N, rw of_real_integral_eq_lintegral_of_real, { exact (hf.sub_martingale (martingale_const _ _ _)).pos.integrable _ }, { exact eventually_of_forall (λ ω, lattice_ordered_comm_group.pos_nonneg _) } }, rw lintegral_supr', { simp_rw [this, ennreal.mul_supr, supr_le_iff], intro N, rw [(by simp : ∫⁻ ω, upcrossings_before a b f N ω ∂μ = ∫⁻ ω, ↑(upcrossings_before a b f N ω : ℝ≥0) ∂μ), lintegral_coe_eq_integral, ← ennreal.of_real_mul (sub_pos.2 hab).le], { simp_rw [nnreal.coe_nat_cast], exact (ennreal.of_real_le_of_real (hf.mul_integral_upcrossings_before_le_integral_pos_part a b N)).trans (le_supr _ N) }, { simp only [nnreal.coe_nat_cast, hf.adapted.integrable_upcrossings_before hab] } }, { exact λ n, measurable_from_top.comp_ae_measurable (hf.adapted.measurable_upcrossings_before hab).ae_measurable }, { refine eventually_of_forall (λ ω N M hNM, _), rw ennreal.coe_nat_le_coe_nat, exact upcrossings_before_mono hab hNM ω } }, { rw [not_lt, ← sub_nonpos] at hab, rw [ennreal.of_real_of_nonpos hab, zero_mul], exact zero_le _ } end end measure_theory
208e46c5c8d17d4159869df1e01cc3a01a24c7fb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/funext_tactic.lean
4ea093d02c2d59bb3853cc28ba793ce4e06872cb
[ "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
1,006
lean
example : (λ x y : nat, x + y) = (λ x y : nat, y + x) := begin funext, apply nat.add_comm x y end example : (λ x y : nat, x + y) = (λ x y : nat, y + x) := begin funext z w, apply nat.add_comm z w end example : (λ x y : nat, x + y) = (λ x y : nat, y + x) := begin funext z, funext w, apply nat.add_comm z w end example : (λ x y : nat, x + y) = (λ x y : nat, y + x) := begin funext _, funext _, apply nat.add_comm x y end example : (λ x y : nat, x + y) = (λ x y : nat, y + x) := begin funext _ _, apply nat.add_comm x y end example : (λ x y : nat, x + 0) = (λ x y : nat, 0 + x) := begin funext _ _, apply nat.add_comm x 0 end example : (λ x y : nat, x + 0) = (λ x y : nat, 0 + x) := begin funext z _, apply nat.add_comm z 0 end example : (λ x y : nat, x + 0) = (λ x y : nat, 0 + x) := begin funext _ z, apply nat.add_comm x 0 end example : (λ x y : nat, x + 0) = (λ x y : nat, 0 + x) := begin funext z, funext _, apply nat.add_comm z 0 end
74c440fbb306f3f1a67e0ffbf92dddf240fa757f
0e175f34f8dca5ea099671777e8d7446d7d74227
/library/init/algebra/order.lean
46c5007ca98513efe31fc3796b66b0366f63c823
[ "Apache-2.0" ]
permissive
utensil-contrib/lean
b31266738071c654d96dac8b35d9ccffc8172fda
a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8
refs/heads/master
1,670,045,564,075
1,597,397,599,000
1,597,397,599,000
287,528,503
0
0
Apache-2.0
1,597,408,338,000
1,597,408,337,000
null
UTF-8
Lean
false
false
9,248
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.logic init.classical init.meta.name init.algebra.classes /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} set_option auto_param.check_exists false /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class preorder (α : Type u) extends has_le α, has_lt α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b, a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) . order_laws_tac) /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class partial_order (α : Type u) extends preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`.-/ class linear_order (α : Type u) extends partial_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) @[refl] lemma le_refl [preorder α] : ∀ a : α, a ≤ a := preorder.le_refl @[trans] lemma le_trans [preorder α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := preorder.le_trans lemma lt_iff_le_not_le [preorder α] : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := preorder.lt_iff_le_not_le lemma lt_of_le_not_le [preorder α] : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a b hab hba := lt_iff_le_not_le.mpr ⟨hab, hba⟩ lemma le_not_le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a b hab := lt_iff_le_not_le.mp hab lemma le_antisymm [partial_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := partial_order.le_antisymm lemma le_of_eq [preorder α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a lemma le_antisymm_iff [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λe, ⟨le_of_eq e, le_of_eq e.symm⟩, λ⟨h1, h2⟩, le_antisymm h1 h2⟩ @[trans] lemma ge_trans [preorder α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_order.le_total lemma le_of_not_ge [linear_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [preorder α] : ∀ a : α, ¬ a < a | a haa := match le_not_le_of_lt haa with | ⟨h1, h2⟩ := false.rec _ (h2 h1) end lemma gt_irrefl [preorder α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [preorder α] : ∀ {a b c : α}, a < b → b < c → a < c | a b c hab hbc := match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ := lt_of_le_not_le (le_trans hab hbc) (λ hca, hcb (le_trans hca hab)) end def lt.trans := @lt_trans @[trans] lemma gt_trans [preorder α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [preorder α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [preorder α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [preorder α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [linear_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b | a b hab := (le_not_le_of_lt hab).left @[trans] lemma lt_of_lt_of_le [preorder α] : ∀ {a b c : α}, a < b → b ≤ c → a < c | a b c hab hbc := let ⟨hab, hba⟩ := le_not_le_of_lt hab in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hba (le_trans hbc hca) @[trans] lemma lt_of_le_of_lt [preorder α] : ∀ {a b c : α}, a ≤ b → b < c → a < c | a b c hab hbc := let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hcb (le_trans hca hab) @[trans] lemma gt_of_gt_of_ge [preorder α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [preorder α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ lemma not_le_of_gt [preorder α] {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right lemma not_lt_of_ge [preorder α] {a b : α} (h : a ≥ b) : ¬ a < b := λ hab, not_le_of_gt hab h lemma lt_or_eq_of_le [partial_order α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b | a b hab := classical.by_cases (λ hba : b ≤ a, or.inr (le_antisymm hab hba)) (λ hba, or.inl (lt_of_le_not_le hab hba)) lemma le_of_lt_or_eq [preorder α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a b (or.inl hab) := le_of_lt hab | a b (or.inr hab) := hab ▸ le_refl _ lemma le_iff_lt_or_eq [partial_order α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b | a b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma lt_of_le_of_ne [partial_order α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ lemma lt_trichotomy [linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt [linear_order α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_order α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_order α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_order α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma le_of_eq_or_lt [preorder α] {a b : α} (h : a = b ∨ a < b) : a ≤ b := or.elim h le_of_eq le_of_lt lemma ne_iff_lt_or_gt [linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, or.elim o ne_of_lt ne_of_gt⟩ lemma lt_iff_not_ge [linear_order α] (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ instance decidable_lt_of_decidable_le [preorder α] [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((<) : α → α → Prop) | a b := if hab : a ≤ b then if hba : b ≤ a then is_false $ λ hab', not_le_of_gt hab' hba else is_true $ lt_of_le_not_le hab hba else is_false $ λ hab', hab (le_of_lt hab') instance decidable_eq_of_decidable_le [partial_order α] [decidable_rel ((≤) : α → α → Prop)] : decidable_eq α | a b := if hab : a ≤ b then if hba : b ≤ a then is_true (le_antisymm hab hba) else is_false (λ heq, hba (heq ▸ le_refl _)) else is_false (λ heq, hab (heq ▸ le_refl _)) class decidable_linear_order (α : Type u) extends linear_order α := (decidable_le : decidable_rel (≤)) (decidable_eq : decidable_eq α := @decidable_eq_of_decidable_le _ _ decidable_le) (decidable_lt : decidable_rel ((<) : α → α → Prop) := @decidable_lt_of_decidable_le _ _ decidable_le) instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁))) instance [decidable_linear_order α] : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_weak_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_total_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_total_order α (<) := { trichotomous := lt_trichotomy }
76136358952566dd8426243520fcf2aa1022667e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/special_functions/pow.lean
d74df6ab40ed2a3390401b25ba0173cc27a1c9a6
[ "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
48,295
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ` and `ℝ⁺` We construct the power functions `x ^ y` where `x` and `y` are complex numbers, or `x` and `y` are real numbers, or `x` is a nonnegative real and `y` is real, and prove their basic properties. -/ noncomputable theory open_locale classical real topological_space nnreal namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc exp (log x * y) * cos (y * π) ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num} }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), log_abs], calc -(exp (log x * y) * cos (y * π)) = exp (log x * y) * (-cos (y * π)) : by ring ... ≤ exp (log x * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log x * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma one_le_rpow (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_le_one {x z : ℝ} (hx : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by rw ←one_rpow z; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt end real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv /- Differentiability statements for the square root of a function, when the function does not vanish -/ lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x := begin simp only [sqrt_eq_rpow], convert hf.rpow (1/2) hx, rcases lt_trichotomy (f x) 0 with H|H|H, { have A : (f x)^((1:ℝ)/2) = 0, { rw rpow_def_of_neg H, have : cos (1/2 * π) = 0, by { convert cos_pi_div_two using 2, ring }, rw [this], simp }, have B : f x ^ ((1:ℝ) / 2 - 1) = 0, { rw rpow_def_of_neg H, have : cos (π/2 - π) = 0, by simp [cos_sub], have : cos (((1:ℝ)/2 - 1) * π) = 0, by { convert this using 2, ring }, rw this, simp }, rw [A, B], simp }, { exact (hx H).elim }, { have A : 0 < (f x)^((1:ℝ)/2) := rpow_pos_of_pos H _, have B : (f x) ^ (-(1:ℝ)) = (f x)^(-((1:ℝ)/2)) * (f x)^(-((1:ℝ)/2)), { rw [← rpow_add H], congr, norm_num }, rw [sub_eq_add_neg, rpow_add H, B, rpow_neg (le_of_lt H)], field_simp [hx, ne_of_gt A], ring } end lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x := begin rw ← has_deriv_within_at_univ at *, exact hf.sqrt hx end lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, sqrt (f x)) s x := (hf.has_deriv_within_at.sqrt hx).differentiable_within_at @[simp] lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, sqrt (f x)) x := (hf.has_deriv_at.sqrt hx).differentiable_at lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, sqrt (f x)) s := λx h, (hf x h).sqrt (hx x h) @[simp] lemma differentiable.sqrt (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, sqrt (f x)) := λx, (hf x).sqrt (hx x) lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) := (hf.has_deriv_within_at.sqrt hx).deriv_within hxs @[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) := (hf.has_deriv_at.sqrt hx).deriv end differentiability namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (zero_lt_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (zero_lt_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (tendsto.prod_mk_nhds hx hy) namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ennreal` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ennreal → ℝ → ennreal | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ennreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ennreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ennreal} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ennreal) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ennreal) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ennreal) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ennreal) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ennreal) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ennreal) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end @[simp] lemma rpow_one (x : ennreal) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ennreal) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ennreal} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ennreal} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_add {x : ennreal} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ennreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_neg_one (x : ennreal) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ennreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ennreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ennreal) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ennreal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ennreal} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma one_le_rpow {x : ennreal} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin cases x, { rcases le_iff_eq_or_lt.1 h₁ with H|H, { simp [← H, le_refl] }, { simp [top_rpow_of_pos H] } }, { simp only [one_le_coe_iff, some_eq_coe] at h, simp [coe_rpow_of_nonneg _ h₁, nnreal.one_le_rpow h h₁] } end lemma rpow_le_rpow {x y : ennreal} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ennreal} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_lt_rpow_of_exponent_lt {x : ennreal} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ennreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ennreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ennreal} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_one {x : ennreal} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp at hx2, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx2 hz] end lemma one_lt_rpow {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz], exact coe_lt_top }, { simp at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma rpow_lt_one {x : ennreal} {z : ℝ} (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := begin by_cases h : x = 0, { simp [h, zero_rpow_of_pos hz, ennreal.zero_lt_one] }, { lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at h hx1, have : 0 < x := bot_lt_iff_ne_bot.mpr h, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one this hx1 hz] } end lemma to_real_rpow (x : ennreal) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end end ennreal
1d04f79c0b2ac6dd62b05d0a69091fc2e5b98d49
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Array/BinSearch.lean
e322eaf76a8fef92def7b62ccf839171119fc3b7
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
2,954
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Array.Basic universe u v -- TODO: CLEANUP namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget -- TODO: remove `partial` using well-founded recursion @[specialize] partial def binSearchAux {α : Type u} {β : Type v} [Inhabited α] [Inhabited β] (lt : α → α → Bool) (found : Option α → β) (as : Array α) (k : α) : Nat → Nat → β | lo, hi => if lo <= hi then let m := (lo + hi)/2; let a := as.get! m; if lt a k then binSearchAux lt found as k (m+1) hi else if lt k a then if m == 0 then found none else binSearchAux lt found as k lo (m-1) else found (some a) else found none @[inline] def binSearch {α : Type} [Inhabited α] (as : Array α) (k : α) (lt : α → α → Bool) (lo := 0) (hi := as.size - 1) : Option α := if lo < as.size then let hi := if hi < as.size then hi else as.size - 1 binSearchAux lt id as k lo hi else none @[inline] def binSearchContains {α : Type} [Inhabited α] (as : Array α) (k : α) (lt : α → α → Bool) (lo := 0) (hi := as.size - 1) : Bool := if lo < as.size then let hi := if hi < as.size then hi else as.size - 1 binSearchAux lt Option.isSome as k lo hi else false @[specialize] private partial def binInsertAux {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] (lt : α → α → Bool) (merge : α → m α) (add : Unit → m α) (as : Array α) (k : α) : Nat → Nat → m (Array α) | lo, hi => -- as[lo] < k < as[hi] let mid := (lo + hi)/2; let midVal := as.get! mid; if lt midVal k then if mid == lo then do let v ← add (); pure <| as.insertAt (lo+1) v else binInsertAux lt merge add as k mid hi else if lt k midVal then binInsertAux lt merge add as k lo mid else do as.modifyM mid <| fun v => merge v @[specialize] partial def binInsertM {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] (lt : α → α → Bool) (merge : α → m α) (add : Unit → m α) (as : Array α) (k : α) : m (Array α) := if as.isEmpty then do let v ← add (); pure <| as.push v else if lt k (as.get! 0) then do let v ← add (); pure <| as.insertAt 0 v else if !lt (as.get! 0) k then as.modifyM 0 <| merge else if lt as.back k then do let v ← add (); pure <| as.push v else if !lt k as.back then as.modifyM (as.size - 1) <| merge else binInsertAux lt merge add as k 0 (as.size - 1) @[inline] def binInsert {α : Type u} [Inhabited α] (lt : α → α → Bool) (as : Array α) (k : α) : Array α := Id.run <| binInsertM lt (fun _ => k) (fun _ => k) as k end Array
ddc78f705be790b4bb75f0a38638df36ca2f17dd
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Module/simple.lean
4d2453c3be8a392c71d88379b271b2c4f4f016ec
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,740
lean
/- Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pierre-Alexandre Bazin, Scott Morrison -/ import category_theory.simple import algebra.category.Module.subobject import algebra.category.Module.algebra import ring_theory.simple_module import linear_algebra.finite_dimensional /-! # Simple objects in the category of `R`-modules We prove simple modules are exactly simple objects in the category of `R`-modules. -/ variables {R M : Type*} [ring R] [add_comm_group M] [module R M] open category_theory Module lemma simple_iff_is_simple_module : simple (of R M) ↔ is_simple_module R M := (simple_iff_subobject_is_simple_order _).trans (subobject_Module (of R M)).is_simple_order_iff lemma simple_iff_is_simple_module' (M : Module R) : simple M ↔ is_simple_module R M := (simple.iff_of_iso (of_self_iso M).symm).trans simple_iff_is_simple_module /-- A simple module is a simple object in the category of modules. -/ instance simple_of_is_simple_module [is_simple_module R M] : simple (of R M) := simple_iff_is_simple_module.mpr ‹_› /-- A simple object in the category of modules is a simple module. -/ instance is_simple_module_of_simple (M : Module R) [simple M] : is_simple_module R M := simple_iff_is_simple_module.mp (simple.of_iso (of_self_iso M)) open finite_dimensional local attribute [instance] module_of_algebra_Module is_scalar_tower_of_algebra_Module /-- Any `k`-algebra module which is 1-dimensional over `k` is simple. -/ lemma simple_of_finrank_eq_one {k : Type*} [field k] [algebra k R] {V : Module R} (h : finrank k V = 1) : simple V := (simple_iff_is_simple_module' V).mpr (is_simple_module_of_finrank_eq_one h)
e4956403120ae6a285ef4707c7f309c8f281e7f1
c777c32c8e484e195053731103c5e52af26a25d1
/src/field_theory/is_alg_closed/algebraic_closure.lean
18dc842228302d90b416c1da849a48d01636deb0
[ "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
10,858
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_limit import algebra.char_p.algebra import field_theory.is_alg_closed.basic /-! # Algebraic Closure In this file we construct the algebraic closure of a field ## Main Definitions - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## Tags algebraic closure, algebraically closed -/ universes u v w noncomputable theory open_locale classical big_operators polynomial open polynomial variables (k : Type u) [field k] namespace algebraic_closure open mv_polynomial /-- The subtype of monic irreducible polynomials -/ @[reducible] def monic_irreducible : Type u := { f : k[X] // monic f ∧ irreducible f } /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (X f) f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span $ set.range $ eval_X_self k /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (s : finset (monic_irreducible k)) : mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : k[X]) := mv_polynomial.aeval $ λ f, if hf : f ∈ s then root_of_splits _ ((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1 (splitting_field.splits _) f hf) (mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit) else 37 theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) : to_splitting_field k s (eval_X_self k f) = 0 := by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂, alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf, ← algebra_map_eq, alg_hom.comp_algebra_map], exact map_root_of_splits _ _ _ } theorem span_eval_ne_top : span_eval k ≠ ⊤ := begin rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨v, _, hv⟩, replace hv := congr_arg (to_splitting_field k v.support) hv, rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv, { exact zero_ne_one hv }, intros j hj, rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero] end /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) := classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k instance max_ideal.is_maximal : (max_ideal k).is_maximal := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1 theorem le_max_ideal : span_eval k ≤ max_ideal k := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2 /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic : Type u := mv_polynomial (monic_irreducible k) k ⧸ max_ideal k instance adjoin_monic.field : field (adjoin_monic k) := ideal.quotient.field _ instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩ /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic : k →+* adjoin_monic k := (ideal.quotient.mk _).comp C instance adjoin_monic.algebra : algebra k (adjoin_monic k) := (to_adjoin_monic k).to_algebra theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C := rfl theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z := let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸ mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add) (λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1, by { erw [adjoin_monic.algebra_map, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩) theorem adjoin_monic.exists_root {f : k[X]} (hfm : f.monic) (hfi : irreducible f) : ∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 := ⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k), by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩ /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (n : ℕ) : Σ α : Type u, field α := nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩ /-- The `n`th step of constructing `algebraic_closure`. -/ def step (n : ℕ) : Type u := (step_aux k n).1 instance step.field (n : ℕ) : field (step k n) := (step_aux k n).2 instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩ /-- The canonical inclusion to the `0`th step. -/ def to_step_zero : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) := @to_adjoin_monic (step k n) (step.field k n) instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) := (to_step_succ k n).to_algebra theorem to_step_succ.exists_root {n} {f : polynomial (step k n)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 := @adjoin_monic.exists_root _ (step.field k n) _ hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n := { to_fun := nat.le_rec_on h (λ n, to_step_succ k n), map_one' := begin induction h with n h ih, { exact nat.le_rec_on_self 1 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_one] end, map_mul' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul] end, map_zero' := begin induction h with n h ih, { exact nat.le_rec_on_self 0 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero] end, map_add' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add] end } @[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) : (to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) := rfl instance step.algebra (n) : algebra k (step k n) := (to_step_of_le k 0 n n.zero_le).to_algebra instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq $ λ z, @nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z theorem step.is_integral (n) : ∀ z : step k n, is_integral k z := nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z, is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _) instance to_step_of_le.directed_system : directed_system (step k) (λ i j h, to_step_of_le k i j h) := ⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩ end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure : Type u := ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h) namespace algebraic_closure instance : field (algebraic_closure k) := field.direct_limit.field _ _ instance : inhabited (algebraic_closure k) := ⟨37⟩ /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (n : ℕ) : step k n →+* algebraic_closure k := ring.direct_limit.of _ _ _ instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) := (of_step k n).to_algebra theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n := ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _, by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm } theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z := ring.direct_limit.exists_of z -- slow theorem exists_root {f : polynomial (algebraic_closure k)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : algebraic_closure k, f.eval x = 0 := begin have : ∃ n p, polynomial.map (of_step k n) p = f, { convert ring.direct_limit.polynomial.exists_of f }, unfreezingI { obtain ⟨n, p, rfl⟩ := this }, rw monic_map_iff at hfm, have := hfm.irreducible_of_irreducible_map (of_step k n) p hfi, obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this, refine ⟨of_step k (n + 1) x, _⟩, rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero] end instance : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root _ $ λ f, exists_root k instance {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra R (algebraic_closure k) := ((of_step k 0).comp (@algebra_map _ _ _ _ alg)).to_algebra lemma algebra_map_def {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra_map R (algebraic_closure k) = ((of_step k 0 : k →+* _).comp (@algebra_map _ _ _ _ alg)) := rfl instance {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] [algebra S k] [algebra R k] [is_scalar_tower R S k] : is_scalar_tower R S (algebraic_closure k) := is_scalar_tower.of_algebra_map_eq (λ x, ring_hom.congr_arg _ (is_scalar_tower.algebra_map_apply R S k x : _)) /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k := { commutes' := λ x, ring.direct_limit.of_f n.zero_le x, .. of_step k n } theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) := λ z, is_algebraic_iff_is_integral.2 $ let ⟨n, x, hx⟩ := exists_of_step k z in hx ▸ map_is_integral (of_step_hom k n) (step.is_integral k n x) instance : is_alg_closure k (algebraic_closure k) := ⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩ end algebraic_closure
e71efa5d8211cc6416f60ce7c9a485b3696c5a1e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/essentially_small.lean
df2db569955244a387ca981d22213ff5c778110c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,509
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 logic.small.basic import category_theory.category.ulift import category_theory.skeletal /-! # Essentially small categories. A category given by `(C : Type u) [category.{v} C]` is `w`-essentially small if there exists a `small_model C : Type w` equipped with `[small_category (small_model C)]`. A category is `w`-locally small if every hom type is `w`-small. The main theorem here is that a category is `w`-essentially small iff the type `skeleton C` is `w`-small, and `C` is `w`-locally small. -/ universes w v v' u u' open category_theory variables (C : Type u) [category.{v} C] namespace category_theory /-- A category is `essentially_small.{w}` if there exists an equivalence to some `S : Type w` with `[small_category S]`. -/ class essentially_small (C : Type u) [category.{v} C] : Prop := (equiv_small_category : ∃ (S : Type w) (_ : small_category S), by exactI nonempty (C ≌ S)) /-- Constructor for `essentially_small C` from an explicit small category witness. -/ lemma essentially_small.mk' {C : Type u} [category.{v} C] {S : Type w} [small_category S] (e : C ≌ S) : essentially_small.{w} C := ⟨⟨S, _, ⟨e⟩⟩⟩ /-- An arbitrarily chosen small model for an essentially small category. -/ @[nolint has_nonempty_instance] def small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : Type w := classical.some (@essentially_small.equiv_small_category C _ _) noncomputable instance small_category_small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : small_category (small_model C) := classical.some (classical.some_spec (@essentially_small.equiv_small_category C _ _)) /-- The (noncomputable) categorical equivalence between an essentially small category and its small model. -/ noncomputable def equiv_small_model (C : Type u) [category.{v} C] [essentially_small.{w} C] : C ≌ small_model C := nonempty.some (classical.some_spec (classical.some_spec (@essentially_small.equiv_small_category C _ _))) lemma essentially_small_congr {C : Type u} [category.{v} C] {D : Type u'} [category.{v'} D] (e : C ≌ D) : essentially_small.{w} C ↔ essentially_small.{w} D := begin fsplit, { rintro ⟨S, 𝒮, ⟨f⟩⟩, resetI, exact essentially_small.mk' (e.symm.trans f), }, { rintro ⟨S, 𝒮, ⟨f⟩⟩, resetI, exact essentially_small.mk' (e.trans f), }, end lemma discrete.essentially_small_of_small {α : Type u} [small.{w} α] : essentially_small.{w} (discrete α) := ⟨⟨discrete (shrink α), ⟨infer_instance, ⟨discrete.equivalence (equiv_shrink _)⟩⟩⟩⟩ lemma essentially_small_self : essentially_small.{max w v u} C := essentially_small.mk' (as_small.equiv : C ≌ as_small.{w} C) /-- A category is `w`-locally small if every hom set is `w`-small. See `shrink_homs C` for a category instance where every hom set has been replaced by a small model. -/ class locally_small (C : Type u) [category.{v} C] : Prop := (hom_small : ∀ X Y : C, small.{w} (X ⟶ Y) . tactic.apply_instance) instance (C : Type u) [category.{v} C] [locally_small.{w} C] (X Y : C) : small (X ⟶ Y) := locally_small.hom_small X Y lemma locally_small_congr {C : Type u} [category.{v} C] {D : Type u'} [category.{v'} D] (e : C ≌ D) : locally_small.{w} C ↔ locally_small.{w} D := begin fsplit, { rintro ⟨L⟩, fsplit, intros X Y, specialize L (e.inverse.obj X) (e.inverse.obj Y), refine (small_congr _).mpr L, exact equiv_of_fully_faithful e.inverse, }, { rintro ⟨L⟩, fsplit, intros X Y, specialize L (e.functor.obj X) (e.functor.obj Y), refine (small_congr _).mpr L, exact equiv_of_fully_faithful e.functor, }, end @[priority 100] instance locally_small_self (C : Type u) [category.{v} C] : locally_small.{v} C := {} @[priority 100] instance locally_small_of_essentially_small (C : Type u) [category.{v} C] [essentially_small.{w} C] : locally_small.{w} C := (locally_small_congr (equiv_small_model C)).mpr (category_theory.locally_small_self _) /-- We define a type alias `shrink_homs C` for `C`. When we have `locally_small.{w} C`, we'll put a `category.{w}` instance on `shrink_homs C`. -/ @[nolint has_nonempty_instance] def shrink_homs (C : Type u) := C namespace shrink_homs section variables {C' : Type*} -- a fresh variable with no category instance attached /-- Help the typechecker by explicitly translating from `C` to `shrink_homs C`. -/ def to_shrink_homs {C' : Type*} (X : C') : shrink_homs C' := X /-- Help the typechecker by explicitly translating from `shrink_homs C` to `C`. -/ def from_shrink_homs {C' : Type*} (X : shrink_homs C') : C' := X @[simp] lemma to_from (X : C') : from_shrink_homs (to_shrink_homs X) = X := rfl @[simp] lemma from_to (X : shrink_homs C') : to_shrink_homs (from_shrink_homs X) = X := rfl end variables (C) [locally_small.{w} C] @[simps] noncomputable instance : category.{w} (shrink_homs C) := { hom := λ X Y, shrink (from_shrink_homs X ⟶ from_shrink_homs Y), id := λ X, equiv_shrink _ (𝟙 (from_shrink_homs X)), comp := λ X Y Z f g, equiv_shrink _ (((equiv_shrink _).symm f) ≫ ((equiv_shrink _).symm g)), }. /-- Implementation of `shrink_homs.equivalence`. -/ @[simps] noncomputable def functor : C ⥤ shrink_homs C := { obj := λ X, to_shrink_homs X, map := λ X Y f, equiv_shrink (X ⟶ Y) f, } /-- Implementation of `shrink_homs.equivalence`. -/ @[simps] noncomputable def inverse : shrink_homs C ⥤ C := { obj := λ X, from_shrink_homs X, map := λ X Y f, (equiv_shrink (from_shrink_homs X ⟶ from_shrink_homs Y)).symm f, } /-- The categorical equivalence between `C` and `shrink_homs C`, when `C` is locally small. -/ @[simps] noncomputable def equivalence : C ≌ shrink_homs C := equivalence.mk (functor C) (inverse C) (nat_iso.of_components (λ X, iso.refl X) (by tidy)) (nat_iso.of_components (λ X, iso.refl X) (by tidy)) end shrink_homs /-- A category is essentially small if and only if the underlying type of its skeleton (i.e. the "set" of isomorphism classes) is small, and it is locally small. -/ theorem essentially_small_iff (C : Type u) [category.{v} C] : essentially_small.{w} C ↔ small.{w} (skeleton C) ∧ locally_small.{w} C := begin -- This theorem is the only bit of real work in this file. fsplit, { intro h, fsplit, { rcases h with ⟨S, 𝒮, ⟨e⟩⟩, resetI, refine ⟨⟨skeleton S, ⟨_⟩⟩⟩, exact e.skeleton_equiv, }, { resetI, apply_instance, }, }, { rintro ⟨⟨S, ⟨e⟩⟩, L⟩, resetI, let e' := (shrink_homs.equivalence C).skeleton_equiv.symm, refine ⟨⟨S, _, ⟨_⟩⟩⟩, apply induced_category.category (e'.trans e).symm, refine (shrink_homs.equivalence C).trans ((skeleton_equivalence _).symm.trans ((induced_functor (e'.trans e).symm).as_equivalence.symm)), }, end /-- Any thin category is locally small. -/ @[priority 100] instance locally_small_of_thin {C : Type u} [category.{v} C] [quiver.is_thin C] : locally_small.{w} C := {} /-- A thin category is essentially small if and only if the underlying type of its skeleton is small. -/ theorem essentially_small_iff_of_thin {C : Type u} [category.{v} C] [quiver.is_thin C] : essentially_small.{w} C ↔ small.{w} (skeleton C) := by simp [essentially_small_iff, category_theory.locally_small_of_thin] end category_theory
e3b7ab57531bf4758b72aab27438045c8436ec7e
c213e436cb87414954d055137f2a847a9674d7d2
/src/measure_theory/borel_space.lean
3eef27f58cfee42e271882b0095475271940512b
[ "Apache-2.0" ]
permissive
dsanjen/mathlib
642d270c3d209cfdfb097c2ddc9dd36c102fae9f
a3844c85c606acca5922408217d55891b760fad6
refs/heads/master
1,606,199,308,451
1,576,274,676,000
1,576,274,676,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,108
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 Borel (measurable) space -- the smallest σ-algebra generated by open sets It would be nice to encode this in the topological space type class, i.e. each topological space carries a measurable space, the Borel space. This would be similar how each uniform space carries a topological space. The idea is to allow definitional equality for product instances. We would like to have definitional equality for borel t₁ × borel t₂ = borel (t₁ × t₂) Unfortunately, this only holds if t₁ and t₂ are second-countable topologies. -/ import measure_theory.measurable_space topology.instances.ennreal analysis.normed_space.basic noncomputable theory open classical set lattice real open_locale classical universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α} open measurable_space topological_space @[instance, priority 900] def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @is_measurable.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [orderable_topology α] : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : {b | a < b} = -Iio a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : {b | a < b} = ⋃ x : v, -Iio x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [orderable_topology α] : borel α = generate_from (range (λ a, {x | a < x})) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (orderable_topology.topology_eq_generate_intervals α), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : {b | b < a} = -{x | a' < x}), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : {b | b < a} = ⋃ x : v, -{b | x.1.1 < b}, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := calc @borel α (t.induced f) = measurable_space.generate_from (preimage f '' {s | is_open s }) : congr_arg measurable_space.generate_from $ set.ext $ assume s : set α, show (t.induced f).is_open s ↔ s ∈ preimage f '' {s | is_open s}, by simp [topological_space.induced, set.image, eq_comm]; refl ... = (@borel β t).comap f : comap_generate_from.symm section variables [topological_space α] lemma is_measurable_of_is_open : is_open s → is_measurable s := generate_measurable.basic s lemma is_measurable_interior : is_measurable (interior s) := is_measurable_of_is_open is_open_interior lemma is_measurable_ball [metric_space β] {x : β} {ε : ℝ} : is_measurable (metric.ball x ε) := is_measurable_of_is_open metric.is_open_ball lemma is_measurable_of_is_closed (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ is_measurable_of_is_open h lemma is_measurable_singleton [t1_space α] {x : α} : is_measurable ({x} : set α) := is_measurable_of_is_closed is_closed_singleton lemma is_measurable_closure : is_measurable (closure s) := is_measurable_of_is_closed is_closed_closure lemma measurable_of_continuous [topological_space β] {f : α → β} (h : continuous f) : measurable f := measurable_generate_from $ assume t ht, is_measurable_of_is_open $ h t ht lemma borel_prod_le [topological_space β] : prod.measurable_space ≤ borel (α × β) := sup_le (comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_fst) (comap_le_iff_le_map.mpr $ measurable_of_continuous continuous_snd) lemma borel_induced {α β} [t : topological_space β] (f : α → β) : @borel α (t.induced f) = (borel β).comap f := comap_generate_from.symm lemma borel_eq_subtype (s : set α) : borel s = subtype.measurable_space := borel_induced coe lemma borel_prod [second_countable_topology α] [topological_space β] [second_countable_topology β] : prod.measurable_space = borel (α × β) := let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := @is_open_generated_countable_inter α _ _ in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := @is_open_generated_countable_inter β _ _ in le_antisymm borel_prod_le begin have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], exact generate_from_le (assume p ⟨u, hu, v, hv, eq⟩, have hu : is_open u, by rw [ha₅]; exact generate_open.basic _ hu, have hv : is_open v, by rw [hb₅]; exact generate_open.basic _ hv, eq.symm ▸ is_measurable_set_prod (is_measurable_of_is_open hu) (is_measurable_of_is_open hv)) end lemma measurable_of_continuous2 {α β γ} [topological_space α] [second_countable_topology α] [topological_space β] [second_countable_topology β] [topological_space γ] [measurable_space δ] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λa, c (f a) (g a)) := show measurable ((λp:α×β, c p.1 p.2) ∘ (λa, (f a, g a))), begin apply measurable.comp, { rw borel_prod, exact measurable_of_continuous h }, { exact measurable.prod_mk hf hg } end lemma measurable.add [add_monoid α] [topological_add_monoid α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a + g a) := measurable_of_continuous2 continuous_add lemma measurable_finset_sum {ι : Type*} [add_comm_monoid α] [topological_add_monoid α] [second_countable_topology α] [measurable_space β] {f : ι → β → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, s.sum (λi, f i a)) := finset.induction_on s (by simpa using measurable_const) (assume i s his ih, by simpa [his] using measurable.add (hf i) ih) lemma measurable.neg [add_group α] [topological_add_group α] [measurable_space β] {f : β → α} (hf : measurable f) : measurable (λa, - f a) := (measurable_of_continuous continuous_neg).comp hf lemma measurable_neg_iff [add_group α] [topological_add_group α] [measurable_space β] (f : β → α) : measurable (-f) ↔ measurable f := iff.intro begin assume h, have := measurable.neg h, convert this, funext, simp only [pi.neg_apply, _root_.neg_neg] end $ measurable.neg lemma measurable.sub [add_group α] [topological_add_group α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a - g a) := measurable_of_continuous2 continuous_sub lemma measurable.mul [monoid α] [topological_monoid α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} : measurable f → measurable g → measurable (λa, f a * g a) := measurable_of_continuous2 continuous_mul lemma is_measurable_le {α β} [topological_space α] [partial_order α] [ordered_topology α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := have is_measurable {p : α × α | p.1 ≤ p.2}, by rw borel_prod; exact is_measurable_of_is_closed (ordered_topology.is_closed_le' _), show is_measurable {a | (f a, g a).1 ≤ (f a, g a).2}, begin refine measurable.preimage _ this, exact measurable.prod_mk hf hg end lemma measurable.max {α β} [topological_space α] [decidable_linear_order α] [ordered_topology α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λa, max (f a) (g a)) := measurable.if (is_measurable_le hf hg) hg hf lemma measurable.min {α β} [topological_space α] [decidable_linear_order α] [ordered_topology α] [second_countable_topology α] [measurable_space β] {f : β → α} {g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λa, min (f a) (g a)) := measurable.if (is_measurable_le hf hg) hf hg -- generalize lemma measurable_coe_int_real : measurable (λa, a : ℤ → ℝ) := assume s (hs : is_measurable s), by trivial section ordered_topology variables [linear_order α] [ordered_topology α] {a b c : α} lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_measurable_of_is_open is_open_Ioo lemma is_measurable_Iio : is_measurable (Iio a) := is_measurable_of_is_open is_open_Iio lemma is_measurable_Ico : is_measurable (Ico a b) := (is_measurable_of_is_closed $ is_closed_le continuous_const continuous_id).inter is_measurable_Iio end ordered_topology lemma measurable.is_lub {α} [topological_space α] [linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin rw borel_eq_generate_Ioi α, apply measurable_generate_from, rintro _ ⟨a, rfl⟩, have : {b | a < g b} = ⋃ i, {b | a < f i b}, { simp [set.ext_iff], intro b, rw [lt_is_lub_iff (hg b)], exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ }, show is_measurable {b | a < g b}, rw this, exact is_measurable.Union (λ i, hf i _ (is_measurable_of_is_open (is_open_lt' _))) end lemma measurable.is_glb {α} [topological_space α] [linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} {g : β → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin rw borel_eq_generate_Iio α, apply measurable_generate_from, rintro _ ⟨a, rfl⟩, have : {b | g b < a} = ⋃ i, {b | f i b < a}, { simp [set.ext_iff], intro b, rw [is_glb_lt_iff (hg b)], exact ⟨λ ⟨_, ⟨i, rfl⟩, h⟩, ⟨i, h⟩, λ ⟨i, h⟩, ⟨_, ⟨i, rfl⟩, h⟩⟩ }, show is_measurable {b | g b < a}, rw this, exact is_measurable.Union (λ i, hf i _ (is_measurable_of_is_open (is_open_gt' _))) end lemma measurable.supr {α} [topological_space α] [complete_linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable.infi {α} [topological_space α] [complete_linear_order α] [orderable_topology α] [second_countable_topology α] {β} [measurable_space β] {ι} [encodable ι] {f : ι → β → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi lemma measurable.supr_Prop {α} [topological_space α] [complete_linear_order α] {β} [measurable_space β] {p : Prop} {f : β → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) lemma measurable.infi_Prop {α} [topological_space α] [complete_linear_order α] {β} [measurable_space β] {p : Prop} {f : β → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) end def homemorph.to_measurable_equiv [topological_space α] [topological_space β] (h : α ≃ₜ β) : measurable_equiv α β := { to_equiv := h.to_equiv, measurable_to_fun := measurable_of_continuous h.continuous_to_fun, measurable_inv_fun := measurable_of_continuous h.continuous_inv_fun } namespace real open measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃a:ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, rfl|⟨⟨⟩⟩⟩, rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, - Iio c) ∩ Iio b), { have hg : ∀q:ℚ, g.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_measurable_of_is_open (is_open_gt' _) } end end real namespace nnreal open filter lemma measurable.add [measurable_space α] {f : α → nnreal} {g : α → nnreal} : measurable f → measurable g → measurable (λa, f a + g a) := measurable_of_continuous2 continuous_add lemma measurable.sub [measurable_space α] {f g: α → nnreal} (hf : measurable f) (hg : measurable g) : measurable (λ a, f a - g a) := measurable_of_continuous2 continuous_sub hf hg lemma measurable.mul [measurable_space α] {f : α → nnreal} {g : α → nnreal} : measurable f → measurable g → measurable (λa, f a * g a) := measurable_of_continuous2 continuous_mul lemma measurable_of_real : measurable nnreal.of_real := measurable_of_continuous nnreal.continuous_of_real end nnreal namespace ennreal open filter lemma measurable_coe : measurable (coe : nnreal → ennreal) := measurable_of_continuous (continuous_coe.2 continuous_id) def ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r < ⊤} nnreal := { to_fun := λr, ennreal.to_nnreal r.1, inv_fun := λr, ⟨r, coe_lt_top⟩, left_inv := assume ⟨r, hr⟩, by simp [coe_to_nnreal (ne_of_lt hr)], right_inv := assume r, to_nnreal_coe, measurable_to_fun := begin rw [← borel_eq_subtype], refine measurable_of_continuous (continuous_iff_continuous_at.2 _), rintros ⟨r, hr⟩, simp [continuous_at, nhds_subtype_eq_comap], refine tendsto.comp (tendsto_to_nnreal (ne_of_lt hr)) tendsto_comap end, measurable_inv_fun := measurable.subtype_mk measurable_coe } lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α} (h : measurable (λp:nnreal, f p)) : measurable f := begin refine measurable_of_measurable_union_cover {⊤} {r : ennreal | r < ⊤} (is_measurable_of_is_closed $ is_closed_singleton) (is_measurable_of_is_open $ is_open_gt' _) (assume r _, by cases r; simp [ennreal.none_eq_top, ennreal.some_eq_coe]) _ _, exact (measurable_equiv.set.singleton ⊤).symm.measurable_coe_iff.1 (measurable_unit _), exact (ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) end def ennreal_equiv_sum : @measurable_equiv ennreal (nnreal ⊕ unit) _ sum.measurable_space := { to_fun := @option.rec nnreal (λ_, nnreal ⊕ unit) (sum.inr ()) (sum.inl : nnreal → nnreal ⊕ unit), inv_fun := @sum.rec nnreal unit (λ_, ennreal) (coe : nnreal → ennreal) (λ_, ⊤), left_inv := assume s, by cases s; refl, right_inv := assume s, by rcases s with r | ⟨⟨⟩⟩; refl, measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤) } lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β] (f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal} (h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2)) (h₂ : measurable (λr:nnreal, f ⊤ r)) (h₃ : measurable (λr:nnreal, f r ⊤)) (hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) := let e : measurable_equiv (ennreal × ennreal) (((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) := (measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans (measurable_equiv.sum_prod_sum _ _ _ _) in have measurable (λp:ennreal×ennreal, f p.1 p.2), begin refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)), { show measurable (λp:nnreal × nnreal, f p.1 p.2), exact h₁ }, { show measurable (λp:nnreal × unit, f p.1 ⊤), exact h₃.comp (measurable.fst measurable_id) }, { show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)), exact h₂.comp (measurable.snd measurable_id) }, { show measurable (λp:unit × unit, f ⊤ ⊤), exact measurable_const } end, this.comp (measurable.prod_mk hg hh) lemma measurable.mul {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a * g a) := begin refine measurable_of_measurable_nnreal_nnreal (*) _ _ _, { simp only [ennreal.coe_mul.symm], exact measurable_coe.comp (measurable.mul (measurable.fst measurable_id) (measurable.snd measurable_id)) }, { simp [top_mul], exact measurable.if (is_measurable_of_is_closed $ is_closed_eq continuous_id continuous_const) measurable_const measurable_const }, { simp [mul_top], exact measurable.if (is_measurable_of_is_closed $ is_closed_eq continuous_id continuous_const) measurable_const measurable_const } end lemma measurable.add {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a + g a) := begin refine measurable_of_measurable_nnreal_nnreal (+) _ _ _, { simp only [ennreal.coe_add.symm], exact measurable_coe.comp (measurable.add (measurable.fst measurable_id) (measurable.snd measurable_id)) }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable.sub {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a - g a) := begin refine measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _, { simp only [ennreal.coe_sub.symm], exact measurable_coe.comp (nnreal.measurable.sub (measurable.fst measurable_id) (measurable.snd measurable_id)) }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable_of_real : measurable ennreal.of_real := measurable_of_continuous ennreal.continuous_of_real end ennreal namespace measure_theory open topological_space lemma measurable_smul' {α : Type*} {β : Type*} {γ : Type*} [semiring α] [topological_space α] [second_countable_topology α] [topological_space β] [add_comm_monoid β] [second_countable_topology β] [semimodule α β] [topological_semimodule α β] [measurable_space γ] {f : γ → α} {g : γ → β} (hf : measurable f) (hg : measurable g) : measurable (λ c, f c • g c) := measurable_of_continuous2 (continuous_smul continuous_fst continuous_snd) hf hg lemma measurable_smul {α : Type*} {β : Type*} {γ : Type*} [semiring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] [topological_semimodule α β] [measurable_space γ] (c : α) {f : γ → β} (hf : measurable f) : measurable (λ x, c • f x) := measurable.comp (measurable_of_continuous (continuous_smul continuous_const continuous_id)) hf lemma measurable_smul_iff {α : Type*} {β : Type*} {γ : Type*} [division_ring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] [topological_semimodule α β] [measurable_space γ] {c : α} (hc : c ≠ 0) (f : γ → β) : measurable (λ x, c • f x) ↔ measurable f := iff.intro begin assume h, have eq : (λ (x : γ), c⁻¹ • (λ (x : γ), c • f x) x) = f, { funext, rw [smul_smul, inv_mul_cancel hc, one_smul] }, have := measurable_smul c⁻¹ h, rwa eq at this end $ measurable_smul c lemma measurable_dist' {α : Type*} [metric_space α] [second_countable_topology α] : measurable (λp:α×α, dist p.1 p.2) := begin rw [borel_prod], apply measurable_of_continuous, exact continuous_dist continuous_fst continuous_snd end lemma measurable_dist {α : Type*} [metric_space α] [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := measurable.comp measurable_dist' (measurable.prod_mk hf hg) lemma measurable_nndist' {α : Type*} [metric_space α] [second_countable_topology α] : measurable (λp:α×α, nndist p.1 p.2) := begin rw [borel_prod], apply measurable_of_continuous, exact continuous_nndist continuous_fst continuous_snd end lemma measurable_nndist {α : Type*} [metric_space α] [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := measurable.comp measurable_nndist' (measurable.prod_mk hf hg) lemma measurable_edist' {α : Type*} [emetric_space α] [second_countable_topology α] : measurable (λp:α×α, edist p.1 p.2) := begin rw [borel_prod], apply measurable_of_continuous, exact continuous_edist continuous_fst continuous_snd end lemma measurable_edist {α : Type*} [emetric_space α] [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := measurable.comp measurable_edist' (measurable.prod_mk hf hg) lemma measurable_norm' {α : Type*} [normed_group α] : measurable (norm : α → ℝ) := measurable_of_continuous continuous_norm lemma measurable_norm {α : Type*} [normed_group α] [measurable_space β] {f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) := measurable.comp measurable_norm' hf lemma measurable_nnnorm' {α : Type*} [normed_group α] : measurable (nnnorm : α → nnreal) := measurable_of_continuous continuous_nnnorm lemma measurable_nnnorm {α : Type*} [normed_group α] [measurable_space β] {f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) := measurable.comp measurable_nnnorm' hf lemma measurable_coe_nnnorm {α : Type*} [normed_group α] [measurable_space β] {f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) := measurable.comp ennreal.measurable_coe $ measurable_nnnorm hf end measure_theory
5c62055987955ee1fe630537afdf572701ed2345
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/lint.lean
7b27edbb0eaf8c51e69d84c48bbea7a7958e64b8
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,805
lean
import tactic.lint import algebra.ring.basic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) /-- Test exception in `def_lemma` linter. -/ @[pattern] def my_exists_intro := @Exists.intro -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 4, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing.", errors_found := "found something:" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt lint_verbosity.medium [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 20 d, guard $ s = "type-class inference timed out" local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end instance beta_redex_test {α} [monoid α] : (λ (X : Type), has_mul X) α := ⟨(*)⟩ run_cmd do d ← get_decl `beta_redex_test, x ← linter.instance_priority.test d, guard $ x = some "set priority below 1000" /- test of `apply_to_fresh_variables` -/ run_cmd do e ← mk_const `id, e2 ← apply_to_fresh_variables e, type_check e2, `(@id %%α %%a) ← instantiate_mvars e2, expr.sort (level.succ $ level.mvar u) ← infer_type α, skip /- Test exception in `def_lemma` linter. -/ run_cmd do d ← get_decl `my_exists_intro, t ← linter.def_lemma.test d, guard $ t = none
cbea7a8d05e38e7820e25bb8406fae306fb2ce1f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/Json/Basic.lean
46bdb5062174625cb4bf3b2530902adec562a2d2
[ "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
9,078
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.RBTree namespace Lean -- mantissa * 10^-exponent structure JsonNumber where mantissa : Int exponent : Nat deriving DecidableEq namespace JsonNumber protected def fromNat (n : Nat) : JsonNumber := ⟨n, 0⟩ protected def fromInt (n : Int) : JsonNumber := ⟨n, 0⟩ instance : Coe Nat JsonNumber := ⟨JsonNumber.fromNat⟩ instance : Coe Int JsonNumber := ⟨JsonNumber.fromInt⟩ instance : OfNat JsonNumber n := ⟨JsonNumber.fromNat n⟩ private partial def countDigits (n : Nat) : Nat := let rec loop (n digits : Nat) : Nat := if n ≤ 9 then digits else loop (n/10) (digits+1) loop n 1 -- convert mantissa * 10^-exponent to 0.mantissa * 10^exponent protected def normalize : JsonNumber → Int × Nat × Int | ⟨m, e⟩ => Id.run do if m = 0 then (0, 0, 0) else let sign : Int := if m > 0 then 1 else -1 let mut mAbs := m.natAbs let nDigits := countDigits mAbs -- eliminate trailing zeros for _ in [0:nDigits] do if mAbs % 10 = 0 then mAbs := mAbs / 10 else break (sign, mAbs, -(e : Int) + nDigits) -- todo (Dany): We should have an Ordering version of this. def lt (a b : JsonNumber) : Bool := let (as, am, ae) := a.normalize let (bs, bm, be) := b.normalize match (as, bs) with | (-1, 1) => true | (1, -1) => false | _ => let ((am, ae), (bm, be)) := if as = -1 && bs = -1 then ((bm, be), (am, ae)) else ((am, ae), (bm, be)) let amDigits := countDigits am let bmDigits := countDigits bm -- align the mantissas let (am, bm) := if amDigits < bmDigits then (am * 10^(bmDigits - amDigits), bm) else (am, bm * 10^(amDigits - bmDigits)) if ae < be then true else if ae > be then false else am < bm def ltProp : LT JsonNumber := ⟨fun a b => lt a b = true⟩ instance : LT JsonNumber := ltProp instance (a b : JsonNumber) : Decidable (a < b) := inferInstanceAs (Decidable (lt a b = true)) instance : Ord JsonNumber where compare x y := if x < y then Ordering.lt else if x > y then Ordering.gt else Ordering.eq protected def toString : JsonNumber → String | ⟨m, 0⟩ => m.repr | ⟨m, e⟩ => let sign := if m ≥ 0 then "" else "-" let m := m.natAbs -- if there are too many zeroes after the decimal, we -- use exponents to compress the representation. -- this is mostly done for memory usage reasons: -- the size of the representation would otherwise -- grow exponentially in the value of exponent. let exp : Int := 9 + countDigits m - (e : Int) let exp := if exp < 0 then exp else 0 let e' := (10 : Int) ^ (e - exp.natAbs) let left := (m / e').repr if m % e' = 0 && exp = 0 then s!"{sign}{left}" else let right := e' + m % e' |>.repr.toSubstring.drop 1 |>.dropRightWhile (fun c => c = '0') |>.toString let exp := if exp = 0 then "" else "e" ++ exp.repr s!"{sign}{left}.{right}{exp}" -- shift a JsonNumber by a specified amount of places to the left protected def shiftl : JsonNumber → Nat → JsonNumber -- if s ≤ e, then 10 ^ (s - e) = 1, and hence the mantissa remains unchanged. -- otherwise, the expression pads the mantissa with zeroes -- to accomodate for the remaining places to shift. | ⟨m, e⟩, s => ⟨m * (10 ^ (s - e) : Nat), e - s⟩ -- shift a JsonNumber by a specified amount of places to the right protected def shiftr : JsonNumber → Nat → JsonNumber | ⟨m, e⟩, s => ⟨m, e + s⟩ instance : ToString JsonNumber := ⟨JsonNumber.toString⟩ instance : Repr JsonNumber where reprPrec | ⟨m, e⟩, _ => Std.Format.bracket "⟨" (repr m ++ "," ++ repr e) "⟩" instance : OfScientific JsonNumber where ofScientific mantissa exponentSign decimalExponent := if exponentSign then {mantissa := mantissa, exponent := decimalExponent} else {mantissa := (mantissa * 10 ^ decimalExponent : Nat), exponent := 0} instance : Neg JsonNumber where neg jn := ⟨- jn.mantissa, jn.exponent⟩ instance : Inhabited JsonNumber := ⟨0⟩ def toFloat : JsonNumber → Float | ⟨m, e⟩ => (if m >= 0 then 1.0 else -1.0) * OfScientific.ofScientific m.natAbs true e /-- Creates a json number from a positive float, panicking if it isn't. [todo]EdAyers: Currently goes via a string representation, when more float primitives are available should switch to using those. -/ private def fromPositiveFloat! (x : Float) : JsonNumber := match Lean.Syntax.decodeScientificLitVal? (toString x) with | none => panic! s!"Failed to parse {toString x}" | some (m, sign, e) => OfScientific.ofScientific m sign e /-- Attempts to convert a float to a JsonNumber, if the number isn't finite returns the appropriate string from "NaN", "Infinity", "-Infinity". -/ def fromFloat? (x : Float): Sum String JsonNumber := if x.isNaN then Sum.inl "NaN" else if x.isInf then Sum.inl <| if x > 0 then "Infinity" else "-Infinity" else if x == 0.0 then Sum.inr 0 -- special case to avoid -0.0 else if x < 0.0 then Sum.inr <| Neg.neg <| fromPositiveFloat! <| Neg.neg <| x else Sum.inr <| fromPositiveFloat! <| x end JsonNumber def strLt (a b : String) := Decidable.decide (a < b) inductive Json where | null | bool (b : Bool) | num (n : JsonNumber) | str (s : String) | arr (elems : Array Json) -- uses RBNode instead of RBMap because RBMap is a def -- and thus currently cannot be used to define a type that -- is recursive in one of its parameters | obj (kvPairs : RBNode String (fun _ => Json)) deriving Inhabited namespace Json private partial def beq' : Json → Json → Bool | null, null => true | bool a, bool b => a == b | num a, num b => a == b | str a, str b => a == b | arr a, arr b => let _ : BEq Json := ⟨beq'⟩ a == b | obj a, obj b => let _ : BEq Json := ⟨beq'⟩ let szA := a.fold (init := 0) (fun a _ _ => a + 1) let szB := b.fold (init := 0) (fun a _ _ => a + 1) szA == szB && a.all fun field fa => match b.find compare field with | none => false | some fb => fa == fb | _, _ => false instance : BEq Json where beq := beq' -- HACK(Marc): temporary ugliness until we can use RBMap for JSON objects def mkObj (o : List (String × Json)) : Json := obj <| Id.run do let mut kvPairs := RBNode.leaf for ⟨k, v⟩ in o do kvPairs := kvPairs.insert compare k v kvPairs instance : Coe Nat Json := ⟨fun n => Json.num n⟩ instance : Coe Int Json := ⟨fun n => Json.num n⟩ instance : Coe String Json := ⟨Json.str⟩ instance : Coe Bool Json := ⟨Json.bool⟩ instance : OfNat Json n := ⟨Json.num n⟩ def isNull : Json -> Bool | null => true | _ => false def getObj? : Json → Except String (RBNode String (fun _ => Json)) | obj kvs => return kvs | _ => throw "object expected" def getArr? : Json → Except String (Array Json) | arr a => return a | _ => throw "array expected" def getStr? : Json → Except String String | str s => return s | _ => throw "String expected" def getNat? : Json → Except String Nat | (n : Nat) => return n | _ => throw "Natural number expected" def getInt? : Json → Except String Int | (i : Int) => return i | _ => throw "Integer expected" def getBool? : Json → Except String Bool | (b : Bool) => return b | _ => throw "Bool expected" def getNum? : Json → Except String JsonNumber | num n => return n | _ => throw "number expected" def getObjVal? : Json → String → Except String Json | obj kvs, k => match kvs.find compare k with | some v => return v | none => throw s!"property not found: {k}" | _ , _ => throw "object expected" def getArrVal? : Json → Nat → Except String Json | arr a, i => match a.get? i with | some v => return v | none => throw s!"index out of bounds: {i}" | _ , _ => throw "array expected" def getObjValD (j : Json) (k : String) : Json := (j.getObjVal? k).toOption.getD null def setObjVal! : Json → String → Json → Json | obj kvs, k, v => obj <| kvs.insert compare k v | _ , _, _ => panic! "Json.setObjVal!: not an object: {j}" open Lean.RBNode in /-- Assuming both inputs `o₁, o₂` are json objects, will compute `{...o₁, ...o₂}`. If `o₁` is not a json object, `o₂` will be returned. -/ def mergeObj : Json → Json → Json | obj kvs₁, obj kvs₂ => obj <| fold (insert compare) kvs₁ kvs₂ | _, j₂ => j₂ inductive Structured where | arr (elems : Array Json) | obj (kvPairs : RBNode String (fun _ => Json)) instance : Coe (Array Json) Structured := ⟨Structured.arr⟩ instance : Coe (RBNode String (fun _ => Json)) Structured := ⟨Structured.obj⟩ end Json end Lean
020ccbc7ec81fa0ba204fef72de616cdf8b7c561
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/interval.lean
23dd0ca3882206b4f8513d4c82d393e83d377c5e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
18,364
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.intervals.basic import data.set.lattice import data.set_like.basic /-! # Order intervals This file defines (nonempty) closed intervals in an order (see `set.Icc`). This is a prototype for interval arithmetic. ## Main declarations * `nonempty_interval`: Nonempty intervals. Pairs where the second element is greater than the first. * `interval`: Intervals. Either `∅` or a nonempty interval. -/ open function order_dual set variables {α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The nonempty closed intervals in an order. We define intervals by the pair of endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `nonempty_interval α → set α`. -/ @[ext] structure nonempty_interval (α : Type*) [has_le α] extends α × α := (fst_le_snd : fst ≤ snd) namespace nonempty_interval section has_le variables [has_le α] {s t : nonempty_interval α} lemma to_prod_injective : injective (to_prod : nonempty_interval α → α × α) := λ s t, (ext_iff _ _).2 /-- The injection that induces the order on intervals. -/ def to_dual_prod : nonempty_interval α → αᵒᵈ × α := to_prod @[simp] lemma to_dual_prod_apply (s : nonempty_interval α) : s.to_dual_prod = (to_dual s.fst, s.snd) := prod.mk.eta.symm lemma to_dual_prod_injective : injective (to_dual_prod : nonempty_interval α → αᵒᵈ × α) := to_prod_injective instance [is_empty α] : is_empty (nonempty_interval α) := ⟨λ s, is_empty_elim s.fst⟩ instance [subsingleton α] : subsingleton (nonempty_interval α) := to_dual_prod_injective.subsingleton instance : has_le (nonempty_interval α) := ⟨λ s t, t.fst ≤ s.fst ∧ s.snd ≤ t.snd⟩ lemma le_def : s ≤ t ↔ t.fst ≤ s.fst ∧ s.snd ≤ t.snd := iff.rfl /-- `to_dual_prod` as an order embedding. -/ @[simps] def to_dual_prod_hom : nonempty_interval α ↪o αᵒᵈ × α := { to_fun := to_dual_prod, inj' := to_dual_prod_injective, map_rel_iff' := λ _ _, iff.rfl } /-- Turn an interval into an interval in the dual order. -/ def dual : nonempty_interval α ≃ nonempty_interval αᵒᵈ := { to_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, inv_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, left_inv := λ s, ext _ _ $ prod.swap_swap _, right_inv := λ s, ext _ _ $ prod.swap_swap _ } @[simp] lemma fst_dual (s : nonempty_interval α) : s.dual.fst = to_dual s.snd := rfl @[simp] lemma snd_dual (s : nonempty_interval α) : s.dual.snd = to_dual s.fst := rfl end has_le section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] {s : nonempty_interval α} {x : α × α} {a : α} instance : preorder (nonempty_interval α) := preorder.lift to_dual_prod instance : has_coe_t (nonempty_interval α) (set α) := ⟨λ s, Icc s.fst s.snd⟩ @[priority 100] instance : has_mem α (nonempty_interval α) := ⟨λ a s, a ∈ (s : set α)⟩ @[simp] lemma mem_mk {hx : x.1 ≤ x.2} : a ∈ mk x hx ↔ x.1 ≤ a ∧ a ≤ x.2 := iff.rfl lemma mem_def : a ∈ s ↔ s.fst ≤ a ∧ a ≤ s.snd := iff.rfl @[simp] lemma coe_nonempty (s : nonempty_interval α) : (s : set α).nonempty := nonempty_Icc.2 s.fst_le_snd /-- `{a}` as an interval. -/ @[simps] def pure (a : α) : nonempty_interval α := ⟨⟨a, a⟩, le_rfl⟩ lemma mem_pure_self (a : α) : a ∈ pure a := ⟨le_rfl, le_rfl⟩ lemma pure_injective : injective (pure : α → nonempty_interval α) := λ s t, congr_arg $ prod.fst ∘ to_prod @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl instance [inhabited α] : inhabited (nonempty_interval α) := ⟨pure default⟩ instance : ∀ [nonempty α], nonempty (nonempty_interval α) := nonempty.map pure instance [nontrivial α] : nontrivial (nonempty_interval α) := pure_injective.nontrivial /-- Pushforward of nonempty intervals. -/ @[simps] def map (f : α →o β) (a : nonempty_interval α) : nonempty_interval β := ⟨a.to_prod.map f f, f.mono a.fst_le_snd⟩ @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (a : nonempty_interval α) : (a.map f).map g = a.map (g.comp f) := rfl @[simp] lemma dual_map (f : α →o β) (a : nonempty_interval α) : (a.map f).dual = a.dual.map f.dual := rfl /-- Binary pushforward of nonempty intervals. -/ @[simps] def map₂ (f : α → β → γ) (h₀ : ∀ b, monotone (λ a, f a b)) (h₁ : ∀ a, monotone (f a)) : nonempty_interval α → nonempty_interval β → nonempty_interval γ := λ s t, ⟨(f s.fst t.fst, f s.snd t.snd), (h₀ _ s.fst_le_snd).trans $ h₁ _ t.fst_le_snd⟩ @[simp] lemma map₂_pure (f : α → β → γ) (h₀ h₁) (a : α) (b : β) : map₂ f h₀ h₁ (pure a) (pure b) = pure (f a b) := rfl @[simp] lemma dual_map₂ (f : α → β → γ) (h₀ h₁ s t) : (map₂ f h₀ h₁ s t).dual = map₂ (λ a b, to_dual $ f (of_dual a) $ of_dual b) (λ _, (h₀ _).dual) (λ _, (h₁ _).dual) s.dual t.dual := rfl variables [bounded_order α] instance : order_top (nonempty_interval α) := { top := ⟨⟨⊥, ⊤⟩, bot_le⟩, le_top := λ a, ⟨bot_le, le_top⟩ } @[simp] lemma dual_top : (⊤ : nonempty_interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : nonempty_interval α} {x : α × α} {a b : α} instance : partial_order (nonempty_interval α) := partial_order.lift _ to_dual_prod_injective /-- Consider a nonempty interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : nonempty_interval α ↪o set α := order_embedding.of_map_le_iff (λ s, Icc s.fst s.snd) (λ s t, Icc_subset_Icc_iff s.fst_le_snd) instance : set_like (nonempty_interval α) α := { coe := λ s, Icc s.fst s.snd, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp] lemma coe_coe_hom : (coe_hom : nonempty_interval α → set α) = coe := rfl @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : nonempty_interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : nonempty_interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := dual_Icc lemma subset_coe_map (f : α →o β) (s : nonempty_interval α) : f '' s ⊆ s.map f := image_subset_iff.2 $ λ a ha, ⟨f.mono ha.1, f.mono ha.2⟩ end partial_order section lattice variables [lattice α] instance : has_sup (nonempty_interval α) := ⟨λ s t, ⟨⟨s.fst ⊓ t.fst, s.snd ⊔ t.snd⟩, inf_le_left.trans $ s.fst_le_snd.trans le_sup_left⟩⟩ instance : semilattice_sup (nonempty_interval α) := to_dual_prod_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma fst_sup (s t : nonempty_interval α) : (s ⊔ t).fst = s.fst ⊓ t.fst := rfl @[simp] lemma snd_sup (s t : nonempty_interval α) : (s ⊔ t).snd = s.snd ⊔ t.snd := rfl end lattice end nonempty_interval /-- The closed intervals in an order. We represent intervals either as `⊥` or a nonempty interval given by its endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `interval α → set α`. -/ @[derive [inhabited, has_le, order_bot]] def interval (α : Type*) [has_le α] := with_bot (nonempty_interval α) namespace interval section has_le variables [has_le α] {s t : interval α} instance : has_coe_t (nonempty_interval α) (interval α) := with_bot.has_coe_t instance can_lift : can_lift (interval α) (nonempty_interval α) coe (λ r, r ≠ ⊥) := with_bot.can_lift lemma coe_injective : injective (coe : nonempty_interval α → interval α) := with_bot.coe_injective @[simp, norm_cast] lemma coe_inj {s t : nonempty_interval α} : (s : interval α) = t ↔ s = t := with_bot.coe_inj @[protected] lemma «forall» {p : interval α → Prop} : (∀ s, p s) ↔ p ⊥ ∧ ∀ s : nonempty_interval α, p s := option.forall @[protected] lemma «exists» {p : interval α → Prop} : (∃ s, p s) ↔ p ⊥ ∨ ∃ s : nonempty_interval α, p s := option.exists instance [is_empty α] : unique (interval α) := option.unique /-- Turn an interval into an interval in the dual order. -/ def dual : interval α ≃ interval αᵒᵈ := nonempty_interval.dual.option_congr end has_le section preorder variables [preorder α] [preorder β] [preorder γ] instance : preorder (interval α) := with_bot.preorder /-- `{a}` as an interval. -/ def pure (a : α) : interval α := nonempty_interval.pure a lemma pure_injective : injective (pure : α → interval α) := coe_injective.comp nonempty_interval.pure_injective @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl @[simp] lemma dual_bot : (⊥ : interval α).dual = ⊥ := rfl @[simp] lemma pure_ne_bot {a : α} : pure a ≠ ⊥ := with_bot.coe_ne_bot @[simp] lemma bot_ne_pure {a : α} : ⊥ ≠ pure a := with_bot.bot_ne_coe instance [nonempty α] : nontrivial (interval α) := option.nontrivial /-- Pushforward of intervals. -/ def map (f : α →o β) : interval α → interval β := with_bot.map (nonempty_interval.map f) @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (s : interval α) : (s.map f).map g = s.map (g.comp f) := option.map_map _ _ _ @[simp] lemma dual_map (f : α →o β) (s : interval α) : (s.map f).dual = s.dual.map f.dual := by { cases s, { refl }, { exact with_bot.map_comm rfl _ } } variables [bounded_order α] instance : bounded_order (interval α) := with_bot.bounded_order @[simp] lemma dual_top : (⊤ : interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : interval α} {a b : α} instance : partial_order (interval α) := with_bot.partial_order /-- Consider a interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : interval α ↪o set α := order_embedding.of_map_le_iff (λ s, match s with | ⊥ := ∅ | some s := s end) (λ s t, match s, t with | ⊥, t := iff_of_true bot_le bot_le | some s, ⊥ := iff_of_false (λ h, s.coe_nonempty.ne_empty $ le_bot_iff.1 h) (with_bot.not_coe_le_bot _) | some s, some t := (@nonempty_interval.coe_hom α _).le_iff_le.trans with_bot.some_le_some.symm end) instance : set_like (interval α) α := { coe := coe_hom, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp, norm_cast] lemma coe_coe (s : nonempty_interval α) : ((s : interval α) : set α) = s := rfl @[simp, norm_cast] lemma coe_bot : ((⊥ : interval α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := by { cases s, { refl }, exact s.coe_dual } lemma subset_coe_map (f : α →o β) : ∀ s : interval α, f '' s ⊆ s.map f | ⊥ := by simp | (s : nonempty_interval α) := s.subset_coe_map _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] lemma mem_pure_self (a : α) : a ∈ pure a := mem_pure.2 rfl end partial_order section lattice variables [lattice α] instance : semilattice_sup (interval α) := with_bot.semilattice_sup section decidable variables [@decidable_rel α (≤)] instance : lattice (interval α) := { inf := λ s t, match s, t with | ⊥, t := ⊥ | s, ⊥ := ⊥ | some s, some t := if h : s.fst ≤ t.snd ∧ t.fst ≤ s.snd then some ⟨⟨s.fst ⊔ t.fst, s.snd ⊓ t.snd⟩, sup_le (le_inf s.fst_le_snd h.1) $ le_inf h.2 t.fst_le_snd⟩ else ⊥ end, inf_le_left := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_left, inf_le_left⟩ }, { exact bot_le } end end, inf_le_right := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_right, inf_le_right⟩ }, { exact bot_le } end end, le_inf := λ s t c, match s, t, c with | ⊥, t, c := λ _ _, bot_le | some s, t, c := λ hb hc, begin lift t to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hb, lift c to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hc, change _ ≤ dite _ _ _, simp only [with_bot.some_eq_coe, with_bot.coe_le_coe] at ⊢ hb hc, rw [dif_pos, with_bot.coe_le_coe], exact ⟨sup_le hb.1 hc.1, le_inf hb.2 hc.2⟩, exact ⟨hb.1.trans $ s.fst_le_snd.trans hc.2, hc.1.trans $ s.fst_le_snd.trans hb.2⟩, end end, ..interval.semilattice_sup } @[simp, norm_cast] lemma coe_inf (s t : interval α) : (↑(s ⊓ t) : set α) = s ∩ t := begin cases s, { rw [with_bot.none_eq_bot, bot_inf_eq], exact (empty_inter _).symm }, cases t, { rw [with_bot.none_eq_bot, inf_bot_eq], exact (inter_empty _).symm }, refine (_ : coe (dite _ _ _) = _).trans Icc_inter_Icc.symm, split_ifs, { refl }, { exact (Icc_eq_empty $ λ H, h ⟨le_sup_left.trans $ H.trans inf_le_right, le_sup_right.trans $ H.trans inf_le_left⟩).symm } end end decidable @[simp, norm_cast] lemma disjoint_coe (s t : interval α) : disjoint (s : set α) t ↔ disjoint s t := begin classical, rw [disjoint_iff_inf_le, disjoint_iff_inf_le, le_eq_subset, ←coe_subset_coe, coe_inf], refl end end lattice end interval namespace nonempty_interval section preorder variables [preorder α] {s : nonempty_interval α} {a : α} @[simp, norm_cast] lemma coe_pure_interval (a : α) : (pure a : interval α) = interval.pure a := rfl @[simp, norm_cast] lemma coe_eq_pure : (s : interval α) = interval.pure a ↔ s = pure a := by rw [←interval.coe_inj, coe_pure_interval] @[simp, norm_cast] lemma coe_top_interval [bounded_order α] : ((⊤ : nonempty_interval α) : interval α) = ⊤ := rfl end preorder @[simp, norm_cast] lemma mem_coe_interval [partial_order α] {s : nonempty_interval α} {x : α} : x ∈ (s : interval α) ↔ x ∈ s := iff.rfl @[simp, norm_cast] lemma coe_sup_interval [lattice α] (s t : nonempty_interval α) : (↑(s ⊔ t) : interval α) = s ⊔ t := rfl end nonempty_interval namespace interval section complete_lattice variables [complete_lattice α] noncomputable instance [@decidable_rel α (≤)] : complete_lattice (interval α) := by classical; exact { Sup := λ S, if h : S ⊆ {⊥} then ⊥ else some ⟨⟨⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, begin obtain ⟨s, hs, ha⟩ := not_subset.1 h, lift s to nonempty_interval α using ha, exact infi₂_le_of_le s hs (le_supr₂_of_le s hs s.fst_le_snd) end⟩, le_Sup := λ s s ha, begin split_ifs, { exact (h ha).le }, cases s, { exact bot_le }, { exact with_bot.some_le_some.2 ⟨infi₂_le _ ha, le_supr₂_of_le _ ha le_rfl⟩ } end, Sup_le := λ s s ha, begin split_ifs, { exact bot_le }, obtain ⟨b, hs, hb⟩ := not_subset.1 h, lift s to nonempty_interval α using ne_bot_of_le_ne_bot hb (ha _ hs), exact with_bot.coe_le_coe.2 ⟨le_infi₂ $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).1, supr₂_le $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).2⟩, end, Inf := λ S, if h : ⊥ ∉ S ∧ ∀ ⦃s : nonempty_interval α⦄, ↑s ∈ S → ∀ ⦃t : nonempty_interval α⦄, ↑t ∈ S → s.fst ≤ t.snd then some ⟨⟨⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, supr₂_le $ λ s hs, le_infi₂ $ h.2 hs⟩ else ⊥, Inf_le := λ s s ha, begin split_ifs, { lift s to nonempty_interval α using ne_of_mem_of_not_mem ha h.1, exact with_bot.coe_le_coe.2 ⟨le_supr₂ s ha, infi₂_le s ha⟩ }, { exact bot_le } end, le_Inf := λ S s ha, begin cases s, { exact bot_le }, split_ifs, { exact with_bot.some_le_some.2 ⟨supr₂_le $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).1, le_infi₂ $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).2⟩ }, rw [not_and_distrib, not_not] at h, cases h, { exact ha _ h }, cases h (λ t hb c hc, (with_bot.coe_le_coe.1 $ ha _ hb).1.trans $ s.fst_le_snd.trans (with_bot.coe_le_coe.1 $ ha _ hc).2), end, ..interval.lattice, ..interval.bounded_order } @[simp, norm_cast] lemma coe_Inf (S : set (interval α)) : ↑(Inf S) = ⋂ s ∈ S, (s : set α) := begin change coe (dite _ _ _) = _, split_ifs, { ext, simp [with_bot.some_eq_coe, interval.forall, h.1, ←forall_and_distrib, ←nonempty_interval.mem_def] }, simp_rw [not_and_distrib, not_not] at h, cases h, { refine (eq_empty_of_subset_empty _).symm, exact Inter₂_subset_of_subset _ h subset.rfl }, { refine (not_nonempty_iff_eq_empty.1 _).symm, rintro ⟨x, hx⟩, rw mem_Inter₂ at hx, exact h (λ s ha t hb, (hx _ ha).1.trans (hx _ hb).2) } end @[simp, norm_cast] lemma coe_infi (f : ι → interval α) : ↑(⨅ i, f i) = ⋂ i, (f i : set α) := by simp [infi] @[simp, norm_cast] lemma coe_infi₂ (f : Π i, κ i → interval α) : ↑(⨅ i j, f i j) = ⋂ i j, (f i j : set α) := by simp_rw [coe_infi] end complete_lattice end interval
cd14f581402b302af60fce696c79d46573ac873d
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/category_theory/comma.lean
e4a3f6e5d4e8154da8f1ced11f4744270511c557
[ "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,951
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.types import category_theory.isomorphism import category_theory.whiskering namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ variables {A : Type u₁} [𝒜 : category.{u₁ v₁} A] variables {B : Type u₂} [ℬ : category.{u₂ v₂} B] variables {T : Type u₃} [𝒯 : category.{u₃ v₃} T] include 𝒜 ℬ 𝒯 structure comma (L : A ⥤ T) (R : B ⥤ T) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) variables {L : A ⥤ T} {R : B ⥤ T} structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) restate_axiom comma_morphism.w' attribute [simp] comma_morphism.w namespace comma_morphism @[extensionality] lemma ext {X Y : comma L R} {f g : comma_morphism X Y} (l : f.left = g.left) (r : f.right = g.right) : f = g := begin cases f, cases g, congr; assumption end end comma_morphism instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right, w' := begin rw [functor.map_comp, category.assoc, g.w, ←category.assoc, f.w, functor.map_comp, category.assoc], end }} namespace comma variables (L) (R) def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } @[simp] lemma fst_obj {X : comma L R} : (fst L R).obj X = X.left := rfl @[simp] lemma snd_obj {X : comma L R} : (snd L R).obj X = X.right := rfl @[simp] lemma fst_map {X Y : comma L R} {f : X ⟶ Y} : (fst L R).map f = f.left := rfl @[simp] lemma snd_map {X Y : comma L R} {f : X ⟶ Y} : (snd L R).map f = f.right := rfl def nat_trans : fst L R ⋙ L ⟹ snd L R ⋙ R := { app := λ X, X.hom } variables {L₁ : A ⥤ T} {L₂ : A ⥤ T} variables {R₁ : B ⥤ T} {R₂ : B ⥤ T} def map_left (l : L₁ ⟹ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←category.assoc, l.naturality f.left, category.assoc]; tidy } } def map_right (r : R₁ ⟹ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right, w' := by tidy; rw [←r.naturality f.right, ←category.assoc]; tidy } } end comma end category_theory
284b9cd520301b24e3844ebf374a7bc5b6432786
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/measure_theory/l1_space.lean
655c3b8eea045955582836c9d8ada38100aab972
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
40,404
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ⊤`. * If `β` is moreover a `measurable_space` then `f` is called `integrable` if `f` is `measurable` and `has_finite_integral f` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. To prove something for an arbitrary integrable function, a useful theorem is `integrable.induction` in the file `set_integral`. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space big_operators open set filter topological_space ennreal emetric measure_theory variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α} variables [normed_group β] variables [normed_group γ] namespace measure_theory /-! ### Some results about the Lebesgue integral involving a normed group -/ lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : ∫⁻ a, nnnorm (f a) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hh : ae_measurable h μ) : ∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ := begin rw ← lintegral_add' (hf.edist hh) (hg.edist hh), refine lintegral_mono (λ a, _), apply edist_triangle_right end lemma lintegral_nnnorm_zero : ∫⁻ a : α, nnnorm (0 : β) ∂μ = 0 := by simp lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ + ∫⁻ a, nnnorm (g a) ∂μ := lintegral_add' hf.ennnorm hg.ennnorm lemma lintegral_nnnorm_neg {f : α → β} : ∫⁻ a, nnnorm ((-f) a) ∂μ = ∫⁻ a, nnnorm (f a) ∂μ := by simp only [pi.neg_apply, nnnorm_neg] /-! ### The predicate `has_finite_integral` -/ /-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `has_finite_integral f` means `has_finite_integral f volume`. -/ def has_finite_integral (f : α → β) (μ : measure α . volume_tac) : Prop := ∫⁻ a, nnnorm (f a) ∂μ < ⊤ lemma has_finite_integral_iff_norm (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ < ⊤ := by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm] lemma has_finite_integral_iff_edist (f : α → β) : has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ⊤ := by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right] lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) : has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ⊤ := have lintegral_eq : ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ := begin refine lintegral_congr_ae (h.mono $ λ a h, _), rwa [real.norm_eq_abs, abs_of_nonneg] end, by rw [has_finite_integral_iff_norm, lintegral_eq] lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : has_finite_integral f μ := begin simp only [has_finite_integral_iff_norm] at *, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ∥g a∥) ∂μ : lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h) ... < ⊤ : hg end lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : has_finite_integral f μ := hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _) lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral g μ := hf.mono $ eventually_eq.le $ eventually_eq.symm h lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : has_finite_integral f μ ↔ has_finite_integral g μ := ⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩ lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) : has_finite_integral g μ := hf.congr' $ h.fun_comp norm lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) : has_finite_integral f μ ↔ has_finite_integral g μ := has_finite_integral_congr' $ h.fun_comp norm lemma has_finite_integral_const_iff {c : β} : has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ⊤ := begin simp only [has_finite_integral, lintegral_const], by_cases hc : c = 0, { simp [hc] }, { simp only [hc, false_or], refine ⟨λ h, _, λ h, mul_lt_top coe_lt_top h⟩, replace h := mul_lt_top (@coe_lt_top $ (nnnorm c)⁻¹) h, rwa [← mul_assoc, ← coe_mul, _root_.inv_mul_cancel, coe_one, one_mul] at h, rwa [ne.def, nnnorm_eq_zero] } end lemma has_finite_integral_const [finite_measure μ] (c : β) : has_finite_integral (λ x : α, c) μ := has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _) lemma has_finite_integral_of_bounded [finite_measure μ] {f : α → β} {C : ℝ} (hC : ∀ᵐ a ∂μ, ∥f a∥ ≤ C) : has_finite_integral f μ := (has_finite_integral_const C).mono' hC lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) : has_finite_integral f μ := lt_of_le_of_lt (lintegral_mono' hμ (le_refl _)) h lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) := begin simp only [has_finite_integral, lintegral_add_measure] at *, exact add_lt_top.2 ⟨hμ, hν⟩ end lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) : has_finite_integral f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma has_finite_integral_add_measure {f : α → β} : has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ennreal} (hc : c < ⊤) : has_finite_integral f (c • μ) := begin simp only [has_finite_integral, lintegral_smul_measure] at *, exact mul_lt_top hc h end @[simp] lemma has_finite_integral_zero_measure (f : α → β) : has_finite_integral f 0 := by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top] variables (α β μ) @[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ := by simp [has_finite_integral] variables {α β μ} lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (-f) μ := by simpa [has_finite_integral] using hfi @[simp] lemma has_finite_integral_neg_iff {f : α → β} : has_finite_integral (-f) μ ↔ has_finite_integral f μ := ⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩ lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) : has_finite_integral (λa, ∥f a∥) μ := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [has_finite_integral, eq] } lemma has_finite_integral_norm_iff (f : α → β) : has_finite_integral (λa, ∥f a∥) μ ↔ has_finite_integral f μ := has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x) section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, (h n).mono $ λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ᵐ a ∂μ, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := h.mono $ λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ᵐ a ∂μ, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' tendsto_norm (F_le_bound) end lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : has_finite_integral f μ := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is has_finite_integral -/ begin rw has_finite_integral_iff_norm, calc ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ : lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← has_finite_integral_iff_of_real, { exact bound_has_finite_integral }, exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h) end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (bound_has_finite_integral : has_finite_integral bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ᵐ a ∂μ, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ᵐ a ∂μ, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin rw ← ennreal.of_real_zero, refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _), rwa ← tendsto_iff_norm_tendsto_zero end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 (∫⁻ (a:α), 0 ∂μ)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence' _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is almost everywhere measurable for all `n` { exact λn, measurable_of_real.comp_ae_measurable ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is has_finite_integral { rw has_finite_integral_iff_of_real at bound_has_finite_integral, { calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_has_finite_integral }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, max (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, le_abs_self] lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) : has_finite_integral (λa, min (f a) 0) μ := hf.mono $ eventually_of_forall $ λ x, by simp [real.norm_eq_abs, abs_le, abs_nonneg, neg_le, neg_le_abs_self] end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ → has_finite_integral (c • f) μ := begin simp only [has_finite_integral], assume hfi, calc ∫⁻ (a : α), nnnorm (c • f a) ∂μ = ∫⁻ (a : α), (nnnorm c) * nnnorm (f a) ∂μ : by simp only [nnnorm_smul, ennreal.coe_mul] ... < ⊤ : begin rw lintegral_const_mul', exacts [mul_lt_top coe_lt_top hfi, coe_ne_top] end end lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : has_finite_integral (c • f) μ ↔ has_finite_integral f μ := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact has_finite_integral.smul _ end lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, c * f x) μ := (has_finite_integral.smul c h : _) lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) : has_finite_integral (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space /-! ### The predicate `integrable` -/ variables [measurable_space β] [measurable_space γ] [measurable_space δ] /-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `integrable f` means `integrable f volume`. -/ def integrable (f : α → β) (μ : measure α . volume_tac) : Prop := ae_measurable f μ ∧ has_finite_integral f μ lemma integrable.ae_measurable {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.1 lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ := hf.2 lemma integrable.mono {f : α → β} {g : α → γ} (hg : integrable g μ) (hf : ae_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : integrable f μ := ⟨hf, hg.has_finite_integral.mono h⟩ lemma integrable.mono' {f : α → β} {g : α → ℝ} (hg : integrable g μ) (hf : ae_measurable f μ) (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ g a) : integrable f μ := ⟨hf, hg.has_finite_integral.mono' h⟩ lemma integrable.congr' {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ := ⟨hg, hf.has_finite_integral.congr' h⟩ lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable f μ ↔ integrable g μ := ⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩ lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) : integrable g μ := ⟨hf.1.congr h, hf.2.congr h⟩ lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) : integrable f μ ↔ integrable g μ := ⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩ lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ⊤ := begin have : ae_measurable (λ (x : α), c) μ := measurable_const.ae_measurable, rw [integrable, and_iff_right this, has_finite_integral_const_iff] end lemma integrable_const [finite_measure μ] (c : β) : integrable (λ x : α, c) μ := integrable_const_iff.2 $ or.inr $ measure_lt_top _ _ lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ := ⟨h.ae_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩ lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) : integrable f (μ + ν) := ⟨hμ.ae_measurable.add_measure hν.ae_measurable, hμ.has_finite_integral.add_measure hν.has_finite_integral⟩ lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ := h.mono_measure $ measure.le_add_right $ le_refl _ lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν := h.mono_measure $ measure.le_add_left $ le_refl _ @[simp] lemma integrable_add_measure {f : α → β} : integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν := ⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩ lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ennreal} (hc : c < ⊤) : integrable f (c • μ) := ⟨h.ae_measurable.smul_measure c, h.has_finite_integral.smul_measure hc⟩ lemma integrable_map_measure [opens_measurable_space β] {f : α → δ} {g : δ → β} (hg : ae_measurable g (measure.map f μ)) (hf : measurable f) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by simp [integrable, hg, hg.comp_measurable hf, has_finite_integral, lintegral_map' hg.ennnorm hf] lemma lintegral_edist_lt_top [second_countable_topology β] [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : ∫⁻ a, edist (f a) (g a) ∂μ < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hf.ae_measurable hg.ae_measurable (measurable_const.ae_measurable : ae_measurable (λa, (0 : β)) μ)) (ennreal.add_lt_top.2 $ by { simp_rw ← has_finite_integral_iff_edist, exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ }) variables (α β μ) @[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ := by simp [integrable, measurable_const.ae_measurable] variables {α β μ} lemma integrable.add' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f + g) μ := calc ∫⁻ a, nnnorm (f a + g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (g a) ∂μ : lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _) ... = _ : lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable ... < ⊤ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.add [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ := ⟨hf.ae_measurable.add hg.ae_measurable, hf.add' hg⟩ lemma integrable_finset_sum {ι} [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hf : ∀ i, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], exact (hf _).add ih } end lemma integrable.neg [borel_space β] {f : α → β} (hf : integrable f μ) : integrable (-f) μ := ⟨hf.ae_measurable.neg, hf.has_finite_integral.neg⟩ @[simp] lemma integrable_neg_iff [borel_space β] {f : α → β} : integrable (-f) μ ↔ integrable f μ := ⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩ lemma integrable.sub' [opens_measurable_space β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ := calc ∫⁻ a, nnnorm (f a - g a) ∂μ ≤ ∫⁻ a, nnnorm (f a) + nnnorm (-g a) ∂μ : lintegral_mono (assume a, by { simp only [sub_eq_add_neg], exact_mod_cast nnnorm_add_le _ _ } ) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hf.ae_measurable hg.ae_measurable } ... < ⊤ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.sub [borel_space β] [second_countable_topology β] {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma integrable.norm [opens_measurable_space β] {f : α → β} (hf : integrable f μ) : integrable (λa, ∥f a∥) μ := ⟨hf.ae_measurable.norm, hf.has_finite_integral.norm⟩ lemma integrable_norm_iff [opens_measurable_space β] {f : α → β} (hf : ae_measurable f μ) : integrable (λa, ∥f a∥) μ ↔ integrable f μ := by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff] lemma integrable.prod_mk [opens_measurable_space β] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) : integrable (λ x, (f x, g x)) μ := ⟨hf.ae_measurable.prod_mk hg.ae_measurable, (hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x, calc max ∥f x∥ ∥g x∥ ≤ ∥f x∥ + ∥g x∥ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _) ... ≤ ∥(∥f x∥ + ∥g x∥)∥ : le_abs_self _⟩ section pos_part /-! ### Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, max (f a) 0) μ := ⟨hf.ae_measurable.max measurable_const.ae_measurable, hf.has_finite_integral.max_zero⟩ lemma integrable.min_zero {f : α → ℝ} (hf : integrable f μ) : integrable (λa, min (f a) 0) μ := ⟨hf.ae_measurable.min measurable_const.ae_measurable, hf.has_finite_integral.min_zero⟩ end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul [borel_space β] (c : 𝕜) {f : α → β} (hf : integrable f μ) : integrable (c • f) μ := ⟨hf.ae_measurable.const_smul c, hf.has_finite_integral.smul c⟩ lemma integrable_smul_iff [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) μ ↔ integrable f μ := and_congr (ae_measurable_const_smul_iff hc) (has_finite_integral_smul_iff hc f) lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, c * f x) μ := integrable.smul c h lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x * c) μ := by simp_rw [mul_comm, h.const_mul _] end normed_space section normed_space_over_complete_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : integrable (λ x, f x • c) μ ↔ integrable f μ := begin simp_rw [integrable, ae_measurable_smul_const hc, and.congr_right_iff, has_finite_integral, nnnorm_smul, ennreal.coe_mul], intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff], have : ∀ x : ennreal, x = 0 → x < ⊤ := by simp, simp [hc, or_iff_left_of_imp (this _)] end end normed_space_over_complete_field variables [second_countable_topology β] /-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/ namespace ae_eq_fun section variable [opens_measurable_space β] /-- A class of almost everywhere equal functions is `integrable` if it has a finite distance to the origin. It means the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ[μ] β) : Prop := f ∈ ball (0 : α →ₘ[μ] β) ⊤ lemma integrable_mk {f : α → β} (hf : ae_measurable f μ ) : (integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm, has_finite_integral, hf] lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f := by rw [← integrable_mk, mk_coe_fn] lemma integrable_zero : integrable (0 : α →ₘ[μ] β) := mem_ball_self coe_lt_top end section variable [borel_space β] lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) := begin refine induction_on₂ f g (λ f hf g hg hfi hgi, _), simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢, exact hfi.add hgi end lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) : integrable (f - g) := hf.add hg.neg protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ[μ] β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _ end normed_space end end ae_eq_fun /-! ### The `L¹` space of functions -/ variables (α β) /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 [opens_measurable_space β] (μ : measure α) : Type* := {f : α →ₘ[μ] β // f.integrable} notation α ` →₁[`:25 μ `] ` β := l1 α β μ variables {α β} namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup section variable [opens_measurable_space β] instance : has_coe (α →₁[μ] β) (α →ₘ[μ] β) := coe_subtype instance : has_coe_to_fun (α →₁[μ] β) := ⟨λ f, α → β, λ f, ⇑(f : α →ₘ[μ] β)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁[μ] β) : ⇑(f : α →ₘ[μ] β) = f := rfl protected lemma eq {f g : α →₁[μ] β} : (f : α →ₘ[μ] β) = (g : α →ₘ[μ] β) → f = g := subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁[μ] β} : (f : α →ₘ[μ] β) = (g : α →ₘ[μ] β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁[μ] β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁[μ] β) := metric_space_emetric_ball 0 ⊤ end variable [borel_space β] instance : add_comm_group (α →₁[μ] β) := subtype.add_comm_group instance : inhabited (α →₁[μ] β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁[μ] β) : α →ₘ[μ] β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁[μ] β) : ((f + g : α →₁[μ] β) : α →ₘ[μ] β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁[μ] β) : ((-f : α →₁[μ] β) : α →ₘ[μ] β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁[μ] β) : ((f - g : α →₁[μ] β) : α →ₘ[μ] β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁[μ] β) : edist f g = edist (f : α →ₘ[μ] β) (g : α →ₘ[μ] β) := rfl lemma dist_eq (f g : α →₁[μ] β) : dist f g = ennreal.to_real (edist (f : α →ₘ[μ] β) (g : α →ₘ[μ] β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁[μ] β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] β) 0) := rfl instance : normed_group (α →₁[μ] β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_add_right } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁[μ] β) := ⟨λ x f, ⟨x • (f : α →ₘ[μ] β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁[μ] β) : ((c • f : α →₁[μ] β) : α →ₘ[μ] β) = c • (f : α →ₘ[μ] β) := rfl instance : semimodule 𝕜 (α →₁[μ] β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : normed_space 𝕜 (α →₁[μ] β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) ≤ ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of an integrable function `f`. -/ def of_fun (f : α → β) (hf : integrable f μ) : (α →₁[μ] β) := ⟨mk f hf.ae_measurable, by { rw integrable_mk, exact hf }⟩ @[simp] lemma of_fun_eq_mk (f : α → β) (hf : integrable f μ) : (of_fun f hf : α →ₘ[μ] β) = mk f hf.ae_measurable := rfl lemma of_fun_eq_of_fun (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun f hf = of_fun g hg ↔ f =ᵐ[μ] g := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λ _, (0 : β)) (integrable_zero α β μ) = 0 := rfl lemma of_fun_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun (f + g) (hf.add hg) = of_fun f hf + of_fun g hg := rfl lemma of_fun_neg (f : α → β) (hf : integrable f μ) : of_fun (- f) (integrable.neg hf) = - of_fun f hf := rfl lemma of_fun_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) : of_fun (f - g) (hf.sub hg) = of_fun f hf - of_fun g hg := by simp only [sub_eq_add_neg, of_fun_add _ _ hf hg.neg, of_fun_neg] lemma norm_of_fun (f : α → β) (hf : integrable f μ) : ∥ of_fun f hf ∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hf : integrable f μ) : ∥ of_fun f hf ∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) : of_fun (λa, k • f a) (hf.smul k) = k • of_fun f hf := rfl end of_fun section to_fun protected lemma measurable (f : α →₁[μ] β) : measurable f := f.1.measurable protected lemma ae_measurable (f : α →₁[μ] β) : ae_measurable f μ := f.1.ae_measurable lemma measurable_norm (f : α →₁[μ] β) : measurable (λ a, ∥f a∥) := f.measurable.norm protected lemma integrable (f : α →₁[μ] β) : integrable ⇑f μ := integrable_coe_fn.2 f.2 protected lemma has_finite_integral (f : α →₁[μ] β) : has_finite_integral ⇑f μ := f.integrable.has_finite_integral lemma integrable_norm (f : α →₁[μ] β) : integrable (λ a, ∥f a∥) μ := (integrable_norm_iff f.ae_measurable).mpr f.integrable lemma of_fun_to_fun (f : α →₁[μ] β) : of_fun f f.integrable = f := subtype.ext (f : α →ₘ[μ] β).mk_coe_fn lemma mk_to_fun (f : α →₁[μ] β) : (mk f f.ae_measurable : α →ₘ[μ] β) = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hf : integrable f μ) : ⇑(of_fun f hf : α →₁[μ] β) =ᵐ[μ] f := coe_fn_mk f hf.ae_measurable variables (α β) lemma zero_to_fun : ⇑(0 : α →₁[μ] β) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {α β} lemma add_to_fun (f g : α →₁[μ] β) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma neg_to_fun (f : α →₁[μ] β) : ⇑(-f) =ᵐ[μ] -⇑f := ae_eq_fun.coe_fn_neg _ lemma sub_to_fun (f g : α →₁[μ] β) : ⇑(f - g) =ᵐ[μ] ⇑f - ⇑g := ae_eq_fun.coe_fn_sub _ _ lemma dist_to_fun (f g : α →₁[μ] β) : dist f g = ennreal.to_real (∫⁻ x, edist (f x) (g x) ∂μ) := by { simp only [← coe_coe, dist_eq, edist_eq_coe] } lemma norm_eq_nnnorm_to_fun (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f a) ∂μ) := by { rw [← coe_coe, lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_eq_coe], refl } lemma norm_eq_norm_to_fun (f : α →₁[μ] β) : ∥f∥ = ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁[μ] β) : (∫⁻ a, edist (f a) (g a) ∂μ) < ⊤ := lintegral_edist_lt_top f.integrable g.integrable variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁[μ] β) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ lemma norm_eq_lintegral (f : α →₁[μ] β) : ∥f∥ = (∫⁻ x, (nnnorm (f x) : ennreal) ∂μ).to_real := by simp [l1.norm_eq, ae_eq_fun.edist_zero_eq_coe, ← edist_eq_coe_nnnorm] /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) : ∥f - g∥ = (∫⁻ x, (nnnorm (f x - g x) : ennreal) ∂μ).to_real := begin simp_rw [l1.norm_eq, ae_eq_fun.edist_zero_eq_coe, ← edist_eq_coe_nnnorm], rw lintegral_congr_ae, refine (ae_eq_fun.coe_fn_sub (f : α →ₘ[μ] β) g).mp _, apply eventually_of_forall, intros x hx, simp [hx] end lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) : ennreal.of_real ∥f∥ = ∫⁻ x, (nnnorm (f x) : ennreal) ∂μ := by { rw [norm_eq_lintegral, ennreal.of_real_to_real], rw [← ennreal.lt_top_iff_ne_top], exact f.has_finite_integral } /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) : ennreal.of_real ∥f - g∥ = ∫⁻ x, (nnnorm (f x - g x) : ennreal) ∂μ := begin simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm], apply lintegral_congr_ae, refine (ae_eq_fun.coe_fn_sub (f : α →ₘ[μ] β) g).mp _, apply eventually_of_forall, intros x hx, simp only [l1.coe_coe, pi.sub_apply] at hx, simp_rw [← hx, ← l1.coe_sub, l1.coe_coe] end end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁[μ] ℝ) : α →₁[μ] ℝ := ⟨ae_eq_fun.pos_part f, begin rw [← ae_eq_fun.integrable_coe_fn], exact f.integrable.max_zero.congr (coe_fn_pos_part _).symm, end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁[μ] ℝ) : α →₁[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁[μ] ℝ) : (f.pos_part : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁[μ] ℝ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma neg_part_to_fun_eq_max (f : α →₁[μ] ℝ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma neg_part_to_fun_eq_min (f : α →₁[μ] ℝ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (neg_part_to_fun_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma norm_le_norm_of_ae_le {f g : α →₁[μ] β} (h : ∀ᵐ a ∂μ, ∥f a∥ ≤ ∥g a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_mono_ae, exact h.mono (λ a h, of_real_le_of_real h) }, { rw [← lt_top_iff_ne_top, ← has_finite_integral_iff_norm], exact f.has_finite_integral }, { rw [← lt_top_iff_ne_top, ← has_finite_integral_iff_norm], exact g.has_finite_integral } end lemma continuous_pos_part : continuous $ λf : α →₁[μ] ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄, pi.sub_apply], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁[μ] ℝ, neg_part f := have eq : (λf : α →₁[μ] ℝ, neg_part f) = (λf : α →₁[μ] ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory open measure_theory lemma integrable_zero_measure [measurable_space β] {f : α → β} : integrable f 0 := begin apply (integrable_zero _ _ _).congr, change (0 : measure α) {x | 0 ≠ f x} = 0, refl, end
46349426a21e53643d0338c50f0245dd5eaff736
fef48cac17c73db8662678da38fd75888db97560
/src/point1.lean
9acb1faa464ab474c2062cfbd903d8e1b9fff025
[]
no_license
kbuzzard/lean-squares-in-fibonacci
6c0d924f799d6751e19798bb2530ee602ec7087e
8cea20e5ce88ab7d17b020932d84d316532a84a8
refs/heads/master
1,584,524,504,815
1,582,387,156,000
1,582,387,156,000
134,576,655
3
1
null
1,541,538,497,000
1,527,083,406,000
Lean
UTF-8
Lean
false
false
6,358
lean
import data.int.modeq import data.nat.modeq import data.nat.prime import data.nat.gcd import algebra.group_power import data.zmod.quadratic_reciprocity -- Su, with a lot of help from Kenny, Chris open nat --#check @zmodp.fermat_little -- zmodp.fermat_little : ∀ {p : ℕ} (hp : prime p) {a : zmodp p hp}, a ≠ 0 → a ^ (p - 1) = 1 theorem Ferlit (a p : ℕ) : nat.prime p → (gcd a ↑p) = 1 → a ^ (p - 1) ≡ 1 [ZMOD p] := sorry -- Chris has done this already! It's in the Xena library, apparently. theorem pow_mod (a b c : ℤ) (n : ℕ) : a ≡ b [ZMOD c] → (a ^ n) ≡ (b ^ n) [ZMOD c] := begin induction n, intro a1, simp, intro a2, have q := n_ih a2, exact int.modeq.modeq_mul a2 q, end theorem pow_neg_one (k : ℕ) (p : ℕ) : nat.prime p → p > 2 → ¬ (2 ∣ k) → (-1) ^ k ≡ - 1 [ZMOD p] := begin intros a b, apply nat.strong_induction_on k, intros a1 a2 a3, cases a1, exact absurd a3 dec_trivial, cases a1, refl, have a4 : ¬2 ∣ a1, intro, apply a3, have a5 : succ (succ a1) = a1 + 2, by simp, rw a5, have a6 : 2 ∣ 2 := by simp, exact dvd_add a_1 a6, have a5 : succ (succ a1) = a1 + 2, by simp, rw a5, have : 0 < 2 , from dec_trivial, have this1 := add_lt_add_left this a1, have this0 : a1 + 0 = a1, by simp, rw this0 at this1, rw ←a5 at this1, have this2 := a2 a1 this1 a4, have this3 := _root_.pow_add (- 1 : ℤ) a1 2, rw this3, have End1 : (- 1 : ℤ) ^ 2 = 1 := dec_trivial, rw End1, simp, exact this2, end theorem one_ne_neg_one_of_odd (p : ℕ) : nat.prime p → p > 2 → ¬ (1 ≡ -1 [ZMOD p]) := sorry -- Can be done immediately with Chris' lemma! theorem nat.pow_pow_mod (x m p : ℕ) : nat.prime p → (↑x ^ 2) ^ m ≡ ↑x ^ (2 * m) [ZMOD p] := begin intro a, have this := pow_mul (↑x : ℤ) 2 m, rw this, end theorem wannaprove (p : ℕ) : nat.prime p → p ≡ 3 [ZMOD 4] → ¬ (∃ (x : ℕ), x ^ 2 + 1 ≡ 0 [ZMOD p]) := begin intros a b c, cases c with x hx, have e : p - 1 ≡ p - 1 [ZMOD p] := rfl, have d := int.modeq.modeq_add e hx, simp at d, have g : 1 + (p - 1 + x ^ 2) = p + x ^ 2 := by rw [← add_assoc, nat.add_sub_cancel' a.pos], have hey1 : p + x ^ 2 = x ^ 2 + p := by simp, have a1 : p + x ^ 2 - x ^ 2 = x ^ 2 + p - x ^ 2 := by simp, suffices this3 : p ∣ ((p + x ^ 2) - x ^ 2), { begin have this1 : ↑p ∣ ↑p := dvd_refl _, have this2 := int.modeq.modeq_zero_iff.2 this1, have this5 : x ^ 2 ≡ x ^ 2 [ZMOD p]:= by refl, have h : p + x ^ 2 ≡ x ^ 2 [ZMOD p] := begin have this11 := int.modeq.modeq_add this5 this2, simp at this11, exact this11, end, have f : gcd x ↑p = 1, { have h1 : gcd x ↑p ∣ x, from gcd_dvd_left _ _, have h2 : gcd x ↑p ∣ ↑p, from gcd_dvd_right _ _, have h3 : gcd x ↑p ∣ x^2 + 1, { have hx1 := hx, generalize H9 : ↑x ^ 2 + 1 = k1, have an1 : ↑x ^ 2 + 1 ≡ k1 [ZMOD p], { rw ←H9, simp, }, have an99 : x ^ 2 + 1 ≡ 0 [MOD ↑p], { have an9 := int.modeq.coe_nat_modeq_iff.1 hx1, simp at an9, have re1 := add_comm 1 (x ^ 2), have re2 := _root_.pow_two x, simp [hx], rw ←re2 at an9, simpa using an9, }, from dvd_trans h2 (nat.modeq.modeq_zero_iff.1 an99), }, have h4 : x ∣ x^2, { have i1 := _root_.pow_two x, have i2 : 1 ≤ 2 := dec_trivial, have i3 := nat.pow_dvd_pow x i2, simp at i3, exact i3, }, have h5 : gcd x ↑p ∣ x^2, from dvd_trans h1 h4, have h6 : gcd x ↑p ∣ 1, from (nat.dvd_add_iff_right h5).2 h3, exact nat.dvd_one.1 h6, }, have ii : p - 1 ≡ p - 1 [ZMOD p] := by refl, have i : x ^ 2 ≡ p - 1 [ZMOD p] := begin have a21 := int.modeq.modeq_add hx this2.symm, simp at a21, have a22 : ↑x ^ 2 + 1 ≡ 1 + ↑x ^ 2 [ZMOD p] := by simp, have s1 : 1 ≡ 1 [ZMOD p] := by refl, have s2 : (p - 1) + 1 ≡ p [ZMOD p] := by simp, have a24 := a21.trans s2.symm, have a24b := a22.trans a24, have a23 := int.modeq.modeq_add_cancel_right s1 a24b, exact a23, end, have Heyya := Ferlit x p a f, have important : p > 2, { by_contradiction cont, have pri := prime.two_le a, have prii := le_of_not_gt cont, have priii := le_antisymm pri prii, have pre := int.modeq.modeq_iff_dvd.1 b, rw ←priii at pre; exact absurd pre dec_trivial, }, have i1 : ∃ m : ℕ, (¬ (2 ∣ m)) ∧ (p - 1 = 2 * m), { have Heynow := nat.mod_add_div p 2, have H1 : ∀ n, n < 2 → n = 0 ∨ n = 1, from dec_trivial, have H2 : p % 2 = 0 ∨ p % 2 = 1, from H1 (p % 2) (nat.mod_lt p dec_trivial), cases H2 with H2 H2, { exfalso, have extra : (2 : ℤ) ∣ (4 : ℤ) := dec_trivial, have wrong := int.modeq.modeq_of_dvd_of_modeq extra b, unfold int.modeq at wrong, have right : (3 : ℤ) % (2 : ℤ) = 1 := dec_trivial, rw right at wrong, have isthis := int.coe_nat_mod p 2, rw H2 at isthis, change (p : ℤ) % ((2 : ℕ) : ℤ) = 1 at wrong, rw wrong at isthis, exact absurd isthis dec_trivial, }, existsi p/2, split, intro nine, have bnew := int.modeq.coe_nat_modeq_iff.1 b, change p ≡ 3 [MOD 4] at bnew, change p % 4 = 3 at bnew, have thing11 := mod_add_div p 4, rw bnew at thing11, {begin rw ← thing11 at nine, change 2 ∣ (3 + (2 * 2) * (p / 4)) / 2 at nine, rw [mul_assoc, nat.add_mul_div_left, ← nat.dvd_add_iff_left] at nine, { exact absurd nine dec_trivial }, { exact dvd_mul_right _ _ }, { exact dec_trivial }, end}, rw H2 at Heynow, generalize H9 : 2 * (p / 2) = k, rw H9 at Heynow, have F2 := nat.sub_eq_of_eq_add Heynow.symm, exact F2, }, cases i1 with m b2, cases b2 with c1 c2, have i2 := int.modeq.modeq_iff_dvd.1 b, cases i2, have j1 : x ^ (p - 1) ≡ - 1 [ZMOD p], {rw c2, have s1 : 1 ≡ 1 [ZMOD p] := by refl, have a123 := int.modeq.modeq_sub s1 hx, simp at a123, have a321 := int.modeq.modeq_neg a123, simp at a321, have a222 : (↑x ^ 2) ^ m ≡ ↑x ^ (2 * m) [ZMOD p], from (@nat.pow_pow_mod x m p a), have a111 := pow_mod (x ^ 2) (-1) p m a321, have g1 := pow_neg_one m p a important c1, have afinal := a111.trans g1, have a2222 := a222.symm, exact a2222.trans afinal}, have Heyya1 := Heyya.symm, have a25 := Heyya1.trans j1, have ans := one_ne_neg_one_of_odd p a important, exact absurd a25 ans, end}, { rw a1, have thes: p + x ^ 2 - x ^ 2 = p := @nat.add_sub_cancel p (x ^ 2), have thees : x ^ 2 + p - x ^ 2 = p + x ^ 2 - x ^ 2 := by simp, rw ←thees at thes, rw thes, }, end
c34dfdb258458d2b34a66b404bd963ad22467277
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Util.lean
cc2e010278d17fbd467a3c3cee89987c008b5c0a
[ "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
6,298
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExprWhere import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.PPGoal namespace Lean.Meta /-- Get the user name of the given metavariable. -/ def _root_.Lean.MVarId.getTag (mvarId : MVarId) : MetaM Name := return (← mvarId.getDecl).userName @[deprecated MVarId.getTag] def getMVarTag (mvarId : MVarId) : MetaM Name := mvarId.getTag def _root_.Lean.MVarId.setTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag } @[deprecated MVarId.setTag] def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do mvarId.setTag tag def appendTag (tag : Name) (suffix : Name) : Name := tag.modifyBase (· ++ suffix.eraseMacroScopes) def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do let tag ← mvarId.getTag mvarId.setTag (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque tag def throwTacticEx (tacticName : Name) (mvarId : MVarId) (msg : MessageData) : MetaM α := if msg.isEmpty then throwError "tactic '{tacticName}' failed\n{mvarId}" else throwError "tactic '{tacticName}' failed, {msg}\n{mvarId}" def throwNestedTacticEx {α} (tacticName : Name) (ex : Exception) : MetaM α := do throwError "tactic '{tacticName}' failed, nested error:\n{ex.toMessageData}" /-- Throw a tactic exception with given tactic name if the given metavariable is assigned. -/ def _root_.Lean.MVarId.checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do if (← mvarId.isAssigned) then throwTacticEx tacticName mvarId "metavariable has already been assigned" @[deprecated MVarId.checkNotAssigned] def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do mvarId.checkNotAssigned tacticName /-- Get the type the given metavariable. -/ def _root_.Lean.MVarId.getType (mvarId : MVarId) : MetaM Expr := return (← mvarId.getDecl).type @[deprecated MVarId.getType] def getMVarType (mvarId : MVarId) : MetaM Expr := mvarId.getType /-- Get the type the given metavariable after instantiating metavariables and reducing to weak head normal form. -/ def _root_.Lean.MVarId.getType' (mvarId : MVarId) : MetaM Expr := do whnf (← instantiateMVars (← mvarId.getType)) @[deprecated MVarId.getType'] def getMVarType' (mvarId : MVarId) : MetaM Expr := do mvarId.getType' builtin_initialize registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def _root_.Lean.MVarId.admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := mvarId.withContext do mvarId.checkNotAssigned `admit let mvarType ← mvarId.getType let val ← mkSorry mvarType synthetic mvarId.assign val @[deprecated MVarId.admit] def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := mvarId.admit synthetic /-- Beta reduce the metavariable type head -/ def _root_.Lean.MVarId.headBetaType (mvarId : MVarId) : MetaM Unit := do mvarId.setType (← mvarId.getType).headBeta @[deprecated MVarId.headBetaType] def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do mvarId.headBetaType /-- Collect nondependent hypotheses that are propositions. -/ def _root_.Lean.MVarId.getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := let removeDeps (e : Expr) (candidates : FVarIdHashSet) : MetaM FVarIdHashSet := do let e ← instantiateMVars e let visit : StateRefT FVarIdHashSet MetaM FVarIdHashSet := do e.forEachWhere Expr.isFVar fun e => modify fun s => s.erase e.fvarId! get visit |>.run' candidates mvarId.withContext do let mut candidates : FVarIdHashSet := {} for localDecl in (← getLCtx) do unless localDecl.isImplementationDetail do candidates ← removeDeps localDecl.type candidates match localDecl.value? with | none => pure () | some value => candidates ← removeDeps value candidates if (← isProp localDecl.type) && !localDecl.hasValue then candidates := candidates.insert localDecl.fvarId candidates ← removeDeps (← mvarId.getType) candidates if candidates.isEmpty then return #[] else let mut result := #[] for localDecl in (← getLCtx) do if candidates.contains localDecl.fvarId then result := result.push localDecl.fvarId return result @[deprecated MVarId.getNondepPropHyps] def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := mvarId.getNondepPropHyps partial def saturate (mvarId : MVarId) (x : MVarId → MetaM (Option (List MVarId))) : MetaM (List MVarId) := do let (_, r) ← go mvarId |>.run #[] return r.toList where go (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := withIncRecDepth do match (← x mvarId) with | none => modify fun s => s.push mvarId | some mvarIds => mvarIds.forM go def exactlyOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM MVarId := match mvarIds with | [mvarId] => return mvarId | _ => throwError msg def ensureAtMostOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM (Option MVarId) := match mvarIds with | [] => return none | [mvarId] => return some mvarId | _ => throwError msg /-- Return all propositions in the local context. -/ def getPropHyps : MetaM (Array FVarId) := do let mut result := #[] for localDecl in (← getLCtx) do unless localDecl.isImplementationDetail do if (← isProp localDecl.type) then result := result.push localDecl.fvarId return result def _root_.Lean.MVarId.inferInstance (mvarId : MVarId) : MetaM Unit := mvarId.withContext do mvarId.checkNotAssigned `infer_instance let synthVal ← synthInstance (← mvarId.getType) unless (← isDefEq (mkMVar mvarId) synthVal) do throwTacticEx `infer_instance mvarId "`infer_instance` tactic failed to assign instance" inductive TacticResultCNM where | closed | noChange | modified (mvarId : MVarId) end Lean.Meta
e1a99fee701c9fd6191c624ca26e7358c96013bc
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/WF.lean
ff9bf3d84f915d24f7c8130d08bd24e68dcb0f92
[ "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
12,063
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SizeOf import Init.Data.Nat.Basic universe u v inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where | intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x noncomputable abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) {a : α} (n : Acc r a) : C a := n.rec m noncomputable abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} {a : α} (n : Acc r a) (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) : C a := n.rec m namespace Acc variable {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y := h₁.recOn (fun _ ac₁ _ h₂ => ac₁ y h₂) h₂ end Acc inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where | intro (h : ∀ a, Acc r a) : WellFounded r class WellFoundedRelation (α : Sort u) where rel : α → α → Prop wf : WellFounded rel namespace WellFounded def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a := wf.rec (fun p => p) a section variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r) theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by induction (apply hwf a) with | intro x₁ _ ih => exact h x₁ ih theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := recursion hwf a h variable {C : α → Sort v} variable (F : ∀ x, (∀ y, r y x → C y) → C x) noncomputable def fixF (x : α) (a : Acc r x) : C x := by induction a with | intro x₁ _ ih => exact F x₁ ih def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by induction acx with | intro x r _ => exact rfl end variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint noncomputable def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := fixF F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (fun y _ => fix hwf F y) := fixFEq F x (apply hwf x) end WellFounded open WellFounded -- Empty relation is well-founded def emptyWf {α : Sort u} : WellFoundedRelation α where rel := emptyRelation wf := by apply WellFounded.intro intro a apply Acc.intro a intro b h cases h -- Subrelation of a well-founded relation is well-founded namespace Subrelation variable {α : Sort u} {r q : α → α → Prop} def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by induction ac with | intro x _ ih => apply Acc.intro intro y h exact ih y (h₁ h) def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q := ⟨fun a => accessible @h₁ (apply h₂ a)⟩ end Subrelation -- The inverse image of a well-founded relation is well-founded namespace InvImage variable {α : Sort u} {β : Sort v} {r : β → β → Prop} private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by induction ac with | intro x acx ih => intro z e apply Acc.intro intro y lt subst x apply ih (f y) lt y rfl def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a := accAux f ac a rfl def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) := ⟨fun a => accessible f (apply h (f a))⟩ end InvImage @[reducible] def invImage (f : α → β) (h : WellFoundedRelation β) : WellFoundedRelation α where rel := InvImage h.rel f wf := InvImage.wf f h.wf -- The transitive closure of a well-founded relation is well-founded namespace TC variable {α : Sort u} {r : α → α → Prop} def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by induction ac with | intro x acx ih => apply Acc.intro x intro y rel induction rel with | base a b rab => exact ih a rab | trans a b c rab _ _ ih₂ => apply Acc.inv (ih₂ acx ih) rab def wf (h : WellFounded r) : WellFounded (TC r) := ⟨fun a => accessible (apply h a)⟩ end TC namespace Nat -- less-than is well-founded def lt_wfRel : WellFoundedRelation Nat where rel := Nat.lt wf := by apply WellFounded.intro intro n induction n with | zero => apply Acc.intro 0 intro _ h apply absurd h (Nat.not_lt_zero _) | succ n ih => apply Acc.intro (Nat.succ n) intro m h have : m = n ∨ m < n := Nat.eq_or_lt_of_le (Nat.le_of_succ_le_succ h) match this with | Or.inl e => subst e; assumption | Or.inr e => exact Acc.inv ih e protected theorem strongInductionOn {motive : Nat → Sort u} (n : Nat) (ind : ∀ n, (∀ m, m < n → motive m) → motive n) : motive n := Nat.lt_wfRel.wf.fix ind n protected theorem caseStrongInductionOn {motive : Nat → Sort u} (a : Nat) (zero : motive 0) (ind : ∀ n, (∀ m, m ≤ n → motive m) → motive (succ n)) : motive a := Nat.strongInductionOn a fun n => match n with | 0 => fun _ => zero | n+1 => fun h₁ => ind n (λ _ h₂ => h₁ _ (lt_succ_of_le h₂)) end Nat def Measure {α : Sort u} : (α → Nat) → α → α → Prop := InvImage (fun a b => a < b) abbrev measure {α : Sort u} (f : α → Nat) : WellFoundedRelation α := invImage f Nat.lt_wfRel def SizeOfRef (α : Sort u) [SizeOf α] : α → α → Prop := Measure sizeOf abbrev sizeOfWFRel {α : Sort u} [SizeOf α] : WellFoundedRelation α := measure sizeOf instance (priority := low) [SizeOf α] : WellFoundedRelation α := sizeOfWFRel namespace Prod open WellFounded section variable {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive Lex : α × β → α × β → Prop where | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂) -- TODO: generalize def Lex.right' {a₁ : Nat} {b₁ : β} (h₁ : a₁ ≤ a₂) (h₂ : rb b₁ b₂) : Prod.Lex Nat.lt rb (a₁, b₁) (a₂, b₂) := match Nat.eq_or_lt_of_le h₁ with | Or.inl h => h ▸ Prod.Lex.right a₁ h₂ | Or.inr h => Prod.Lex.left b₁ _ h -- relational product based on ra and rb inductive RProd : α × β → α × β → Prop where | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : RProd (a₁, b₁) (a₂, b₂) end section variable {α : Type u} {β : Type v} variable {ra : α → α → Prop} {rb : β → β → Prop} def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by induction (aca a) generalizing b with | intro xa _ iha => induction (acb b) with | intro xb _ ihb => apply Acc.intro (xa, xb) intro p lt cases lt with | left _ _ h => apply iha _ h | right _ h => apply ihb _ h -- The lexicographical order of well founded relations is well-founded @[reducible] def lex (ha : WellFoundedRelation α) (hb : WellFoundedRelation β) : WellFoundedRelation (α × β) where rel := Lex ha.rel hb.rel wf := ⟨fun (a, b) => lexAccessible (WellFounded.apply ha.wf) (WellFounded.apply hb.wf) a b⟩ instance [ha : WellFoundedRelation α] [hb : WellFoundedRelation β] : WellFoundedRelation (α × β) := lex ha hb -- relational product is a Subrelation of the Lex def RProdSubLex (a : α × β) (b : α × β) (h : RProd ra rb a b) : Lex ra rb a b := by cases h with | intro h₁ h₂ => exact Lex.left _ _ h₁ -- The relational product of well founded relations is well-founded def rprod (ha : WellFoundedRelation α) (hb : WellFoundedRelation β) : WellFoundedRelation (α × β) where rel := RProd ha.rel hb.rel wf := by apply Subrelation.wf (r := Lex ha.rel hb.rel) (h₂ := (lex ha hb).wf) intro a b h exact RProdSubLex a b h end end Prod namespace PSigma section variable {α : Sort u} {β : α → Sort v} variable (r : α → α → Prop) variable (s : ∀ a, β a → β a → Prop) -- Lexicographical order based on r and s inductive Lex : PSigma β → PSigma β → Prop where | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩ end section variable {α : Sort u} {β : α → Sort v} variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop} def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by induction aca with | intro xa _ iha => induction (WellFounded.apply (acb xa) b) with | intro xb _ ihb => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption -- The lexicographical order of well founded relations is well-founded @[reducible] def lex (ha : WellFoundedRelation α) (hb : (a : α) → WellFoundedRelation (β a)) : WellFoundedRelation (PSigma β) where rel := Lex ha.rel (fun a => hb a |>.rel) wf := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha.wf a) (fun a => hb a |>.wf) b instance [ha : WellFoundedRelation α] [hb : (a : α) → WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) := lex ha hb end section variable {α : Sort u} {β : Sort v} def lexNdep (r : α → α → Prop) (s : β → β → Prop) := Lex r (fun _ => s) def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun _ => hb) b end section variable {α : Sort u} {β : Sort v} -- Reverse lexicographical order based on r and s inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun _ => β) → @PSigma α (fun _ => β) → Prop where | left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩ | right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ end section open WellFounded variable {α : Sort u} {β : Sort v} variable {r : α → α → Prop} {s : β → β → Prop} def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by induction acb with | intro xb _ ihb => intro a induction (aca a) with | intro xa _ iha => apply Acc.intro intro p lt cases lt with | left => apply iha; assumption | right => apply ihb; assumption def revLex (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a end section def SkipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun _ => β) → @PSigma α (fun _ => β) → Prop := RevLex emptyRelation s def skipLeft (α : Type u) {β : Type v} (hb : WellFoundedRelation β) : WellFoundedRelation (PSigma fun _ : α => β) where rel := SkipLeft α hb.rel wf := revLex emptyWf.wf hb.wf def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : SkipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := RevLex.right _ _ h end end PSigma
3ed4a48a6b4c74ea07fba0d4a62e9676ede12c50
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/base_case.lean
11b8c9dbfda88e39002b3325a6e2b62a03c1e21e
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
2,489
lean
import P import initial /-! # The base case of the `group_thingy` tactic ## Main definitions The only definition used outside of this file is `base_case_solver`. `base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning a normalized word in `T` when possible, and `none` otherwise -/ variables {ι : Type} [decidable_eq ι] open multiplicative free_group P semidirect_product /-- `base_case_core` takes a word `l₁` in the free_group as a `list (Σ i : ι, C∞)` and a normalized word with proof `p` as a `P (free_group ι)`. It returns a normalized version `reverse l₁ * p`, reduced modulo `of' r₁ r₂` -/ @[inline] meta def base_case_core (r₁ : ι) (r₂ : C∞) : list (Σ i : ι, C∞) → P (free_group ι) → P (free_group ι) | [] p := p | (i::l₁) ⟨p, ⟨[], _⟩⟩ := if i.1 = r₁ then if to_add r₂ ∣ i.2 then let q := to_add i.2 / to_add r₂ in base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, 1⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, 1⟩) else base_case_core l₁ (inr (of' i.1 i.2) * inl p) | (i::l₁) ⟨p, ⟨j::l₂, _⟩⟩ := if i.1 = r₁ then if j.1 = r₁ then let x := to_add i.2 + to_add j.2 in if to_add r₂ ∣ x then base_case_core l₁ (inl (of' (1 : free_group ι) (of_add (to_add x / to_add r₂))) * inr (of' j.1 j.2⁻¹) * ⟨p, of_list (j::l₂)⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, of_list (j::l₂)⟩) else if to_add r₂ ∣ i.2 then let q := to_add i.2 / to_add r₂ in base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, of_list (j::l₂)⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, of_list (j::l₂)⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, of_list (j::l₂)⟩) /-- `base_case` reduces a word `w` in the `free_group ι` modulo `of' r₁ r₂` -/ @[inline] meta def base_case (r₁ : ι) (r₂ : C∞) (w : free_group ι) : P (free_group ι) := base_case_core r₁ r₂ w.to_list.reverse 1 /-- `base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning a normalized word in `T` when possible, and `none` otherwise -/ @[inline] meta def base_case_solver (T : set ι) [decidable_pred T] (r₁ : ι) (r₂ : C∞) : solver (of' r₁ r₂) T := λ w, let p := base_case r₁ r₂ w in guard (mem_closure_var T p.right) >> return p
a8921bd16b90eb144aef254728b9dc639ec44e80
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/mathlib.lean
4ae5304a62a35af42a8cc17178c97f89a5bda70a
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
3,673
lean
import tactic -- This file contains lemmas about objects in Mathlib, which have not yet landed in Mathlib. -- The following lemmas have all been proven by Yakov Pechersky. -- https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/list.2Eupdate_nth_same/near/229661061 lemma list.update_nth_same {α : Type*} (l : list (option α)) (n : ℕ) : l.update_nth n (l.nth n).join = l := begin ext k, by_cases hk : k = n, { cases h : l.nth n; simp [list.nth_update_nth_eq, hk, h] }, { rw list.nth_update_nth_ne _ l (ne.symm hk) } end -- https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/list.2Eupdate_same/near/228774282 lemma list.update_same {α : Type*} (l : list α) (n : ℕ) (a a' : α) : (l.update_nth n a).update_nth n a' = l.update_nth n a' := begin induction l with hd tl hl generalizing n, { simp [list.update_nth] }, { cases n, { simp [list.update_nth] }, { simp [list.update_nth, hl] } } end -- https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/index_of_erase_lt/near/228527125 @[simp] lemma list.sublist_nil {α : Type*} {l : list α} : l <+ [] ↔ l = [] := begin split, { rintro ⟨⟩, refl }, { rintro rfl, refl } end lemma list.mem_of_mem_sublist {α : Type*} {l l' : list α} {x : α} (h : x ∈ l) (hl : l <+ l') : x ∈ l' := begin induction hl with _ tl hd hl IH tl tl' hd hl IH, simpa using h, exact list.mem_cons_of_mem _ (IH h), { rw [list.mem_cons_iff] at h ⊢, rcases h with h | h, exact or.inl h, exact or.inr (IH h) } end lemma list.index_of_lt_of_sublist {α : Type*} [decidable_eq α] {l l' : list α} {x x' : α} (h : l.index_of x < l.index_of x') (hl : l' <+ l) (hₘ : x ∈ l') (hₘ' : x' ∈ l') (hₙ : l.nodup) : l'.index_of x < l'.index_of x' := begin induction hl with _ tl hd hl IH tl tl' hd hl IH, { simpa using hₘ }, { refine IH _ hₘ hₘ' _, { have hne : ∀ z ∈ hl_l₁, z ≠ hd, { rintro z hz rfl, have : z ∈ tl := list.mem_of_mem_sublist hz hl, simpa [this] using hₙ }, rwa [list.index_of_cons_ne _ (hne _ hₘ), list.index_of_cons_ne _ (hne _ hₘ'), nat.succ_lt_succ_iff] at h }, { rw list.nodup_cons at hₙ, exact hₙ.right } }, { rw list.mem_cons_iff at hₘ hₘ', rw list.nodup_cons at hₙ, rcases hₘ with rfl|hₘ; rcases hₘ' with rfl|hₘ', { simpa using h }, { have hx' : x' ∈ tl' := list.mem_of_mem_sublist hₘ' hl, replace hx' : x' ≠ x := ne_of_mem_of_not_mem hx' hₙ.left, simp [hx'] }, { have hx : x ∈ tl' := list.mem_of_mem_sublist hₘ hl, replace hx : x ≠ x' := ne_of_mem_of_not_mem hx hₙ.left, simpa [hx] using h }, { have hx : x ∈ tl' := list.mem_of_mem_sublist hₘ hl, replace hx : x ≠ hd := ne_of_mem_of_not_mem hx hₙ.left, have hx' : x' ∈ tl' := list.mem_of_mem_sublist hₘ' hl, replace hx' : x' ≠ hd := ne_of_mem_of_not_mem hx' hₙ.left, rw [list.index_of_cons_ne _ hx, list.index_of_cons_ne _ hx', nat.succ_lt_succ_iff] at h ⊢, exact IH h hₘ hₘ' hₙ.right } } end lemma list.index_of_erase_lt {α : Type*} [decidable_eq α] {l : list α} {e x x' : α} (h : l.index_of x < l.index_of x') (hₘ : x ∈ l.erase e) (hₘ' : x' ∈ l.erase e) (hₙ : l.nodup) : (l.erase e).index_of x < (l.erase e).index_of x' := list.index_of_lt_of_sublist h (l.erase_sublist e) hₘ hₘ' hₙ
57fa397a5e503ee4db32b0741cdf4ce7aef09d1d
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/nat/totient.lean
ce069c0f1d9b6c896075b8e90214c7f273099f7b
[ "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
3,586
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 algebra.big_operators open finset open_locale big_operators namespace nat def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat @[simp] theorem totient_zero : φ 0 = 0 := rfl lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _) ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩ lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n := if hn0 : n = 0 then by rw hn0; refl else calc ∑ m in (range n.succ).filter (∣ n), φ m = ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_right_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bind (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bind (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bind.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
cfe572182164e00a9491f4780bda504d283b510e
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/padics/padic_integers.lean
537272890427481a7d2e1b675c70799e9e9983af
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
9,475
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, Mario Carneiro Define the p-adic integers ℤ_p as a subtype of ℚ_p. Construct algebraic structures on ℤ_p. -/ import data.padics.padic_numbers ring_theory.ideals data.int.modeq import tactic.linarith open nat padic metric noncomputable theory local attribute [instance] classical.prop_decidable local attribute [instance, priority 0] nat.cast_coe local attribute [instance, priority 0] int.cast_coe local attribute [instance, priority 0] rat.cast_coe def padic_int (p : ℕ) [p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int variables {p : ℕ} [nat.prime p] def add : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩ def mul : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩ def neg : ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ := ⟨-x, by simpa⟩ instance : ring ℤ_[p] := begin refine { add := add, mul := mul, neg := neg, zero := ⟨0, by simp [zero_le_one]⟩, one := ⟨1, by simp⟩, .. }; {repeat {rintro ⟨_, _⟩}, simp [mul_assoc, left_distrib, right_distrib, add, mul, neg]} end lemma zero_def : ∀ x : ℤ_[p], x = 0 ↔ x.val = 0 | ⟨x, _⟩ := ⟨subtype.mk.inj, λ h, by simp at h; simp only [h]; refl⟩ @[simp] lemma add_def : ∀ (x y : ℤ_[p]), (x+y).val = x.val + y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mul_def : ∀ (x y : ℤ_[p]), (x*y).val = x.val * y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = ↑z := rfl @[simp] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), (↑(z1 + z2) : ℚ_[p]) = ↑z1 + ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), (↑(z1 * z2) : ℚ_[p]) = ↑z1 * ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_neg : ∀ (z1 : ℤ_[p]), (↑(-z1) : ℚ_[p]) = -↑z1 | ⟨_, _⟩ := rfl @[simp] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] lemma coe_one : (↑(1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp] lemma coe_coe : ∀ n : ℕ, (↑(↑n : ℤ_[p]) : ℚ_[p]) = (↑n : ℚ_[p]) | 0 := rfl | (k+1) := by simp [coe_coe] @[simp] lemma coe_zero : (↑(0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl @[simp] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n | 0 := by simp | (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow lemma mk_coe : ∀ (k : ℤ_[p]), (⟨↑k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 end padic_int section instances variables {p : ℕ} [nat.prime p] @[reducible] def padic_norm_z (z : ℤ_[p]) : ℝ := ∥z.val∥ instance : metric_space ℤ_[p] := subtype.metric_space instance : has_norm ℤ_[p] := ⟨padic_norm_z⟩ instance : normed_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _ } instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero, padic_int.zero_def], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_triangle _ _, abv_mul := λ _ _, by unfold norm; simp [padic_norm_z] } protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm] instance : comm_ring ℤ_[p] := { mul_comm := padic_int.pmul_comm, ..padic_int.ring } protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext.1 zero_ne_one protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext.1 h, (mul_eq_zero_iff_eq_zero_or_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := padic_int.zero_ne_one, ..padic_int.comm_ring } end instances namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z] @[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by unfold norm; simp [padic_norm_z] @[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne @[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := norm_one lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm, padic_norm_z] @[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl end padic_norm_z private lemma mul_lt_one {α} [decidable_linear_ordered_comm_ring α] {a b : α} (hbz : 0 < b) (ha : a < 1) (hb : b < 1) : a * b < 1 := suffices a*b < 1*1, by simpa, mul_lt_mul ha (le_of_lt hb) hbz zero_le_one private lemma mul_lt_one_of_le_of_lt {α} [decidable_linear_ordered_comm_ring α] {a b : α} (ha : a ≤ 1) (hbz : 0 ≤ b) (hb : b < 1) : a * b < 1 := if hb' : b = 0 then by simpa [hb'] using zero_lt_one else if ha' : a = 1 then by simpa [ha'] else mul_lt_one (lt_of_le_of_ne hbz (ne.symm hb')) (lt_of_le_of_ne ha ha') hb namespace padic_int variables {p : ℕ} [nat.prime p] local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (padic_norm_z.le_one _) _, have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z), rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_le_of_lt (padic_norm_z.le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff] instance : is_local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩ instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) : ∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) := have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz, have (↑(z2 - z1) : ℚ_[p]) = padic.of_rat p ↑(z2 - z1), by simp, begin rw [norm_sub_rev, ←int.cast_sub, this, padic_norm_e.eq_padic_norm], simpa using padic_norm.le_of_dvd p hdvd end end padic_norm_z
04280fb0bfa09fb48165354b0988d083f4edc697
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/meta/name.lean
93f92173f71bd5c4d1b641a4e77e908bff8201f5
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
2,480
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.ordering init.coe /- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/ inductive name | anonymous : name | mk_string : string → name → name | mk_numeral : unsigned → name → name instance : inhabited name := ⟨name.anonymous⟩ def mk_str_name (n : name) (s : string) : name := name.mk_string s n def mk_num_name (n : name) (v : nat) : name := name.mk_numeral (unsigned.of_nat v) n def mk_simple_name (s : string) : name := mk_str_name name.anonymous s instance string_to_name : has_coe string name := ⟨mk_simple_name⟩ infix ` <.> `:65 := mk_str_name open name def name.get_prefix : name → name | anonymous := anonymous | (mk_string s p) := p | (mk_numeral s p) := p definition name.to_string_with_sep (sep : string) : name → string | anonymous := "[anonymous]" | (mk_string s anonymous) := s | (mk_numeral v anonymous) := to_string v | (mk_string s n) := name.to_string_with_sep n ++ sep ++ s | (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ to_string v private def name.components' : name -> list name | anonymous := [] | (mk_string s n) := mk_string s anonymous :: name.components' n | (mk_numeral v n) := mk_numeral v anonymous :: name.components' n def name.components (n : name) : list name := list.reverse (name.components' n) definition name.to_string : name → string := name.to_string_with_sep "." instance : has_to_string name := ⟨name.to_string⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant name.has_decidable_eq : decidable_eq name /- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/ meta constant name.cmp : name → name → ordering meta constant name.lex_cmp : name → name → ordering meta constant name.append : name → name → name attribute [instance] name.has_decidable_eq meta instance : has_ordering name := ⟨name.cmp⟩ meta instance : has_append name := ⟨name.append⟩ /- (name.append_after n i) return a name of the form n_i -/ meta constant name.append_after : name → nat → name meta def name.is_prefix_of : name → name → bool | p name.anonymous := ff | p n := if p = n then tt else name.is_prefix_of p n^.get_prefix
6b0cb5f8d05106c51086fb86129a38edf39686da
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/multiTargetCasesInductionIssue.lean
a4a067bbd22898de54ba9ac4aabddafb7345dd05
[ "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,648
lean
def Vec (α : Type u) (n : Nat) : Type u := { a : List α // a.length = n } def Vec.nil : Vec α 0 := ⟨[], rfl⟩ def Vec.cons (a : α) (as : Vec α n) : Vec α (n+1) := ⟨a :: as.val, by simp [as.property]⟩ set_option pp.analyze false def Vec.casesOn (motive : (n : Nat) → Vec α n → Sort v) (n : Nat) (as : Vec α n) (nil : motive 0 Vec.nil) (cons : (n : Nat) → (a : α) → (as : Vec α n) → (ih : motive n as) → motive (n+1) (Vec.cons a as)) : motive n as := let rec go (n : Nat) (as : List α) (h : as.length = n) : motive n ⟨as, h⟩ := match n, as, h with | 0, [], _ => nil | n+1, a::as, h => have : as.length = n := by injection h have ih : motive n ⟨as, this⟩ := go n as this cons n a ⟨as, this⟩ ih match as with | ⟨as, h⟩ => go n as h example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by induction n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => trace_state constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => trace_state constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases h₁ : n+2, h₂ : Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n' a' as' ih => trace_state constructor
b101ab6f65563aeada43e584ddd89695fa1f12d6
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/option.lean
5e0e6191f7244a612911efb1d5314f348218bea2
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
7,611
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic data.bool init.data.option.instances tactic.interactive namespace option variables {α : Type*} {β : Type*} instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp theorem injective_some (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl theorem is_none_iff_eq_none {o : option α} : o.is_none ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ instance decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_bool _ is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp) | (some a) := decidable_of_iff (p a) (by simp) instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (by simp) | (some a) := decidable_of_iff (p a) (by simp) /-- inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default α @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b section rel inductive rel (r : α → β → Prop) : option α → option β → Prop | some {a b} : r a b → rel (some a) (some b) | none {} : rel none none end rel end option
a6fa6622eb88b1ca95a87ab601323ae9aea62f18
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/analysis/calculus/deriv.lean
128d48fffd46bd1c6d174e84f0cf10b1e5ba7e93
[ "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,386
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ principal (-{x})) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (-{x})) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall _ $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_prod is_open_ne is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, nat.sub_zero, nat.cast_one] }, { simp only [nat.iterate_succ', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = ((finset.range k).prod (λ i, m - i):ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [nat.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], apply deriv_congr_of_mem_nhds, apply eventually.mono _ @ihk, exact mem_nhds_sets is_open_ne hx } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x) end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x) /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x), refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
5ad96afbf9aca5a4f65e6be5a335f3075aa7dda6
a959f48a0621edea632487cf2130bbf70d301e05
/src/norms.lean
4724f2d98eaa9cb2861d9ea255a5b430e0bcb9b6
[]
no_license
cipher1024/lean-differential-topology
cf441b36af9fdb022f10afff6a2fdc5aa4afa379
1938b0a5d9e89faff89dac4bc51598698cae6dbb
refs/heads/master
1,619,477,568,536
1,527,790,354,000
1,527,790,354,000
124,159,851
0
0
null
1,520,385,485,000
1,520,385,485,000
null
UTF-8
Lean
false
false
11,064
lean
import analysis.real import algebra.linear_algebra.prod_module import squeeze noncomputable theory local notation f `→_{`:50 a `}`:0 b := filter.tendsto f (nhds a) (nhds b) class normed_group (α : Type*) extends add_comm_group α, metric_space α := (norm : α → ℝ) (dist_eq : ∀ x y, dist x y = norm (x - y)) def norm {G : Type*} [normed_group G] : G → ℝ := normed_group.norm notation `∥` e `∥` := norm e section normed_group variables {G : Type*} [normed_group G] {H : Type*} [normed_group H] lemma norm_dist' { g h : G} : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma norm_dist { g : G} : dist g 0 = ∥g∥ := by { rw[norm_dist'], simp } lemma norm_triangle (g h : G) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[norm_dist'] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[norm_dist'] @[simp] lemma norm_nonneg {g : G} : 0 ≤ ∥g∥ := by { rw[←norm_dist], exact dist_nonneg } lemma norm_zero_iff_zero {g : G} : ∥g∥ = 0 ↔ g = 0 := by { rw[←norm_dist], exact dist_eq_zero } @[simp] lemma zero_norm_zero : ∥(0:G)∥ = 0 := norm_zero_iff_zero.2 (by simp) lemma norm_pos_iff {g : G} : ∥ g ∥ > 0 ↔ g ≠ 0 := begin split ; intro h ; rw[←norm_dist] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff {g : G} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←norm_dist], exact dist_le_zero } @[simp] lemma norm_neg {g : G} : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : norm_dist'.symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : norm_dist' ... = ∥g∥ : by simp lemma norm_triangle' (g h : G) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := begin have ng := calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _, replace ng := sub_right_le_of_le_add ng, have nh := calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [show ∥-(g - h)∥ = ∥g-h∥, from norm_neg] }, replace nh := sub_right_le_of_le_add nh, replace nh : -(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa using nh, replace nh : -∥g - h∥ ≤ ∥g∥ - ∥h∥ := by simpa using neg_le_neg nh, exact abs_le.2 ⟨nh, ng⟩ end instance prod.normed_group {F : Type*} [normed_group F] : normed_group (G × F) := { norm := λ x, max ∥x.1∥ ∥x.2∥, dist_eq := assume x y, by { simp, repeat {rw norm_dist'}, simp }, ..prod.metric_space_max, ..prod.add_comm_group } lemma norm_proj1_le (x : G × H) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) ( ∥x.snd∥) := rfl, rw this, simp[le_max_left], end lemma norm_proj2_le (x : G × H) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) ( ∥x.snd∥) := rfl, rw this, simp[le_max_right], end lemma tendsto_iff_norm_tendsto_zero {f : G → H} {a : G} {b : H} : (f →_{a} b) ↔ ((λ e, ∥ f e - b ∥) →_{a} 0) := begin simp only [norm_dist'.symm], exact tendsto_iff_dist_tendsto_zero end lemma lim_norm (x: G) : ((λ g, ∥g-x∥) : G → ℝ) →_{x} 0 := begin apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_tendsto.1, simp[show (λ e : G , e) = id, from rfl, continuous_id] end lemma lim_norm_zero : ((λ g, ∥g∥) : G → ℝ) →_{0} 0 := by simpa using lim_norm (0:G) lemma norm_continuous {G : Type*} [normed_group G]: continuous ((λ g, ∥g∥) : G → ℝ) := begin apply continuous_iff_tendsto.2, intro x, have : (λ (g : G), dist ∥g∥ ∥x∥) →_{x} 0 := squeeze_zero (λ g, dist ∥g∥ ∥x∥) _ x (λ t, abs_nonneg _) (λ t, norm_triangle' _ _) (lim_norm x), exact tendsto_iff_dist_tendsto_zero.2 this end instance normed_top_monoid : topological_add_monoid G := ⟨begin apply continuous_iff_tendsto.2 _, intro x, apply tendsto_iff_norm_tendsto_zero.2, simp, have ineq := λ e: G × G, calc ∥e.fst + (e.snd + (-x.fst + -x.snd))∥ = ∥(e.fst-x.fst) + (e.snd - x.snd)∥ : by simp ... ≤ ∥e.fst - x.fst∥ + ∥ e.snd - x.snd ∥ : norm_triangle (e.fst-x.fst) (e.snd - x.snd), apply squeeze_zero _ _ x (by simp) ineq, have ineq1 : ∀ e : G × G, ∥ e.fst - x.fst∥ ≤ ∥e - x∥ := assume e, norm_proj1_le (e-x), have lim1 : (λ e : G × G, ∥ e.fst - x.fst∥) →_{x} 0 := squeeze_zero _ _ x (by simp) ineq1 _, clear ineq1, have ineq2 : ∀ e : G × G, ∥ e.snd - x.snd∥ ≤ ∥e - x∥ := assume e, norm_proj2_le (e-x), have lim2 : (λ e : G × G, ∥ e.snd - x.snd∥) →_{x} 0 := squeeze_zero _ _ x (by simp) ineq2 _, clear ineq2, have := tendsto_add lim1 lim2, simpa using this, exact lim_norm x, exact lim_norm x, end⟩ instance normed_top_group : topological_add_group G := { continuous_neg := begin apply continuous_iff_tendsto.2, intro x, apply tendsto_iff_norm_tendsto_zero.2, simp, have neg := λ (e : G), calc ∥ x + -e∥ = ∥ -(e -x)∥ : by simp ... = ∥e - x∥ : norm_neg, conv in _ {rw [neg]}, have lim_negx : (λ (e : G), -x )→_{x} -x:= tendsto_const_nhds, have lim_e : (λ (e : G), e )→_{x} x := continuous_iff_tendsto.1 continuous_id x, have := tendsto_add lim_negx lim_e, simp at this, simpa using filter.tendsto.comp this lim_norm_zero end, ..normed_top_monoid } end normed_group section normed_ring class normed_ring (α : Type*) extends ring α, metric_space α := (norm : α → ℝ) (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) variables {α : Type*} {β : Type*} instance normed_ring.to_normed_group [H : normed_ring α] : normed_group α := { ..H } lemma norm_mul {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ instance prod.ring [ring α] [ring β] : ring (α × β) := { left_distrib := assume x y z, calc x*(y+z) = (x.1, x.2) * (y.1 + z.1, y.2 + z.2) : rfl ... = (x.1*(y.1 + z.1), x.2*(y.2 + z.2)) : rfl ... = (x.1*y.1 + x.1*z.1, x.2*y.2 + x.2*z.2) : by simp[left_distrib], right_distrib := assume x y z, calc (x+y)*z = (x.1 + y.1, x.2 + y.2)*(z.1, z.2) : rfl ... = ((x.1 + y.1)*z.1, (x.2 + y.2)*z.2) : rfl ... = (x.1*z.1 + y.1*z.1, x.2*z.2 + y.2*z.2) : by simp[right_distrib], ..prod.monoid, ..prod.add_comm_group} instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul (x.1) (y.1)) (norm_mul (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.ring, ..prod.normed_group } end normed_ring section normed_field variables {α : Type*} class normed_field (α : Type*) extends discrete_field α, metric_space α := (norm : α → ℝ) (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) instance normed_field.to_normed_ring [H : normed_field α] : normed_ring α := { norm_mul := by finish[H.norm_mul], ..H } instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul} end normed_field section normed_space class normed_space (α : out_param $ Type*) (β : Type*) [out_param $ normed_field α] extends vector_space α β, metric_space β := (norm : β → ℝ) (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_smul : ∀ a b, norm (a • b) = normed_field.norm a * norm b) variables {α : Type*} [normed_field α] {β : Type*} instance normed_space.to_normed_group [H : normed_space α β] : normed_group β := by refine { add := (+), dist_eq := normed_space.dist_eq, zero := 0, neg := λ x, -x, ..H, .. }; simp variable [normed_space α β] lemma norm_smul (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul _ _ variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : E → α} { g : E → F} {e : E} {s : α} {b : F} : (f →_{e} s) → (g →_{e} b) → ((λ e, (f e) • (g e)) →_{e} s • b) := begin intros limf limg, apply tendsto_iff_norm_tendsto_zero.2, have ineq := λ x : E, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg }, { exact ineq }, { clear ineq, have limf': (λ (x : E), ∥f x - s∥)→_{e}0 := tendsto_iff_norm_tendsto_zero.1 limf, have limg' := filter.tendsto.comp limg (continuous_iff_tendsto.1 norm_continuous _), have limg'' : (λ (x : E), ∥g x∥)→_{e} ∥b∥, simp[limg'], clear limg', have lim1 := tendsto_mul limf' limg'', simp at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul tendsto_const_nhds limg3, swap, exact ∥s∥, simp at lim2, have := tendsto_add lim1 lim2, rw [show (0:ℝ) + 0 = 0, by simp] at this, exact this } end /- Do we want the following? I have difficulties with instances to set it up class topological_vector_space (E : Type*) [topological_space E] [vector_space α E] extends topological_add_group E : Prop := (continuous_smul : continuous (λ x : α×E, x.1• x.2)) -/ instance product_normed_space : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, exact calc ∥s • (x₁, x₂)∥ = ∥ (s • x₁, s• x₂)∥ : rfl ... = max (∥s • x₁∥) (∥ s• x₂∥) : rfl ... = max (∥s∥ * ∥x₁∥) (∥s∥ * ∥x₂∥) : by simp[norm_smul s x₁, norm_smul s x₂] ... = ∥s∥ * max (∥x₁∥) (∥x₂∥) : by simp[mul_max_of_nonneg] end, add_smul := by simp[add_smul], -- I have no idea why by simp[smul_add] is not enough for the next goal smul_add := assume r x y, show (r•(x+y).fst, r•(x+y).snd) = (r•x.fst+r•y.fst, r•x.snd+r•y.snd), by simp[smul_add], ..prod.normed_group, ..prod.vector_space } end normed_space
e27358f12faede80ace538016c162f73a089ecdc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/quadratic_form/dual.lean
68ed89fab74cbc4eb197fb93ee1c05566806e976
[ "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,376
lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.quadratic_form.isometry import linear_algebra.quadratic_form.prod /-! # Quadratic form structures related to `module.dual` ## Main definitions * `bilin_form.dual_prod R M`, the bilinear form on `(f, x) : module.dual R M × M` defined as `f x`. * `quadratic_form.dual_prod R M`, the quadratic form on `(f, x) : module.dual R M × M` defined as `f x`. * `quadratic_form.to_dual_prod : M × M →ₗ[R] module.dual R M × M` a form-preserving map from `(Q.prod $ -Q)` to `quadratic_form.dual_prod R M`. Note that we do not have the morphism version of `quadratic_form.isometry`, so for now this is stated without full bundling. -/ variables (R M N : Type*) namespace bilin_form section semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] /-- The symmetric bilinear form on `module.dual R M × M` defined as `B (f, x) (g, y) = f y + g x`. -/ @[simps] def dual_prod : bilin_form R (module.dual R M × M) := linear_map.to_bilin $ (linear_map.applyₗ.comp (linear_map.snd R (module.dual R M) M)).compl₂ (linear_map.fst R (module.dual R M) M) + ((linear_map.applyₗ.comp (linear_map.snd R (module.dual R M) M)).compl₂ (linear_map.fst R (module.dual R M) M)).flip lemma is_symm_dual_prod : (dual_prod R M).is_symm := λ x y, add_comm _ _ end semiring section ring variables [comm_ring R] [add_comm_group M] [module R M] lemma nondenerate_dual_prod : (dual_prod R M).nondegenerate ↔ function.injective (module.dual.eval R M) := begin classical, rw nondegenerate_iff_ker_eq_bot, rw linear_map.ker_eq_bot, let e := linear_equiv.prod_comm R _ _ ≪≫ₗ module.dual_prod_dual_equiv_dual R (module.dual R M) M, let h_d := e.symm.to_linear_map.comp (dual_prod R M).to_lin, refine (function.injective.of_comp_iff e.symm.injective (dual_prod R M).to_lin).symm.trans _, rw [←linear_equiv.coe_to_linear_map, ←linear_map.coe_comp], change function.injective h_d ↔ _, have : h_d = linear_map.prod_map (linear_map.id) (module.dual.eval R M), { refine linear_map.ext (λ x, prod.ext _ _), { ext, dsimp [h_d, module.dual.eval, linear_equiv.prod_comm], simp }, { ext, dsimp [h_d, module.dual.eval, linear_equiv.prod_comm], simp } }, rw [this, linear_map.coe_prod_map], refine prod.map_injective.trans _, exact and_iff_right function.injective_id, end end ring end bilin_form namespace quadratic_form section semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] /-- The quadratic form on `module.dual R M × M` defined as `Q (f, x) = f x`. -/ @[simps] def dual_prod : quadratic_form R (module.dual R M × M) := { to_fun := λ p, p.1 p.2, to_fun_smul := λ a p, by rw [prod.smul_fst, prod.smul_snd, linear_map.smul_apply, linear_map.map_smul, smul_eq_mul, smul_eq_mul, mul_assoc], exists_companion' := ⟨bilin_form.dual_prod R M, λ p q, begin rw [bilin_form.dual_prod_apply, prod.fst_add, prod.snd_add, linear_map.add_apply, map_add, map_add, add_right_comm _ (q.1 q.2), add_comm (q.1 p.2) (p.1 q.2), ←add_assoc, ←add_assoc], end⟩ } @[simp] lemma _root_.bilin_form.dual_prod.to_quadratic_form : (bilin_form.dual_prod R M).to_quadratic_form = 2 • dual_prod R M := ext $ λ a, (two_nsmul _).symm variables {R M N} /-- Any module isomorphism induces a quadratic isomorphism between the corresponding `dual_prod.` -/ @[simps] def dual_prod_isometry (f : M ≃ₗ[R] N) : (dual_prod R M).isometry (dual_prod R N) := { to_linear_equiv := f.dual_map.symm.prod f, map_app' := λ x, fun_like.congr_arg x.fst $ f.symm_apply_apply _ } /-- `quadratic_form.dual_prod` commutes (isometrically) with `quadratic_form.prod`. -/ @[simps] def dual_prod_prod_isometry : (dual_prod R (M × N)).isometry ((dual_prod R M).prod (dual_prod R N)) := { to_linear_equiv := ((module.dual_prod_dual_equiv_dual R M N).symm.prod (linear_equiv.refl R (M × N))) ≪≫ₗ linear_equiv.prod_prod_prod_comm R _ _ M N, map_app' := λ m, (m.fst.map_add _ _).symm.trans $ fun_like.congr_arg m.fst $ prod.ext (add_zero _) (zero_add _) } end semiring section ring variables [comm_ring R] [add_comm_group M] [module R M] variables {R M} /-- The isometry sending `(Q.prod $ -Q)` to `(quadratic_form.dual_prod R M)`. This is `σ` from Proposition 4.8, page 84 of [*Hermitian K-Theory and Geometric Applications*][hyman1973]; though we swap the order of the pairs. -/ @[simps] def to_dual_prod (Q : quadratic_form R M) [invertible (2 : R)] : M × M →ₗ[R] module.dual R M × M := linear_map.prod (Q.associated.to_lin.comp (linear_map.fst _ _ _) + Q.associated.to_lin.comp (linear_map.snd _ _ _)) ((linear_map.fst _ _ _ - linear_map.snd _ _ _)) lemma to_dual_prod_isometry [invertible (2 : R)] (Q : quadratic_form R M) (x : M × M) : quadratic_form.dual_prod R M (to_dual_prod Q x) = (Q.prod $ -Q) x := begin dsimp only [to_dual_prod, associated, associated_hom], dsimp, simp [polar_comm _ x.1 x.2, ←sub_add, mul_sub, sub_mul, smul_sub, submonoid.smul_def, ←sub_eq_add_neg (Q x.1) (Q x.2)], end -- TODO: show that `to_dual_prod` is an equivalence end ring end quadratic_form
e9b5f1bcd8f3820f875a1e95a2795963cd0787b4
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/skeleton.lean
d90d0e99939f9edef3cc4761bbd6f6d9c82cbda1
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,789
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.monoidal.functor import category_theory.monoidal.braided import category_theory.monoidal.transport import category_theory.skeletal /-! # The monoid on the skeleton of a monoidal category The skeleton of a monoidal category is a monoid. -/ namespace category_theory open monoidal_category universes v u variables {C : Type u} [category.{v} C] [monoidal_category C] /-- If `C` is monoidal and skeletal, it is a monoid. See note [reducible non-instances]. -/ @[reducible] def monoid_of_skeletal_monoidal (hC : skeletal C) : monoid C := { mul := λ X Y, (X ⊗ Y : C), one := (𝟙_ C : C), one_mul := λ X, hC ⟨λ_ X⟩, mul_one := λ X, hC ⟨ρ_ X⟩, mul_assoc := λ X Y Z, hC ⟨α_ X Y Z⟩ } /-- If `C` is braided and skeletal, it is a commutative monoid. -/ def comm_monoid_of_skeletal_braided [braided_category C] (hC : skeletal C) : comm_monoid C := { mul_comm := λ X Y, hC ⟨β_ X Y⟩, ..monoid_of_skeletal_monoidal hC } /-- The skeleton of a monoidal category has a monoidal structure itself, induced by the equivalence. -/ noncomputable instance : monoidal_category (skeleton C) := monoidal.transport (skeleton_equivalence C).symm /-- The skeleton of a monoidal category can be viewed as a monoid, where the multiplication is given by the tensor product, and satisfies the monoid axioms since it is a skeleton. -/ noncomputable instance : monoid (skeleton C) := monoid_of_skeletal_monoidal (skeleton_is_skeleton _).skel -- TODO: Transfer the braided structure to the skeleton of C along the equivalence, and show that -- the skeleton is a commutative monoid. end category_theory
00620e3b6029629741e8b4004a785adc41cc38b7
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/tactic/core.lean
0389f5154f409cb5ddf322213b5771c3e6cceeb7
[ "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
96,281
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import logic.function.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.binder_matching import tactic.lean_core_docs import tactic.interactive_expr import tactic.project_dir import system.io universe u attribute [derive [has_reflect, decidable_eq]] tactic.transparency -- Rather than import order.lexicographic here, we can get away with defining the order by hand. instance : has_lt pos := { lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column } namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a proof by reflexivity. -/ meta def or_refl_conv (tac : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := tac e <|> refl_conv e /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Constructs a list of `tactic expr` given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list. We need to return a list of `tactic expr`, rather than just `expr`, because these expressions will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. -/ meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr)) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n), -- We reverse the list of lemmas marked with an attribute, -- on the assumption that lemmas proved earlier are more often applicable -- than lemmas proved later. This is a performance optimization. build_list_expr_for_apply (m.reverse ++ t)) <|> return ((i_to_expr_for_apply h) :: tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit := do l ← lock_tactic_state $ build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorrry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. 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. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open _root_.lean open _root_.lean.parser open _root_.interactive _root_.interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean _root_.interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of any project. Requires as argument any declaration name `n` in that project, and `k`, the number of characters in the path of the file where `n` is declared not part of the `src` directory. Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`. Note: does not work in the file where `n` is declared. -/ meta def get_project_dir (n : name) (k : ℕ) : tactic string := do e ← get_env, s ← e.decl_olean n <|> fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.", return $ s.popn_back k /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := get_project_dir `mathlib_dir_locator 23 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name (default _) %%persistent) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
5ec5004db75036f2677f7ff93b2a8bbdca338e22
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/ring_power.lean
b0febfaf18869484f427a3ff829883cdaa45334a
[ "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
6,252
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Properties of the power operation in various structures, including ordered rings and fields. -/ import .group_power .ordered_field open nat variable {A : Type} section semiring variable [s : semiring A] include s definition semiring_has_pow_nat [instance] : has_pow_nat A := monoid_has_pow_nat theorem zero_pow {m : ℕ} (mpos : m > 0) : 0^m = (0 : A) := have h₁ : ∀ m : nat, (0 : A)^(succ m) = (0 : A), begin intro m, induction m, krewrite pow_one, apply zero_mul end, obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos mpos, show 0^m = 0, by rewrite h₂; apply h₁ end semiring section integral_domain variable [s : integral_domain A] include s definition integral_domain_has_pow_nat [instance] : has_pow_nat A := monoid_has_pow_nat theorem eq_zero_of_pow_eq_zero {a : A} {m : ℕ} (H : a^m = 0) : a = 0 := or.elim (eq_zero_or_pos m) (suppose m = 0, by rewrite [`m = 0` at H, pow_zero at H]; apply absurd H (ne.symm zero_ne_one)) (suppose m > 0, have h₁ : ∀ m, a^succ m = 0 → a = 0, begin intro m, induction m with m ih, {krewrite pow_one; intros; assumption}, rewrite pow_succ, intro H, cases eq_zero_or_eq_zero_of_mul_eq_zero H with h₃ h₄, assumption, exact ih h₄ end, obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos `m > 0`, show a = 0, by rewrite h₂ at H; apply h₁ m' H) theorem pow_ne_zero_of_ne_zero {a : A} {m : ℕ} (H : a ≠ 0) : a^m ≠ 0 := assume H', H (eq_zero_of_pow_eq_zero H') end integral_domain section division_ring variable [s : division_ring A] include s theorem division_ring.pow_ne_zero_of_ne_zero {a : A} {m : ℕ} (H : a ≠ 0) : a^m ≠ 0 := or.elim (eq_zero_or_pos m) (suppose m = 0, by rewrite [`m = 0`, pow_zero]; exact (ne.symm zero_ne_one)) (suppose m > 0, have h₁ : ∀ m, a^succ m ≠ 0, begin intro m, induction m with m ih, { krewrite pow_one; assumption }, rewrite pow_succ, apply division_ring.mul_ne_zero H ih end, obtain m' (h₂ : m = succ m'), from exists_eq_succ_of_pos `m > 0`, show a^m ≠ 0, by rewrite h₂; apply h₁ m') end division_ring section linear_ordered_semiring variable [s : linear_ordered_semiring A] include s theorem pow_pos_of_pos {x : A} (i : ℕ) (H : x > 0) : x^i > 0 := begin induction i with [j, ih], {show (1 : A) > 0, from zero_lt_one}, {show x^(succ j) > 0, from mul_pos H ih} end theorem pow_nonneg_of_nonneg {x : A} (i : ℕ) (H : x ≥ 0) : x^i ≥ 0 := begin induction i with j ih, {show (1 : A) ≥ 0, from le_of_lt zero_lt_one}, {show x^(succ j) ≥ 0, from mul_nonneg H ih} end theorem pow_le_pow_of_le {x y : A} (i : ℕ) (H₁ : 0 ≤ x) (H₂ : x ≤ y) : x^i ≤ y^i := begin induction i with i ih, {rewrite *pow_zero, apply le.refl}, rewrite *pow_succ, have H : 0 ≤ x^i, from pow_nonneg_of_nonneg i H₁, apply mul_le_mul H₂ ih H (le.trans H₁ H₂) end theorem pow_ge_one {x : A} (i : ℕ) (xge1 : x ≥ 1) : x^i ≥ 1 := have H : x^i ≥ 1^i, from pow_le_pow_of_le i (le_of_lt zero_lt_one) xge1, by rewrite one_pow at H; exact H theorem pow_gt_one {x : A} {i : ℕ} (xgt1 : x > 1) (ipos : i > 0) : x^i > 1 := have xpos : x > 0, from lt.trans zero_lt_one xgt1, begin induction i with [i, ih], {exfalso, exact !lt.irrefl ipos}, have xige1 : x^i ≥ 1, from pow_ge_one _ (le_of_lt xgt1), rewrite [pow_succ, -mul_one 1], apply mul_lt_mul xgt1 xige1 zero_lt_one, apply le_of_lt xpos end theorem squared_lt_squared {x y : A} (H1 : 0 ≤ x) (H2 : x < y) : x^2 < y^2 := by rewrite [*pow_two]; apply mul_self_lt_mul_self H1 H2 theorem squared_le_squared {x y : A} (H1 : 0 ≤ x) (H2 : x ≤ y) : x^2 ≤ y^2 := or.elim (lt_or_eq_of_le H2) (assume xlty, le_of_lt (squared_lt_squared H1 xlty)) (assume xeqy, by rewrite xeqy; apply le.refl) theorem lt_of_squared_lt_squared {x y : A} (H1 : y ≥ 0) (H2 : x^2 < y^2) : x < y := lt_of_not_ge (assume H : x ≥ y, not_le_of_gt H2 (squared_le_squared H1 H)) theorem le_of_squared_le_squared {x y : A} (H1 : y ≥ 0) (H2 : x^2 ≤ y^2) : x ≤ y := le_of_not_gt (assume H : x > y, not_lt_of_ge H2 (squared_lt_squared H1 H)) theorem eq_of_squared_eq_squared_of_nonneg {x y : A} (H1 : x ≥ 0) (H2 : y ≥ 0) (H3 : x^2 = y^2) : x = y := lt.by_cases (suppose x < y, absurd (eq.subst H3 (squared_lt_squared H1 this)) !lt.irrefl) (suppose x = y, this) (suppose x > y, absurd (eq.subst H3 (squared_lt_squared H2 this)) !lt.irrefl) end linear_ordered_semiring section decidable_linear_ordered_comm_ring variable [s : decidable_linear_ordered_comm_ring A] include s definition decidable_linear_ordered_comm_ring_has_pow_nat [instance] : has_pow_nat A := monoid_has_pow_nat theorem abs_pow (a : A) (n : ℕ) : abs (a^n) = abs a^n := begin induction n with n ih, krewrite [*pow_zero, (abs_of_nonneg zero_le_one : abs (1 : A) = 1)], rewrite [*pow_succ, abs_mul, ih] end theorem squared_nonneg (x : A) : x^2 ≥ 0 := by rewrite [pow_two]; apply mul_self_nonneg theorem eq_zero_of_squared_eq_zero {x : A} (H : x^2 = 0) : x = 0 := by rewrite [pow_two at H]; exact eq_zero_of_mul_self_eq_zero H theorem abs_eq_abs_of_squared_eq_squared {x y : A} (H : x^2 = y^2) : abs x = abs y := have (abs x)^2 = (abs y)^2, by rewrite [-+abs_pow, H], eq_of_squared_eq_squared_of_nonneg (abs_nonneg x) (abs_nonneg y) this end decidable_linear_ordered_comm_ring section field variable [s : field A] include s theorem field.div_pow (a : A) {b : A} {n : ℕ} (bnz : b ≠ 0) : (a / b)^n = a^n / b^n := begin induction n with n ih, krewrite [*pow_zero, div_one], have bnnz : b^n ≠ 0, from division_ring.pow_ne_zero_of_ne_zero bnz, rewrite [*pow_succ, ih, !field.div_mul_div bnz bnnz] end end field section discrete_field variable [s : discrete_field A] include s theorem div_pow (a : A) {b : A} {n : ℕ} : (a / b)^n = a^n / b^n := begin induction n with n ih, krewrite [*pow_zero, div_one], rewrite [*pow_succ, ih, div_mul_div] end end discrete_field
75a5c71617f607871ca5067e7b2088822b3226b5
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/vm_let_expr.lean
8aa36a99a817368c28694480d2c8a54fd80ac2e3
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
meta def mk_value (n : nat) : nat := trace "mk_value" (2 * n) meta def mk_fn (sz : nat) : nat → nat := let n := mk_value sz in λ x, x + n vm_eval let f := mk_fn 10 in f 1 + f 2 + f 3 + f 4 vm_eval ((let x := mk_value 10 in mk_fn x) 10)
26177cb029d0cfc2d4da24272ae162d07586362e
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/Reformat.lean
0b64ec31f1cf165139ad9749cf29ce7d5cd776d9
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
978
lean
/-! Parse and reformat file -/ import Lean.PrettyPrinter open Lean open Lean.Elab open Lean.Elab.Term open Lean.Format unsafe def main (args : List String) : IO Unit := do let (debug, f) : Bool × String := match args with | [f, "-d"] => (true, f) | [f] => (false, f) | _ => panic! "usage: file [-d]" let env ← mkEmptyEnvironment let stx ← Lean.Parser.parseFile env args.head! let (f, _) ← (tryFinally (PrettyPrinter.ppModule stx) printTraces).toIO { options := Options.empty.setBool `trace.PrettyPrinter.format debug } { env := env } IO.print f let stx' ← Lean.Parser.parseModule env args.head! (toString f) if stx' != stx then let stx := stx.getArg 1 let stx' := stx'.getArg 1 stx.getArgs.size.forM fun i => do if stx.getArg i != stx'.getArg i then throw $ IO.userError s!"reparsing failed:\n{stx.getArg i}\n{stx'.getArg i}" -- abbreviated Prelude.lean, which can be parsed without elaboration #eval main ["Reformat/Input.lean"]
f0c4982f081605b9e3220b31e7e604f0452079c4
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/type_library/tuple.lean
29d040b94048a0d2a6f2ffe3eb101f14286e2a4b
[]
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
110
lean
-- for each (n : nat), a type, (tuple n) def tuple : nat → Type | 0 := unit | (n' + 1) := nat × (tuple n')
2a9a8f05f7fd6232b3e4df6b6f5c81b77c41746d
6e44fda625e48340c6ffc7b1109a9e3b208e5384
/src/metric_spaces/basic.lean
a980071c32dc156dae2f9f1f91a200ddee5b89ac
[]
no_license
JasonKYi/learn_mspaces
9f998a265b907af6be6a54061637fcf1f6d1ee9d
54083e81da420d2d362a7024a8c86bea8529fe66
refs/heads/master
1,619,008,842,896
1,609,897,382,000
1,609,897,382,000
249,780,600
5
0
null
null
null
null
UTF-8
Lean
false
false
24,585
lean
import metric_spaces.definitions /- A metric space (X, d) is a non-empty set X alongside a function d : X ⨯ X → ℝ satisfying - ∀ x, y, ∈ X, d(x, y) ≥ 0 with equality iff x = y. - ∀ x, y, ∈ X, d(x, y) = d(y, x) - ∀ x, y, z ∈ X, d(x, z) ≤ d(x, y) + d(y, z). We call d a metric of the metric space (X, d). class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) [... Some stuff that doesn't matter ...] -/ /- In basic we will prove some simple results regarding metric spaces including theorem about - continuous functions - bounded metric spaces - open balls and open sets - closed sets - closure and interior - convergence of sequences -/ noncomputable theory local attribute [instance] classical.prop_decidable open set definitions variables {α : Type*} variables {X : Type*} [metric_space X] /- The metric of any two elements of a metric space is non-negative -/ theorem metric_nonneg : ∀ x y : X, 0 ≤ dist x y := λ x y, begin suffices : 0 ≤ dist y x + dist x y - dist y y, rw [dist_self, dist_comm, sub_zero] at this, linarith, linarith [dist_triangle y x y] end namespace continuity variables {Y : Type*} [metric_space Y] variables {Z : Type*} [metric_space Z] variables {f : X → Y} {g : Y → Z} /- The composition of two continuous functions is continuous -/ theorem comp_continuous (h₁ : is_continuous f) (h₂ : is_continuous g) : is_continuous (g ∘ f) := λ a ε hε, let ⟨δ₁, hg₁, hg₂⟩ := h₂ (f a) ε hε in let ⟨δ₂, hf₁, hf₂⟩ := h₁ a δ₁ hg₁ in ⟨δ₂, hf₁, λ x hx, hg₂ (f x) (hf₂ x hx)⟩ /- The product of two metric spaces is also a metric space (This messes with the product space defined in mathlib, hence setting the priority to 0) -/ @[priority 0] instance : metric_space (X × Y) := { dist := λ ⟨x₀, y₀⟩ ⟨x₁, y₁⟩, dist x₀ x₁ + dist y₀ y₁, dist_self := λ ⟨x, y⟩, show dist x x + dist y y = 0, by simp, eq_of_dist_eq_zero := begin rintros ⟨x₀, y₀⟩ ⟨x₁, y₁⟩, show dist x₀ x₁ + dist y₀ y₁ = 0 → (x₀, y₀) = (x₁, y₁), intro h, suffices : dist x₀ x₁ = 0 ∧ dist y₀ y₁ = 0, rwa [eq_of_dist_eq_zero this.left, eq_of_dist_eq_zero this.right], split, all_goals { linarith [metric_nonneg x₀ x₁, metric_nonneg y₀ y₁, h] } end, dist_comm := λ ⟨x₀, y₀⟩ ⟨x₁, y₁⟩, show dist x₀ x₁ + dist y₀ y₁ = dist x₁ x₀ + dist y₁ y₀, by simp [dist_comm], dist_triangle := λ ⟨x₀, y₀⟩ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show dist x₀ x₂ + dist y₀ y₂ ≤ dist x₀ x₁ + dist y₀ y₁ + (dist x₁ x₂ + dist y₁ y₂), by linarith [dist_triangle x₀ x₁ x₂, dist_triangle y₀ y₁ y₂] } /- This is based on the metric λ ⟨x₀, y₀⟩ ⟨x₁, y₁⟩, dist x₀ x₁ + dist y₀ y₁ /- Given two functions f g : X → ℝ, if both are continuous, then so is λ x : X, (f x, g x) -/ theorem prod_continuous' (f g : X → ℝ) (h₁ : is_continuous f) (h₂ : is_continuous g) : is_continuous (λ x : X, (f x, g x)) := λ x₀ ε hε, let ⟨δ₁, hδ₁, hf⟩ := h₁ x₀ (ε / 2) (half_pos hε) in let ⟨δ₂, hδ₂, hg⟩ := h₂ x₀ (ε / 2) (half_pos hε) in show ∃ δ > 0, ∀ (x : X), dist x x₀ < δ → dist (f x) (f x₀) + dist (g x) (g x₀) < ε, from ⟨min δ₁ δ₂, by simp; from ⟨hδ₁, hδ₂⟩, λ x hx, begin suffices : dist (f x) (f x₀) < ε / 2 ∧ dist (g x) (g x₀) < ε / 2, linarith [this.left, this.right], split, all_goals {apply hf x <|> apply hg x, apply lt_of_lt_of_le hx}, from inf_le_left, from inf_le_right end ⟩ -/ variables {X' : Type*} [metric_space X'] variables {Y' : Type*} [metric_space Y'] /- A generalisation of the above using the metric λ x y : X × X' max (dist x.1 y.1) (dist x.2 y.2) -/ theorem prod_continuous (f : X → Y) (g : X' → Y') (h₁ : is_continuous f) (h₂ : is_continuous g) : is_continuous (λ x : X × X', (f x.1, g x.2)) := λ x₀ ε hε, let ⟨δ₁, hδ₁, hf⟩ := h₁ x₀.1 ε hε in let ⟨δ₂, hδ₂, hg⟩ := h₂ x₀.2 ε hε in show ∃ δ > 0, ∀ (x : X × X'), dist x x₀ < δ → max (dist (f x.1) (f x₀.1)) (dist (g x.2) (g x₀.2)) < ε, from ⟨min δ₁ δ₂, by simp; from ⟨hδ₁, hδ₂⟩, λ x hx, begin suffices : dist (f x.1) (f x₀.1) < ε ∧ dist (g x.2) (g x₀.2) < ε, simp [this.left, this.right], split, { apply hf x.1, simp at hx, apply lt_of_le_of_lt _ hx.left, show dist x.1 x₀.1 ≤ max (dist x.1 x₀.1) (dist x.2 x₀.2), rw le_max_iff, left, apply le_refl }, { apply hg x.2, simp at hx, apply lt_of_le_of_lt _ hx.right, show dist x.2 x₀.2 ≤ max (dist x.1 x₀.1) (dist x.2 x₀.2), rw le_max_iff, right, apply le_refl } end ⟩ /- TODO: now that we have the product of two metric spaces is also a metric space, we can show that (+) : ℝ × ℝ → ℝ is a continuous function and this the composition of this and two continous functions f, g is also continuous, i.e. f + g is continuous. Similar process for f × g. -/ /- Defining the diagonal map Δ : X → X × X as Δ(x) := (x, x) -/ def diagonal_map (X : Type*) [metric_space X] : X → X × X := λ x : X, (x, x) /- The diagonal map is continuous -/ lemma diagonal_map_is_continuous : is_continuous (diagonal_map X) := λ x₀ ε hε, ⟨ε, hε, λ x hx, show max (dist x x₀) (dist x x₀) < ε, by simp [hx]⟩ lemma comp_map_prod (f : X → Y) (g : X → Y') : (λ x : X, (f x, g x)) = (λ x : X × X, (f x.1, g x.2)) ∘ (diagonal_map X) := by ext; all_goals {simp, refl} /- Using the diagonal map, we can show given continuous functions f g, x → (f x, g x) is continous-/ theorem map_prod_continous (f : X → Y) (g : X → Y') (h₁ : is_continuous f) (h₂ : is_continuous g) : is_continuous (λ x : X, (f x, g x)) := begin rw comp_map_prod, refine comp_continuous diagonal_map_is_continuous _, apply prod_continuous, repeat {assumption} end end continuity namespace bounded /- If S is bounded then ∀ s₀ ∈ S, ∃ K : ℝ, ∀ s ∈ S, dist s₀ s ≤ K -/ lemma bounded_all {S : set X} (h₀ : is_bounded S) : ∀ s₀ ∈ S, ∃ K : ℝ, ∀ s ∈ S, dist s₀ s ≤ K := λ s₀ hs₀, or.elim h₀ (λ h₀, by simp [h₀, hs₀]) (λ h₀, let ⟨x₀, hx₀, K, hK⟩ := h₀ in ⟨K + K, λ s hs, by linarith [dist_triangle s₀ x₀ s, hK s₀ hs₀, (show dist x₀ s ≤ K, by rw dist_comm; from hK s hs)]⟩) /- Reverse of the above -/ lemma all_bounded {S : set X} (h₀ : ∀ s₀ ∈ S, ∃ K : ℝ, ∀ s ∈ S, dist s₀ s ≤ K) : is_bounded S := or.elim (eq_empty_or_nonempty S) (λ hs, or.inl $ hs) (λ hs, or.inr $ let ⟨s', hs'⟩ := hs in ⟨s', hs', let ⟨K, hK⟩ := h₀ s' hs' in ⟨K, by simp [dist_comm]; from hK⟩⟩) /- If S is bounded if and only if ∀ s₀ ∈ S, ∃ K : ℝ, ∀ s ∈ S, dist s₀ s ≤ K -/ theorem bounded_iff_all {S : set X} : is_bounded S ↔ ∀ s₀ ∈ S, ∃ K : ℝ, ∀ s ∈ S, dist s₀ s ≤ K := iff.intro (λ h, bounded_all h) (λ h, all_bounded h) /- The union of two bounded subsets is also bounded -/ lemma bounded_union_two (S T : set X) (hs : is_bounded S) (ht : is_bounded T) : is_bounded $ S ∪ T := or.elim hs (λ hs, by simp [hs, ht]) (λ ⟨x₀, hx₀, K₀, hK₀⟩, or.elim ht (λ ht, by simp [hs, ht]) (λ ⟨x₁, hx₁, K₁, hK₁⟩, or.inr ⟨x₀, by simp [hx₀], ⟨max K₀ (K₁ + dist x₀ x₁), λ x hx, begin cases hx, simp [hK₀, hx], rw [le_max_iff], right, conv_rhs {rw dist_comm}, apply le_trans (dist_triangle x x₁ x₀), simp [hK₁ x hx] end ⟩⟩ ) ) /- The union of finitely many bounded subsets is also bounded -/ theorem bounded_union (S : ℕ → set X) (h₀ : ∀ n : ℕ, is_bounded $ S n) : ∀ n : ℕ, is_bounded $ finset.sup (finset.range n) S | 0 := by left; simp; refl | (n + 1) := by simpa [finset.range_succ] using bounded_union_two _ _ (h₀ _) (bounded_union n) /- TODO : Change the above to something like theorem bounded_union {s : set β} (f : β → set X) {hs : finite s} (h₀ : ∀ i ∈ s, is_bounded $ f i) : is_bounded $ ⋃ i ∈ s, f i := -/ end bounded namespace open_closed /- Given an open ball, there exists an open ball (with positive radius) centered anywhere within the ball-/ theorem subset_open_ball (x₀ : X) (r : ℝ) : ∀ y ∈ open_ball x₀ r, ∃ r' > 0, open_ball y r' ⊆ open_ball x₀ r := λ y hy, ⟨r - dist x₀ y, by rw mem_set_of_eq at hy; linarith [hy], λ x hx, by apply lt_of_le_of_lt (dist_triangle x₀ y x); rw [mem_set_of_eq] at hx; linarith [hx] ⟩ /- An open ball is open -/ theorem open_ball_is_open (x₀ : X) (r : ℝ) (h : 0 < r) : is_open' $ open_ball x₀ r := subset_open_ball x₀ r /- An open ball has non-positive radius then its empty -/ lemma nonpos_empty {x₀ : X} {r : ℝ} (h₁ : r ≤ 0) : open_ball x₀ r = ∅ := begin ext, split, { intro hx, rw mem_set_of_eq at hx, exfalso, apply (not_le.mpr hx), apply le_trans h₁, from metric_nonneg x₀ x }, { intro hx, exfalso, from hx } end /- An open ball either has positive radius or its empty -/ lemma pos_or_empty (x₀ : X) (r : ℝ) : open_ball x₀ r = ∅ ∨ 0 < r := or_iff_not_imp_left.2 (by rw ← not_le; exact mt nonpos_empty) /- An empty set is open -/ theorem empty_is_open : is_open' (∅ : set X) := λ s hs, by exfalso; from hs variables {Y : Type*} [metric_space Y] variables {f : X → Y} /- f : X → Y is continuous iff f⁻¹ U is open in X whenever U is open -/ lemma contin_to_preimg_open (U : set Y) (h₀ : is_open' U) (h₁ : is_continuous f) : is_open' $ preimage f U := λ x hx, let ⟨ε, hε₁, hε₂⟩ := h₀ (f x) hx in let ⟨δ, hδ₁, hδ₂⟩ := h₁ x ε hε₁ in ⟨δ, hδ₁, λ x' hx', by apply hε₂; rw [mem_set_of_eq, dist_comm]; apply hδ₂ x'; rw dist_comm; assumption⟩ lemma preimg_open_to_contin : (∀ (U : set Y) (h₀ : is_open' U), is_open' $ preimage f U) → is_continuous f := λ h x ε hε, let U := open_ball (f x) ε in have hinU : f x ∈ U := by simp; from hε, let ⟨δ, hδ₀, hδ₁⟩ := h U (open_ball_is_open (f x) ε hε) x hinU in ⟨δ, hδ₀, λ y hy, begin suffices : y ∈ f⁻¹' U, simp at this, rw dist_comm, assumption, apply hδ₁, rw [mem_set_of_eq, dist_comm], assumption end ⟩ theorem contin_iff_preimg_open : (∀ (U : set Y) (h₀ : is_open' U), is_open' $ preimage f U) ↔ is_continuous f := iff.intro (preimg_open_to_contin) (λ hcontin U hopen, contin_to_preimg_open U hopen hcontin) /- A continuous function is continuous when restricted to a subspace -/ theorem restricted_contin_of_contin (h : is_continuous f) (U : set X) : is_continuous $ restrict f U := begin refine preimg_open_to_contin (λ V hV s hs, _), rcases hV (f s) hs with ⟨ε, hε₀, hε₁⟩, rcases h s ε hε₀ with ⟨δ, hδ₀, hδ₁⟩, refine ⟨δ, hδ₀, λ x hx, hε₁ $ _⟩, rw [mem_set_of_eq, dist_comm], refine hδ₁ x _, rw dist_comm, exact hx end /- An similar lemma for subsets -/ theorem subset_contin_of_contin {S T : set X} (hsub : S ⊆ T) (f : T → Y) (g : S → Y) (hf : is_continuous f) (hg : g = λ s, f ⟨s.1, hsub s.2⟩) : is_continuous g := begin refine preimg_open_to_contin (λ V hV s hs, _), rcases hV (g s) hs with ⟨ε, hε₀, hε₁⟩, rcases hf ⟨s.1, hsub s.2⟩ ε hε₀ with ⟨δ, hδ₀, hδ₁⟩, refine ⟨δ, hδ₀, λ x hx, hε₁ $ _⟩, rw [mem_set_of_eq, dist_comm, hg], refine hδ₁ ⟨x.1, hsub x.2⟩ _, rw dist_comm, exact hx end /- The intersect of finitely many open sets is open -/ lemma inter_open_is_open {U₀ U₁ : set X} (h₀ : is_open' U₀) (h₁ : is_open' U₁) : is_open' (U₀ ∩ U₁) := λ s ⟨hs₀, hs₁⟩, let ⟨ε₀, hε₀, hε₀'⟩ := h₀ s hs₀ in let ⟨ε₁, hε₁, hε₁'⟩ := h₁ s hs₁ in let ε := min ε₀ ε₁ in ⟨ε, by simp [hε₀, hε₁], begin rw subset_inter_iff, split, { refine subset.trans _ hε₀', simp, intros _ h _, assumption }, refine subset.trans _ hε₁', simp end ⟩ lemma inter_finite_open_is_open {I : set α} {U : α → set X} (hI : finite I) : (∀ i ∈ I, is_open' $ U i) → (is_open' $ ⋂ i ∈ I, U i) := finite.induction_on hI (λ x, by simp; from (λ s _, ⟨1, ⟨by norm_num, subset_univ (open_ball s 1)⟩⟩)) $ λ i S hi hS hopen hopen', begin rw bInter_insert, apply inter_open_is_open, { apply hopen', from mem_insert i S }, apply hopen, intros j hj, apply hopen', apply mem_union_right, assumption end /- The union of open sets is open-/ lemma union_open_is_open {U₀ U₁ : set X} (h₀ : is_open' U₀) (h₁ : is_open' U₁) : is_open' (U₀ ∪ U₁) := λ s hs, or.elim hs (λ hs', let ⟨ε, hε, hε'⟩ := h₀ s hs' in ⟨ε, hε, subset.trans hε' (subset_union_left U₀ U₁)⟩) (λ hs', let ⟨ε, hε, hε'⟩ := h₁ s hs' in ⟨ε, hε, subset.trans hε' (subset_union_right U₀ U₁)⟩) theorem Union_open_is_open {α} {U : α → set X} (h : ∀ i, is_open' $ U i) : is_open' $ ⋃ i, U i := λ x hx, let ⟨i, hi⟩ := mem_Union.mp hx in let ⟨ε, hε, hε'⟩ := h i x hi in ⟨ε, hε, begin refine subset.trans hε' _, intros y hy, rw mem_Union, from ⟨i, hy⟩ end ⟩ /- The union of finitely many closed sets is closed -/ theorem union_closed_is_closed {U V : set X} (hU : is_closed' U) (hV : is_closed' V) : is_closed' (U ∪ V) := begin unfold is_closed' at *, rw compl_union, exact inter_open_is_open hU hV end theorem union_finite_closed_is_closed {I : set α} {U : α → set X} (hI : finite I) (h : ∀ i ∈ I, is_closed' $ U i) : (is_closed' $ ⋃ i ∈ I, U i) := begin unfold is_closed' at *, rw compl_bUnion, from inter_finite_open_is_open hI h end /- The empty set is closed-/ theorem empty_is_closed : is_closed' (∅ : set X) := λ x hx, ⟨1, zero_lt_one, by simp⟩ /- The intersect of closed sets is closed-/ theorem Inter_closed_is_closed {α} {U : α → set X} (h : ∀ i, is_closed' $ U i) : is_closed' $ ⋂ i, U i := begin unfold is_closed' at *, rw compl_Inter, from Union_open_is_open h end namespace closure' /- The closure of a closed set is itself -/ theorem closure_self {S : set X} (h : is_closed' S) : (closure' S) = S := begin ext, unfold closure', simp, split, { intro hx, apply hx; finish }, intros hx T hT₀ hT₁, apply hT₀, assumption end /- The closure of a set is also closed -/ lemma closure_closed (S : set X) : is_closed' $ closure' S := Inter_closed_is_closed $ λ T, Inter_closed_is_closed $ λ h₁, Inter_closed_is_closed $ λ h₂, h₂ /- The closure of a closure is itself -/ theorem closure_closure' (S : set X) : closure' (closure' S) = closure' S := closure_self $ closure_closed S /- The closure of a set S is S ∪ {limit points of S} -/ -- A set is smaller than its closure lemma subset_closure' {S : set X} : S ⊆ closure' S := subset_Inter $ λ _, subset_Inter $ λ h, subset_Inter $ λ _, h -- The limit points of a set is smaller than its closure lemma limit_points_sub_closure' {S : set X} : limit_points S ⊆ closure' S := λ x hx, begin simp, intros T hS hT, apply classical.by_contradiction, intro hnT, rcases hT x hnT with ⟨ε, hε₀, hε₁⟩, rcases hx ε hε₀ with ⟨y, hy₀, hy₁, hy₂⟩, have : y ∈ Tᶜ, apply hε₁, assumption, have : y ∈ T, apply hS, assumption, contradiction end lemma with_limit_points_sub_closure {S : set X} : S ∪ limit_points S ⊆ closure' S := union_subset_iff.mpr $ ⟨subset_closure', limit_points_sub_closure'⟩ lemma closure_sub_sub_closed {S T : set X} (hT : is_closed' T) (hST : S ⊆ T) : closure' S ⊆ T := begin intros x hx, rw mem_Inter at hx, have := mem_Inter.1 (hx T) hST, refine mem_Inter.1 this hT end /- Sequences within a set and it's limit points that converges converges to itself-/ lemma limit_in_with_limit_points {a : ℕ → X} {l} {S : set X} (h : ∀ n, a n ∈ S ∪ limit_points S) (h₁ : a ⇒ l) : l ∈ S ∪ limit_points S := begin cases classical.em (∃ n, l = a n) with heq hneq, cases heq with n hn, cases h n with hS hlS, left, exact ((symm hn) ▸ hS), right, exact ((symm hn) ▸ hlS), push_neg at hneq, cases classical.em (l ∈ S) with _ hlS, { left, assumption }, { right, intros ε hε, cases h₁ (ε / 2) (half_pos hε) with n hn, cases h n with hS' hlS', exact ⟨a n, hS', hneq n, lt_trans (hn n (le_refl n)) (half_lt_self hε)⟩, rcases hlS' (ε / 2) (half_pos hε) with ⟨y, hy₀, hy₁, hy₂⟩, refine ⟨y, hy₀, λ heq, hlS $ _, lt_of_le_of_lt (dist_triangle l (a n) y) _⟩, { rw heq, exact hy₀ }, { rw mem_set_of_eq at hy₂, linarith [hy₂, hn n (le_refl n)] } } end /- By constructing a sequence that converges outside of the limit points with show by contradiction that a set with its limit points is closed -/ theorem with_limit_points_is_closed (S : set X) : is_closed' (S ∪ limit_points S) := begin intros s hs, apply classical.by_contradiction, intro h, push_neg at h, have : ∀ n : ℕ, ∃ x ∈ open_ball s (1 / (n + 1)), x ∈ (S ∪ limit_points S), { intro n, apply classical.by_contradiction, push_neg, intro hn, exact h (1 / (n + 1)) (nat.one_div_pos_of_nat) hn }, simp only [classical.skolem] at this, rcases this with ⟨a, ha₀, ha₁⟩, have : a ⇒ s, { intros ε hε, cases exists_nat_gt (1 / ε) with N hN, refine ⟨N, λ n hn, _⟩, have := ha₀ n, rw mem_set_of_eq at this, refine lt_trans this _, rw (one_div_lt _ hε), exact lt_of_lt_of_le hN (by norm_cast; exact le_trans hn (nat.le_succ n)), norm_cast, exact nat.succ_pos n }, exact hs (limit_in_with_limit_points ha₁ this) end lemma closure_sub_with_limit_points {S : set X} : closure' S ⊆ S ∪ limit_points S := closure_sub_sub_closed (with_limit_points_is_closed S) (subset_union_left S (limit_points S)) theorem with_limit_points_is_closure (S : set X) : closure' S = S ∪ limit_points S := subset.antisymm_iff.mpr $ ⟨closure_sub_with_limit_points, with_limit_points_sub_closure⟩ /- If S ⊆ T, the the limit points of S ⊆ limit points of T -/ theorem limit_points_le {S T : set X} (h : S ⊆ T) : limit_points S ⊆ limit_points T := λ x hx ε hε, let ⟨δ, hδ₀, hδ₁⟩ := hx ε hε in ⟨δ, by apply h; from hδ₀, hδ₁⟩ /- The closure of a smaller set is smaller than closure -/ theorem closure_mono' {S T : set X} (h : S ⊆ T) : closure' S ⊆ closure' T := begin iterate 2 {rw with_limit_points_is_closure}, suffices : limit_points S ⊆ limit_points T, rw union_subset_iff, split, refine subset.trans h _, simp, refine subset.trans this _, simp, from limit_points_le h end theorem monotone_closure' : monotone $ @closure' X _ := λ _ _, closure_mono' /- Closure is the smallest closed subset -/ theorem closure_is_min {S T : set X} (h₀ : is_closed' T) (h₁ : S ⊆ T) : closure' S ⊆ T := λ x hx, begin apply mem_Inter.mp hx T, simp only [mem_range], refine ⟨h₁, by finish⟩ end end closure' namespace interior' /- An alternative definition of interiror -/ attribute [reducible] def interior'' (S : set X) := {x : X | x ∈ S ∧ ∃ ε > 0, open_ball x ε ⊆ S} notation S`⁰` := interior'' S /- The interior is open -/ lemma interior'_is_open (S : set X) : is_open' $ interior' S := Union_open_is_open $ λ _, Union_open_is_open $ λ _, Union_open_is_open $ λ h, h lemma interior''_is_open (S : set X) : is_open' $ S⁰ := λ x hx, let ⟨hS, ε, hε₀, hε₁⟩ := hx in ⟨ε, hε₀, λ y hy, ⟨by apply hε₁; assumption, let ⟨δ, hδ₀, hδ₁⟩ := (open_ball_is_open x ε hε₀) y hy in ⟨δ, hδ₀, subset.trans hδ₁ hε₁⟩⟩ ⟩ /- The interior is smaller than the set -/ lemma interior'_subset (S : set X) : interior' S ⊆ S := λ x hx, let ⟨T, T', hT, hT'⟩ := mem_Union.mp hx in begin simp at hT, cases hT with hT₀ hT₁, suffices : (⋃ (h₀ : is_open' T), T) ⊆ T, { apply hT₀, apply this, rw hT₁, assumption }, { intros y hy, rw mem_Union at hy, cases hy with _ h, assumption } end lemma interior''_subset (S : set X) : S⁰ ⊆ S := λ x hx, hx.1 @[simp] theorem eq_interior (S : set X) : interior' S = (S⁰) := begin rw subset.antisymm_iff, refine ⟨λ x hx, _, λ x hx, _⟩, { refine ⟨interior'_subset S hx, _⟩, rcases interior'_is_open S x hx with ⟨ε, hε₀, hε₁⟩, exact ⟨ε, hε₀, subset.trans hε₁ (interior'_subset S)⟩ }, { rw mem_Union, refine ⟨S⁰, _⟩, rw mem_Union, refine ⟨interior''_subset S, _⟩, rw mem_Union, exact ⟨interior''_is_open S, hx⟩ } end /- The interior of an open set is itself -/ theorem interior'_self {S : set X} (h : is_open' S) : interior' S = S := begin rw subset.antisymm_iff, refine ⟨interior'_subset S, λ _ hx, _⟩, rw mem_Union, refine ⟨S, _⟩, rw mem_Union, refine ⟨subset.refl S, _⟩, rw mem_Union, refine ⟨h, hx⟩ end theorem interior''_self {S : set X} (h : is_open' S) : S⁰ = S := by rw ←eq_interior; exact interior'_self h /- The interior of the interior is itself -/ @[simp] theorem interior'_interior {S : set X} : interior' (interior' S) = interior' S:= interior'_self $ interior'_is_open S /- If S ⊆ T, then S⁰ ⊆ T⁰ -/ theorem interior''_mono {S T : set X} (h : S ⊆ T) : S⁰ ⊆ (T⁰) := λ x ⟨hx₀, ε, hε₀, hε₁⟩, ⟨h hx₀, ε, hε₀, subset.trans hε₁ h⟩ theorem monotone_interior'' : monotone $ @interior'' X _ := @interior''_mono X _ end interior' namespace boundary open closure' interior' /- Alternative definition of boundary -/ @[simp] theorem boundary' {S : set X} : boundary S = closure' S \ (S⁰) := by rwa ←eq_interior S end boundary end open_closed namespace convergence variables {Y : Type*} [metric_space Y] variables {s : ℕ → X} lemma dist_zero {x₀ x₁ : X} (h : ∀ (ε : ℝ) (hε : 0 < ε), dist x₀ x₁ < ε ) : x₀ = x₁ := eq_of_dist_eq_zero $ classical.by_contradiction $ λ hne, begin cases lt_or_gt_of_ne hne with hlt hgt, rw ←not_le at hlt, from hlt (metric_nonneg x₀ x₁), linarith [h _ hgt] end /- Limits are unique -/ theorem limit_unique (x₀ x₁ : X) (h₀ : s ⇒ x₀) (h₁ : s ⇒ x₁) : x₀ = x₁ := dist_zero $ λ ε hε, let ⟨N₀, hN₀⟩ := h₀ (ε / 2) (half_pos hε) in let ⟨N₁, hN₁⟩ := h₁ (ε / 2) (half_pos hε) in let N := max N₀ N₁ in lt_of_le_of_lt (dist_triangle x₀ (s N) x₁) $ by linarith [hN₀ N (le_max_left _ _), show dist (s N) x₁ < ε / 2, by rw dist_comm; from hN₁ N (le_max_right _ _)] /- Constants converges to themselves -/ theorem const_converge (x : X) : (λ n, x) ⇒ x := λ ε hε, ⟨1, λ n hn, by rw dist_self; exact hε⟩ /- Sequential continuity -/ theorem seq_contin {x : X} {f : X → Y} (hf : is_continuous f) (hs : s ⇒ x) : (λ n, f (s n)) ⇒ f x := λ ε hε, begin rcases hf x ε hε with ⟨δ, hδ₀, hδ₁⟩, rcases hs δ hδ₀ with ⟨N, hN⟩, refine ⟨N, λ n hn, _⟩, simp only [], rw dist_comm, refine hδ₁ _ _, rw dist_comm, refine hN _ hn end theorem seq_contin' {x : X} {f : X → Y} (hf : ∀ s : ℕ → X, s ⇒ x → (λ n, f (s n)) ⇒ f x) : is_continuous_at f x := begin unfold is_continuous_at, by_contra h, push_neg at h, rcases h with ⟨ε, hε, h⟩, choose s hs using λ n : ℕ, h (1 / (n + 1) : ℝ) nat.one_div_pos_of_nat, have : s ⇒ x, { intros δ hδ, rcases exists_nat_gt (1 / δ) with ⟨N, hN'⟩, refine ⟨N, λ n hn, _⟩, rw dist_comm, apply lt_trans (hs n).1 ((one_div_lt _ hδ).2 _), exact nat.cast_add_one_pos n, apply lt_trans hN', norm_cast, exact nat.lt_succ_iff.mpr hn }, specialize hf s this, suffices : ¬ ((λ (n : ℕ), f (s n)) ⇒ f x), contradiction, unfold converge_to, push_neg, refine ⟨ε, hε, λ N, ⟨N, le_refl _, _⟩⟩, rw dist_comm, exact (hs N).2 end end convergence
5236cff9b0a911a0418693292538179fc09a62ad
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Control/Functor.lean
af4a5259bc1e68722dd750c0f554484cfb31d71a
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,018
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.Core open Function universes u v class Functor (f : Type u → Type v) : Type (max (u+1) v) := (map : ∀ {α β : Type u}, (α → β) → f α → f β) (mapConst : ∀ {α β : Type u}, α → f β → f α := fun α β => map ∘ const β) infixr `<$>` := Functor.map infixr `<$` := Functor.mapConst @[reducible] def Functor.mapConstRev {f : Type u → Type v} [Functor f] {α β : Type u} : f β → α → f α := fun a b => b <$ a infixr `$>` := Functor.mapConstRev @[reducible] def Functor.mapRev {f : Type u → Type v} [Functor f] {α β : Type u} : f α → (α → β) → f β := fun a f => f <$> a infixl `<&>` := Functor.mapRev def Functor.discard {f : Type u → Type v} {α : Type u} [Functor f] (x : f α) : f PUnit := PUnit.unit <$ x export Functor (discard)
4b396c784b2c495fac6421632162a32716454756
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/dynamics/fixed_points/topology.lean
ace366252c332420c55df15d07345ddeecf6fa13
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,358
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl -/ import dynamics.fixed_points.basic import topology.separation /-! # Topological properties of fixed points > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Currently this file contains two lemmas: - `is_fixed_pt_of_tendsto_iterate`: if `f^n(x) → y` and `f` is continuous at `y`, then `f y = y`; - `is_closed_fixed_points`: the set of fixed points of a continuous map is a closed set. ## TODO fixed points, iterates -/ variables {α : Type*} [topological_space α] [t2_space α] {f : α → α} open function filter open_locale topology /-- If the iterates `f^[n] x` converge to `y` and `f` is continuous at `y`, then `y` is a fixed point for `f`. -/ lemma is_fixed_pt_of_tendsto_iterate {x y : α} (hy : tendsto (λ n, f^[n] x) at_top (𝓝 y)) (hf : continuous_at f y) : is_fixed_pt f y := begin refine tendsto_nhds_unique ((tendsto_add_at_top_iff_nat 1).1 _) hy, simp only [iterate_succ' f], exact hf.tendsto.comp hy end /-- The set of fixed points of a continuous map is a closed set. -/ lemma is_closed_fixed_points (hf : continuous f) : is_closed (fixed_points f) := is_closed_eq hf continuous_id
4817773cfbec3c91103094ca9d12bf2f6d1a33c6
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/abelian/non_preadditive.lean
7776df48b38e97ff1592d55c3296ac02e884b201
[ "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
32,067
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.kernels import category_theory.limits.shapes.normal_mono import category_theory.preadditive /-! # Every non_preadditive_abelian category is preadditive In mathlib, we define an abelian category as a preadditive category with a zero object, kernels and cokernels, products and coproducts and in which every monomorphism and epimorphis is normal. While virtually every interesting abelian category has a natural preadditive structure (which is why it is included in the definition), preadditivity is not actually needed: Every category that has all of the other properties appearing in the definition of an abelian category admits a preadditive structure. This is the construction we carry out in this file. The proof proceeds in roughly five steps: 1. Prove some results (for example that all equalizers exist) that would be trivial if we already had the preadditive structure but are a bit of work without it. 2. Develop images and coimages to show that every monomorphism is the kernel of its cokernel. The results of the first two steps are also useful for the "normal" development of abelian categories, and will be used there. 3. For every object `A`, define a "subtraction" morphism `σ : A ⨯ A ⟶ A` and use it to define subtraction on morphisms as `f - g := prod.lift f g ≫ σ`. 4. Prove a small number of identities about this subtraction from the definition of `σ`. 5. From these identities, prove a large number of other identities that imply that defining `f + g := f - (0 - g)` indeed gives an abelian group structure on morphisms such that composition is bilinear. The construction is non-trivial and it is quite remarkable that this abelian group structure can be constructed purely from the existence of a few limits and colimits. What's even more impressive is that all additive structures on a category are in some sense isomorphic, so for abelian categories with a natural preadditive structure, this construction manages to "almost" reconstruct this natural structure. However, we have not formalized this isomorphism. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory open category_theory open category_theory.limits namespace category_theory section universes v u variables (C : Type u) [category.{v} C] /-- We call a category `non_preadditive_abelian` if it has a zero object, kernels, cokernels, binary products and coproducts, and every monomorphism and every epimorphism is normal. -/ class non_preadditive_abelian := [has_zero_object : has_zero_object C] [has_zero_morphisms : has_zero_morphisms C] [has_kernels : has_kernels C] [has_cokernels : has_cokernels C] [has_finite_products : has_finite_products C] [has_finite_coproducts : has_finite_coproducts C] (normal_mono : Π {X Y : C} (f : X ⟶ Y) [mono f], normal_mono f) (normal_epi : Π {X Y : C} (f : X ⟶ Y) [epi f], normal_epi f) set_option default_priority 100 attribute [instance] non_preadditive_abelian.has_zero_object attribute [instance] non_preadditive_abelian.has_zero_morphisms attribute [instance] non_preadditive_abelian.has_kernels attribute [instance] non_preadditive_abelian.has_cokernels attribute [instance] non_preadditive_abelian.has_finite_products attribute [instance] non_preadditive_abelian.has_finite_coproducts end end category_theory open category_theory namespace category_theory.non_preadditive_abelian universes v u variables {C : Type u} [category.{v} C] section variables [non_preadditive_abelian C] section strong local attribute [instance] non_preadditive_abelian.normal_epi /-- In a `non_preadditive_abelian` category, every epimorphism is strong. -/ lemma strong_epi_of_epi {P Q : C} (f : P ⟶ Q) [epi f] : strong_epi f := by apply_instance end strong section mono_epi_iso variables {X Y : C} (f : X ⟶ Y) local attribute [instance] strong_epi_of_epi /-- In a `non_preadditive_abelian` category, a monomorphism which is also an epimorphism is an isomorphism. -/ def is_iso_of_mono_of_epi [mono f] [epi f] : is_iso f := is_iso_of_mono_of_strong_epi _ end mono_epi_iso /-- The pullback of two monomorphisms exists. -/ @[irreducible] lemma pullback_of_mono {X Y Z : C} (a : X ⟶ Z) (b : Y ⟶ Z) [mono a] [mono b] : has_limit (cospan a b) := let ⟨P, f, haf, i⟩ := non_preadditive_abelian.normal_mono a in let ⟨Q, g, hbg, i'⟩ := non_preadditive_abelian.normal_mono b in let ⟨a', ha'⟩ := kernel_fork.is_limit.lift' i (kernel.ι (prod.lift f g)) $ calc kernel.ι (prod.lift f g) ≫ f = kernel.ι (prod.lift f g) ≫ prod.lift f g ≫ limits.prod.fst : by rw prod.lift_fst ... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.fst : by rw kernel.condition_assoc ... = 0 : zero_comp in let ⟨b', hb'⟩ := kernel_fork.is_limit.lift' i' (kernel.ι (prod.lift f g)) $ calc kernel.ι (prod.lift f g) ≫ g = kernel.ι (prod.lift f g) ≫ (prod.lift f g) ≫ limits.prod.snd : by rw prod.lift_snd ... = (0 : kernel (prod.lift f g) ⟶ P ⨯ Q) ≫ limits.prod.snd : by rw kernel.condition_assoc ... = 0 : zero_comp in has_limit.mk { cone := pullback_cone.mk a' b' $ by { simp at ha' hb', rw [ha', hb'] }, is_limit := pullback_cone.is_limit.mk _ (λ s, kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) $ prod.hom_ext (calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.fst = pullback_cone.snd s ≫ b ≫ f : by simp only [prod.lift_fst, category.assoc] ... = pullback_cone.fst s ≫ a ≫ f : by rw pullback_cone.condition_assoc ... = pullback_cone.fst s ≫ 0 : by rw haf ... = 0 ≫ limits.prod.fst : by rw [comp_zero, zero_comp]) (calc ((pullback_cone.snd s ≫ b) ≫ prod.lift f g) ≫ limits.prod.snd = pullback_cone.snd s ≫ b ≫ g : by simp only [prod.lift_snd, category.assoc] ... = pullback_cone.snd s ≫ 0 : by rw hbg ... = 0 ≫ limits.prod.snd : by rw [comp_zero, zero_comp])) (λ s, (cancel_mono a).1 $ by { rw kernel_fork.ι_of_ι at ha', simp [ha', pullback_cone.condition s] }) (λ s, (cancel_mono b).1 $ by { rw kernel_fork.ι_of_ι at hb', simp [hb'] }) (λ s m h₁ h₂, (cancel_mono (kernel.ι (prod.lift f g))).1 $ calc m ≫ kernel.ι (prod.lift f g) = m ≫ a' ≫ a : by { congr, exact ha'.symm } ... = pullback_cone.fst s ≫ a : by rw [←category.assoc, h₁] ... = pullback_cone.snd s ≫ b : pullback_cone.condition s ... = kernel.lift (prod.lift f g) (pullback_cone.snd s ≫ b) _ ≫ kernel.ι (prod.lift f g) : by rw kernel.lift_ι) } /-- The pushout of two epimorphisms exists. -/ @[irreducible] lemma pushout_of_epi {X Y Z : C} (a : X ⟶ Y) (b : X ⟶ Z) [epi a] [epi b] : has_colimit (span a b) := let ⟨P, f, hfa, i⟩ := non_preadditive_abelian.normal_epi a in let ⟨Q, g, hgb, i'⟩ := non_preadditive_abelian.normal_epi b in let ⟨a', ha'⟩ := cokernel_cofork.is_colimit.desc' i (cokernel.π (coprod.desc f g)) $ calc f ≫ cokernel.π (coprod.desc f g) = coprod.inl ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inl_desc_assoc ... = coprod.inl ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition ... = 0 : has_zero_morphisms.comp_zero _ _ in let ⟨b', hb'⟩ := cokernel_cofork.is_colimit.desc' i' (cokernel.π (coprod.desc f g)) $ calc g ≫ cokernel.π (coprod.desc f g) = coprod.inr ≫ coprod.desc f g ≫ cokernel.π (coprod.desc f g) : by rw coprod.inr_desc_assoc ... = coprod.inr ≫ (0 : P ⨿ Q ⟶ cokernel (coprod.desc f g)) : by rw cokernel.condition ... = 0 : has_zero_morphisms.comp_zero _ _ in has_colimit.mk { cocone := pushout_cocone.mk a' b' $ by { simp only [cofork.π_of_π] at ha' hb', rw [ha', hb'] }, is_colimit := pushout_cocone.is_colimit.mk _ (λ s, cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) $ coprod.hom_ext (calc coprod.inl ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s = f ≫ b ≫ pushout_cocone.inr s : by rw coprod.inl_desc_assoc ... = f ≫ a ≫ pushout_cocone.inl s : by rw pushout_cocone.condition ... = 0 ≫ pushout_cocone.inl s : by rw reassoc_of hfa ... = coprod.inl ≫ 0 : by rw [comp_zero, zero_comp]) (calc coprod.inr ≫ coprod.desc f g ≫ b ≫ pushout_cocone.inr s = g ≫ b ≫ pushout_cocone.inr s : by rw coprod.inr_desc_assoc ... = 0 ≫ pushout_cocone.inr s : by rw reassoc_of hgb ... = coprod.inr ≫ 0 : by rw [comp_zero, zero_comp])) (λ s, (cancel_epi a).1 $ by { rw cokernel_cofork.π_of_π at ha', simp [reassoc_of ha', pushout_cocone.condition s] }) (λ s, (cancel_epi b).1 $ by { rw cokernel_cofork.π_of_π at hb', simp [reassoc_of hb'] }) (λ s m h₁ h₂, (cancel_epi (cokernel.π (coprod.desc f g))).1 $ calc cokernel.π (coprod.desc f g) ≫ m = (a ≫ a') ≫ m : by { congr, exact ha'.symm } ... = a ≫ pushout_cocone.inl s : by rw [category.assoc, h₁] ... = b ≫ pushout_cocone.inr s : pushout_cocone.condition s ... = cokernel.π (coprod.desc f g) ≫ cokernel.desc (coprod.desc f g) (b ≫ pushout_cocone.inr s) _ : by rw cokernel.π_desc) } section local attribute [instance] pullback_of_mono /-- The pullback of `(𝟙 X, f)` and `(𝟙 X, g)` -/ private abbreviation P {X Y : C} (f g : X ⟶ Y) [mono (prod.lift (𝟙 X) f)] [mono (prod.lift (𝟙 X) g)] : C := pullback (prod.lift (𝟙 X) f) (prod.lift (𝟙 X) g) /-- The equalizer of `f` and `g` exists. -/ @[irreducible] lemma has_limit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := have huv : (pullback.fst : P f g ⟶ X) = pullback.snd, from calc (pullback.fst : P f g ⟶ X) = pullback.fst ≫ 𝟙 _ : eq.symm $ category.comp_id _ ... = pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.fst : by rw prod.lift_fst ... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.fst : by rw pullback.condition_assoc ... = pullback.snd : by rw [prod.lift_fst, category.comp_id], have hvu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.snd ≫ g, from calc (pullback.fst : P f g ⟶ X) ≫ f = pullback.fst ≫ prod.lift (𝟙 X) f ≫ limits.prod.snd : by rw prod.lift_snd ... = pullback.snd ≫ prod.lift (𝟙 X) g ≫ limits.prod.snd : by rw pullback.condition_assoc ... = pullback.snd ≫ g : by rw prod.lift_snd, have huu : (pullback.fst : P f g ⟶ X) ≫ f = pullback.fst ≫ g, by rw [hvu, ←huv], has_limit.mk { cone := fork.of_ι pullback.fst huu, is_limit := fork.is_limit.mk _ (λ s, pullback.lift (fork.ι s) (fork.ι s) $ prod.hom_ext (by simp only [prod.lift_fst, category.assoc]) (by simp only [fork.app_zero_right, fork.app_zero_left, prod.lift_snd, category.assoc])) (λ s, by simp only [fork.ι_of_ι, pullback.lift_fst]) (λ s m h, pullback.hom_ext (by simpa only [pullback.lift_fst] using h walking_parallel_pair.zero) (by simpa only [huv.symm, pullback.lift_fst] using h walking_parallel_pair.zero)) } end section local attribute [instance] pushout_of_epi /-- The pushout of `(𝟙 Y, f)` and `(𝟙 Y, g)`. -/ private abbreviation Q {X Y : C} (f g : X ⟶ Y) [epi (coprod.desc (𝟙 Y) f)] [epi (coprod.desc (𝟙 Y) g)] : C := pushout (coprod.desc (𝟙 Y) f) (coprod.desc (𝟙 Y) g) /-- The coequalizer of `f` and `g` exists. -/ @[irreducible] lemma has_colimit_parallel_pair {X Y : C} (f g : X ⟶ Y) : has_colimit (parallel_pair f g) := have huv : (pushout.inl : Y ⟶ Q f g) = pushout.inr, from calc (pushout.inl : Y ⟶ Q f g) = 𝟙 _ ≫ pushout.inl : eq.symm $ category.id_comp _ ... = (coprod.inl ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inl_desc ... = (coprod.inl ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr : by simp only [category.assoc, pushout.condition] ... = pushout.inr : by rw [coprod.inl_desc, category.id_comp], have hvu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inr, from calc f ≫ (pushout.inl : Y ⟶ Q f g) = (coprod.inr ≫ coprod.desc (𝟙 Y) f) ≫ pushout.inl : by rw coprod.inr_desc ... = (coprod.inr ≫ coprod.desc (𝟙 Y) g) ≫ pushout.inr : by simp only [category.assoc, pushout.condition] ... = g ≫ pushout.inr : by rw coprod.inr_desc, have huu : f ≫ (pushout.inl : Y ⟶ Q f g) = g ≫ pushout.inl, by rw [hvu, huv], has_colimit.mk { cocone := cofork.of_π pushout.inl huu, is_colimit := cofork.is_colimit.mk _ (λ s, pushout.desc (cofork.π s) (cofork.π s) $ coprod.hom_ext (by simp only [coprod.inl_desc_assoc]) (by simp only [cofork.right_app_one, coprod.inr_desc_assoc, cofork.left_app_one])) (λ s, by simp only [pushout.inl_desc, cofork.π_of_π]) (λ s m h, pushout.hom_ext (by simpa only [pushout.inl_desc] using h walking_parallel_pair.one) (by simpa only [huv.symm, pushout.inl_desc] using h walking_parallel_pair.one)) } end section local attribute [instance] has_limit_parallel_pair /-- A `non_preadditive_abelian` category has all equalizers. -/ @[priority 100] instance has_equalizers : has_equalizers C := has_equalizers_of_has_limit_parallel_pair _ end section local attribute [instance] has_colimit_parallel_pair /-- A `non_preadditive_abelian` category has all coequalizers. -/ @[priority 100] instance has_coequalizers : has_coequalizers C := has_coequalizers_of_has_colimit_parallel_pair _ end section /-- If a zero morphism is a kernel of `f`, then `f` is a monomorphism. -/ lemma mono_of_zero_kernel {X Y : C} (f : X ⟶ Y) (Z : C) (l : is_limit (kernel_fork.of_ι (0 : Z ⟶ X) (show 0 ≫ f = 0, by simp))) : mono f := ⟨λ P u v huv, begin obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_epi (coequalizer.π u v), obtain ⟨m, hm⟩ := coequalizer.desc' f huv, have hwf : w ≫ f = 0, { rw [←hm, reassoc_of hw, zero_comp] }, obtain ⟨n, hn⟩ := kernel_fork.is_limit.lift' l _ hwf, rw [fork.ι_of_ι, has_zero_morphisms.comp_zero] at hn, haveI : is_iso (coequalizer.π u v) := by apply is_iso_colimit_cocone_parallel_pair_of_eq hn.symm hl, apply (cancel_mono (coequalizer.π u v)).1, exact coequalizer.condition _ _ end⟩ /-- If a zero morphism is a cokernel of `f`, then `f` is an epimorphism. -/ lemma epi_of_zero_cokernel {X Y : C} (f : X ⟶ Y) (Z : C) (l : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ Z) (show f ≫ 0 = 0, by simp))) : epi f := ⟨λ P u v huv, begin obtain ⟨W, w, hw, hl⟩ := non_preadditive_abelian.normal_mono (equalizer.ι u v), obtain ⟨m, hm⟩ := equalizer.lift' f huv, have hwf : f ≫ w = 0, { rw [←hm, category.assoc, hw, comp_zero] }, obtain ⟨n, hn⟩ := cokernel_cofork.is_colimit.desc' l _ hwf, rw [cofork.π_of_π, zero_comp] at hn, haveI : is_iso (equalizer.ι u v) := by apply is_iso_limit_cone_parallel_pair_of_eq hn.symm hl, apply (cancel_epi (equalizer.ι u v)).1, exact equalizer.condition _ _ end⟩ local attribute [instance] has_zero_object.has_zero /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `0 : 0 ⟶ X` is a kernel of `f`. -/ def zero_kernel_of_cancel_zero {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : is_limit (kernel_fork.of_ι (0 : 0 ⟶ X) (show 0 ≫ f = 0, by simp)) := fork.is_limit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (kernel_fork.condition s), zero_comp]) (λ s m h, by ext) /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `0 : Y ⟶ 0` is a cokernel of `f`. -/ def zero_cokernel_of_zero_cancel {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : is_colimit (cokernel_cofork.of_π (0 : Y ⟶ 0) (show f ≫ 0 = 0, by simp)) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by rw [hf _ _ (cokernel_cofork.condition s), comp_zero]) (λ s m h, by ext) /-- If `g ≫ f = 0` implies `g = 0` for all `g`, then `f` is a monomorphism. -/ lemma mono_of_cancel_zero {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Z ⟶ X) (hgf : g ≫ f = 0), g = 0) : mono f := mono_of_zero_kernel f 0 $ zero_kernel_of_cancel_zero f hf /-- If `f ≫ g = 0` implies `g = 0` for all `g`, then `g` is a monomorphism. -/ lemma epi_of_zero_cancel {X Y : C} (f : X ⟶ Y) (hf : ∀ (Z : C) (g : Y ⟶ Z) (hgf : f ≫ g = 0), g = 0) : epi f := epi_of_zero_cokernel f 0 $ zero_cokernel_of_zero_cancel f hf end section factor variables {P Q : C} (f : P ⟶ Q) /-- The kernel of the cokernel of `f` is called the image of `f`. -/ protected abbreviation image : C := kernel (cokernel.π f) /-- The inclusion of the image into the codomain. -/ protected abbreviation image.ι : non_preadditive_abelian.image f ⟶ Q := kernel.ι (cokernel.π f) /-- There is a canonical epimorphism `p : P ⟶ image f` for every `f`. -/ protected abbreviation factor_thru_image : P ⟶ non_preadditive_abelian.image f := kernel.lift (cokernel.π f) f $ cokernel.condition f /-- `f` factors through its image via the canonical morphism `p`. -/ @[simp, reassoc] protected lemma image.fac : non_preadditive_abelian.factor_thru_image f ≫ image.ι f = f := kernel.lift_ι _ _ _ /-- The map `p : P ⟶ image f` is an epimorphism -/ instance : epi (non_preadditive_abelian.factor_thru_image f) := let I := non_preadditive_abelian.image f, p := non_preadditive_abelian.factor_thru_image f, i := kernel.ι (cokernel.π f) in -- It will suffice to consider some g : I ⟶ R such that p ≫ g = 0 and show that g = 0. epi_of_zero_cancel _ $ λ R (g : I ⟶ R) (hpg : p ≫ g = 0), begin -- Since C is abelian, u := ker g ≫ i is the kernel of some morphism h. let u := kernel.ι g ≫ i, haveI : mono u := mono_comp _ _, haveI hu := non_preadditive_abelian.normal_mono u, let h := hu.g, -- By hypothesis, p factors through the kernel of g via some t. obtain ⟨t, ht⟩ := kernel.lift' g p hpg, have fh : f ≫ h = 0, calc f ≫ h = (p ≫ i) ≫ h : (image.fac f).symm ▸ rfl ... = ((t ≫ kernel.ι g) ≫ i) ≫ h : ht ▸ rfl ... = t ≫ u ≫ h : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = t ≫ 0 : hu.w ▸ rfl ... = 0 : has_zero_morphisms.comp_zero _ _, -- h factors through the cokernel of f via some l. obtain ⟨l, hl⟩ := cokernel.desc' f h fh, have hih : i ≫ h = 0, calc i ≫ h = i ≫ cokernel.π f ≫ l : hl ▸ rfl ... = 0 ≫ l : by rw [←category.assoc, kernel.condition] ... = 0 : zero_comp, -- i factors through u = ker h via some s. obtain ⟨s, hs⟩ := normal_mono.lift' u i hih, have hs' : (s ≫ kernel.ι g) ≫ i = 𝟙 I ≫ i, by rw [category.assoc, hs, category.id_comp], haveI : epi (kernel.ι g) := epi_of_epi_fac ((cancel_mono _).1 hs'), -- ker g is an epimorphism, but ker g ≫ g = 0 = ker g ≫ 0, so g = 0 as required. exact zero_of_epi_comp _ (kernel.condition g) end instance mono_factor_thru_image [mono f] : mono (non_preadditive_abelian.factor_thru_image f) := mono_of_mono_fac $ image.fac f instance is_iso_factor_thru_image [mono f] : is_iso (non_preadditive_abelian.factor_thru_image f) := is_iso_of_mono_of_epi _ /-- The cokernel of the kernel of `f` is called the coimage of `f`. -/ protected abbreviation coimage : C := cokernel (kernel.ι f) /-- The projection onto the coimage. -/ protected abbreviation coimage.π : P ⟶ non_preadditive_abelian.coimage f := cokernel.π (kernel.ι f) /-- There is a canonical monomorphism `i : coimage f ⟶ Q`. -/ protected abbreviation factor_thru_coimage : non_preadditive_abelian.coimage f ⟶ Q := cokernel.desc (kernel.ι f) f $ kernel.condition f /-- `f` factors through its coimage via the canonical morphism `p`. -/ protected lemma coimage.fac : coimage.π f ≫ non_preadditive_abelian.factor_thru_coimage f = f := cokernel.π_desc _ _ _ /-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/ instance : mono (non_preadditive_abelian.factor_thru_coimage f) := let I := non_preadditive_abelian.coimage f, i := non_preadditive_abelian.factor_thru_coimage f, p := cokernel.π (kernel.ι f) in mono_of_cancel_zero _ $ λ R (g : R ⟶ I) (hgi : g ≫ i = 0), begin -- Since C is abelian, u := p ≫ coker g is the cokernel of some morphism h. let u := p ≫ cokernel.π g, haveI : epi u := epi_comp _ _, haveI hu := non_preadditive_abelian.normal_epi u, let h := hu.g, -- By hypothesis, i factors through the cokernel of g via some t. obtain ⟨t, ht⟩ := cokernel.desc' g i hgi, have hf : h ≫ f = 0, calc h ≫ f = h ≫ (p ≫ i) : (coimage.fac f).symm ▸ rfl ... = h ≫ (p ≫ (cokernel.π g ≫ t)) : ht ▸ rfl ... = h ≫ u ≫ t : by simp only [category.assoc]; conv_lhs { congr, skip, rw ←category.assoc } ... = 0 ≫ t : by rw [←category.assoc, hu.w] ... = 0 : zero_comp, -- h factors through the kernel of f via some l. obtain ⟨l, hl⟩ := kernel.lift' f h hf, have hhp : h ≫ p = 0, calc h ≫ p = (l ≫ kernel.ι f) ≫ p : hl ▸ rfl ... = l ≫ 0 : by rw [category.assoc, cokernel.condition] ... = 0 : comp_zero, -- p factors through u = coker h via some s. obtain ⟨s, hs⟩ := normal_epi.desc' u p hhp, have hs' : p ≫ cokernel.π g ≫ s = p ≫ 𝟙 I, by rw [←category.assoc, hs, category.comp_id], haveI : mono (cokernel.π g) := mono_of_mono_fac ((cancel_epi _).1 hs'), -- coker g is a monomorphism, but g ≫ coker g = 0 = 0 ≫ coker g, so g = 0 as required. exact zero_of_comp_mono _ (cokernel.condition g) end instance epi_factor_thru_coimage [epi f] : epi (non_preadditive_abelian.factor_thru_coimage f) := epi_of_epi_fac $ coimage.fac f instance is_iso_factor_thru_coimage [epi f] : is_iso (non_preadditive_abelian.factor_thru_coimage f) := is_iso_of_mono_of_epi _ end factor section cokernel_of_kernel variables {X Y : C} {f : X ⟶ Y} /-- In a `non_preadditive_abelian` category, an epi is the cokernel of its kernel. More precisely: If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel of `fork.ι s`. -/ def epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) : is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) := is_cokernel.cokernel_iso _ _ (cokernel.of_iso_comp _ _ (limits.is_limit.cone_point_unique_up_to_iso (limit.is_limit _) h) (cone_morphism.w (limits.is_limit.unique_up_to_iso (limit.is_limit _) h).hom _)) (as_iso $ non_preadditive_abelian.factor_thru_coimage f) (coimage.fac f) /-- In a `non_preadditive_abelian` category, a mono is the kernel of its cokernel. More precisely: If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel of `cofork.π s`. -/ def mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) : is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) := is_kernel.iso_kernel _ _ (kernel.of_comp_iso _ _ (limits.is_colimit.cocone_point_unique_up_to_iso h (colimit.is_colimit _)) (cocone_morphism.w (limits.is_colimit.unique_up_to_iso h $ colimit.is_colimit _).hom _)) (as_iso $ non_preadditive_abelian.factor_thru_image f) (image.fac f) end cokernel_of_kernel section /-- The composite `A ⟶ A ⨯ A ⟶ cokernel (Δ A)`, where the first map is `(𝟙 A, 0)` and the second map is the canonical projection into the cokernel. -/ abbreviation r (A : C) : A ⟶ cokernel (diag A) := prod.lift (𝟙 A) 0 ≫ cokernel.π (diag A) instance mono_Δ {A : C} : mono (diag A) := mono_of_mono_fac $ prod.lift_fst _ _ instance mono_r {A : C} : mono (r A) := begin let hl : is_limit (kernel_fork.of_ι (diag A) (cokernel.condition (diag A))), { exact mono_is_kernel_of_cokernel _ (colimit.is_colimit _) }, apply mono_of_cancel_zero, intros Z x hx, have hxx : (x ≫ prod.lift (𝟙 A) (0 : A ⟶ A)) ≫ cokernel.π (diag A) = 0, { rw [category.assoc, hx] }, obtain ⟨y, hy⟩ := kernel_fork.is_limit.lift' hl _ hxx, rw kernel_fork.ι_of_ι at hy, have hyy : y = 0, { erw [←category.comp_id y, ←limits.prod.lift_snd (𝟙 A) (𝟙 A), ←category.assoc, hy, category.assoc, prod.lift_snd, has_zero_morphisms.comp_zero] }, haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _), apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1, rw [←hy, hyy, zero_comp, zero_comp] end instance epi_r {A : C} : epi (r A) := begin have hlp : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ limits.prod.snd = 0 := prod.lift_snd _ _, let hp1 : is_limit (kernel_fork.of_ι (prod.lift (𝟙 A) (0 : A ⟶ A)) hlp), { refine fork.is_limit.mk _ (λ s, fork.ι s ≫ limits.prod.fst) _ _, { intro s, ext; simp, erw category.comp_id }, { intros s m h, haveI : mono (prod.lift (𝟙 A) (0 : A ⟶ A)) := mono_of_mono_fac (prod.lift_fst _ _), apply (cancel_mono (prod.lift (𝟙 A) (0 : A ⟶ A))).1, convert h walking_parallel_pair.zero, ext; simp } }, let hp2 : is_colimit (cokernel_cofork.of_π (limits.prod.snd : A ⨯ A ⟶ A) hlp), { exact epi_is_cokernel_of_kernel _ hp1 }, apply epi_of_zero_cancel, intros Z z hz, have h : prod.lift (𝟙 A) (0 : A ⟶ A) ≫ cokernel.π (diag A) ≫ z = 0, { rw [←category.assoc, hz] }, obtain ⟨t, ht⟩ := cokernel_cofork.is_colimit.desc' hp2 _ h, rw cokernel_cofork.π_of_π at ht, have htt : t = 0, { rw [←category.id_comp t], change 𝟙 A ≫ t = 0, rw [←limits.prod.lift_snd (𝟙 A) (𝟙 A), category.assoc, ht, ←category.assoc, cokernel.condition, zero_comp] }, apply (cancel_epi (cokernel.π (diag A))).1, rw [←ht, htt, comp_zero, comp_zero] end instance is_iso_r {A : C} : is_iso (r A) := is_iso_of_mono_of_epi _ /-- The composite `A ⨯ A ⟶ cokernel (diag A) ⟶ A` given by the natural projection into the cokernel followed by the inverse of `r`. In the category of modules, using the normal kernels and cokernels, this map is equal to the map `(a, b) ↦ a - b`, hence the name `σ` for "subtraction". -/ abbreviation σ {A : C} : A ⨯ A ⟶ A := cokernel.π (diag A) ≫ is_iso.inv (r A) end @[simp, reassoc] lemma diag_σ {X : C} : diag X ≫ σ = 0 := by rw [cokernel.condition_assoc, zero_comp] @[simp, reassoc] lemma lift_σ {X : C} : prod.lift (𝟙 X) 0 ≫ σ = 𝟙 X := by rw [←category.assoc, is_iso.hom_inv_id] @[reassoc] lemma lift_map {X Y : C} (f : X ⟶ Y) : prod.lift (𝟙 X) 0 ≫ limits.prod.map f f = f ≫ prod.lift (𝟙 Y) 0 := by simp /-- σ is a cokernel of Δ X. -/ def is_colimit_σ {X : C} : is_colimit (cokernel_cofork.of_π σ diag_σ) := cokernel.cokernel_iso _ σ (as_iso (r X)).symm (by rw [iso.symm_hom, as_iso_inv]) /-- This is the key identity satisfied by `σ`. -/ lemma σ_comp {X Y : C} (f : X ⟶ Y) : σ ≫ f = limits.prod.map f f ≫ σ := begin obtain ⟨g, hg⟩ := cokernel_cofork.is_colimit.desc' is_colimit_σ (limits.prod.map f f ≫ σ) (by simp), suffices hfg : f = g, { rw [←hg, cofork.π_of_π, hfg] }, calc f = f ≫ prod.lift (𝟙 Y) 0 ≫ σ : by rw [lift_σ, category.comp_id] ... = prod.lift (𝟙 X) 0 ≫ limits.prod.map f f ≫ σ : by rw lift_map_assoc ... = prod.lift (𝟙 X) 0 ≫ σ ≫ g : by rw [←hg, cokernel_cofork.π_of_π] ... = g : by rw [←category.assoc, lift_σ, category.id_comp] end section /- We write `f - g` for `prod.lift f g ≫ σ`. -/ /-- Subtraction of morphisms in a `non_preadditive_abelian` category. -/ def has_sub {X Y : C} : has_sub (X ⟶ Y) := ⟨λ f g, prod.lift f g ≫ σ⟩ local attribute [instance] has_sub /- We write `-f` for `0 - f`. -/ /-- Negation of morphisms in a `non_preadditive_abelian` category. -/ def has_neg {X Y : C} : has_neg (X ⟶ Y) := ⟨λ f, 0 - f⟩ local attribute [instance] has_neg /- We write `f + g` for `f - (-g)`. -/ /-- Addition of morphisms in a `non_preadditive_abelian` category. -/ def has_add {X Y : C} : has_add (X ⟶ Y) := ⟨λ f g, f - (-g)⟩ local attribute [instance] has_add lemma sub_def {X Y : C} (a b : X ⟶ Y) : a - b = prod.lift a b ≫ σ := rfl lemma add_def {X Y : C} (a b : X ⟶ Y) : a + b = a - (-b) := rfl lemma neg_def {X Y : C} (a : X ⟶ Y) : -a = 0 - a := rfl lemma sub_zero {X Y : C} (a : X ⟶ Y) : a - 0 = a := begin rw sub_def, conv_lhs { congr, congr, rw ←category.comp_id a, skip, rw (show 0 = a ≫ (0 : Y ⟶ Y), by simp)}, rw [← prod.comp_lift, category.assoc, lift_σ, category.comp_id] end lemma sub_self {X Y : C} (a : X ⟶ Y) : a - a = 0 := by rw [sub_def, ←category.comp_id a, ← prod.comp_lift, category.assoc, diag_σ, comp_zero] lemma lift_sub_lift {X Y : C} (a b c d : X ⟶ Y) : prod.lift a b - prod.lift c d = prod.lift (a - c) (b - d) := begin simp only [sub_def], ext, { rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_fst, prod.lift_fst, prod.lift_fst] }, { rw [category.assoc, σ_comp, prod.lift_map_assoc, prod.lift_snd, prod.lift_snd, prod.lift_snd] } end lemma sub_sub_sub {X Y : C} (a b c d : X ⟶ Y) : (a - c) - (b - d) = (a - b) - (c - d) := begin rw [sub_def, ←lift_sub_lift, sub_def, category.assoc, σ_comp, prod.lift_map_assoc], refl end lemma neg_sub {X Y : C} (a b : X ⟶ Y) : (-a) - b = (-b) - a := by conv_lhs { rw [neg_def, ←sub_zero b, sub_sub_sub, sub_zero, ←neg_def] } lemma neg_neg {X Y : C} (a : X ⟶ Y) : -(-a) = a := begin rw [neg_def, neg_def], conv_lhs { congr, rw ←sub_self a }, rw [sub_sub_sub, sub_zero, sub_self, sub_zero] end lemma add_comm {X Y : C} (a b : X ⟶ Y) : a + b = b + a := begin rw [add_def], conv_lhs { rw ←neg_neg a }, rw [neg_def, neg_def, neg_def, sub_sub_sub], conv_lhs {congr, skip, rw [←neg_def, neg_sub] }, rw [sub_sub_sub, add_def, ←neg_def, neg_neg b, neg_def] end lemma add_neg {X Y : C} (a b : X ⟶ Y) : a + (-b) = a - b := by rw [add_def, neg_neg] lemma add_neg_self {X Y : C} (a : X ⟶ Y) : a + (-a) = 0 := by rw [add_neg, sub_self] lemma neg_add_self {X Y : C} (a : X ⟶ Y) : (-a) + a = 0 := by rw [add_comm, add_neg_self] lemma neg_sub' {X Y : C} (a b : X ⟶ Y) : -(a - b) = (-a) + b := begin rw [neg_def, neg_def], conv_lhs { rw ←sub_self (0 : X ⟶ Y) }, rw [sub_sub_sub, add_def, neg_def] end lemma neg_add {X Y : C} (a b : X ⟶ Y) : -(a + b) = (-a) - b := by rw [add_def, neg_sub', add_neg] lemma sub_add {X Y : C} (a b c : X ⟶ Y) : (a - b) + c = a - (b - c) := by rw [add_def, neg_def, sub_sub_sub, sub_zero] lemma add_assoc {X Y : C} (a b c : X ⟶ Y) : (a + b) + c = a + (b + c) := begin conv_lhs { congr, rw add_def }, rw [sub_add, ←add_neg, neg_sub', neg_neg] end lemma add_zero {X Y : C} (a : X ⟶ Y) : a + 0 = a := by rw [add_def, neg_def, sub_self, sub_zero] lemma comp_sub {X Y Z : C} (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g - h) = f ≫ g - f ≫ h := by rw [sub_def, ←category.assoc, prod.comp_lift, sub_def] lemma sub_comp {X Y Z : C} (f g : X ⟶ Y) (h : Y ⟶ Z) : (f - g) ≫ h = f ≫ h - g ≫ h := by rw [sub_def, category.assoc, σ_comp, ←category.assoc, prod.lift_map, sub_def] lemma comp_add (X Y Z : C) (f : X ⟶ Y) (g h : Y ⟶ Z) : f ≫ (g + h) = f ≫ g + f ≫ h := by rw [add_def, comp_sub, neg_def, comp_sub, comp_zero, add_def, neg_def] lemma add_comp (X Y Z : C) (f g : X ⟶ Y) (h : Y ⟶ Z) : (f + g) ≫ h = f ≫ h + g ≫ h := by rw [add_def, sub_comp, neg_def, sub_comp, zero_comp, add_def, neg_def] /-- Every `non_preadditive_abelian` category is preadditive. -/ def preadditive : preadditive C := { hom_group := λ X Y, { add := (+), add_assoc := add_assoc, zero := 0, zero_add := neg_neg, add_zero := add_zero, neg := λ f, -f, add_left_neg := neg_add_self, add_comm := add_comm }, add_comp' := add_comp, comp_add' := comp_add } end end end category_theory.non_preadditive_abelian
bc18f823dec532d02b5e681c4e9a61cb6e881c32
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/StxQuot.lean
ad77179062137d247806770e30d5d01155d4e209
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,189
lean
import Lean namespace Lean open Lean.Elab def run {α} [ToString α] : Unhygienic α → String := toString ∘ Unhygienic.run #eval run `(Nat.one) #eval run `($Syntax.missing) namespace Syntax #eval run `($missing) #eval run `($(missing)) #eval run `($(id Syntax.missing) + 1) #eval run $ let id := Syntax.missing; `($id + 1) end Syntax #eval run `(1 + 1) #eval run $ `(fun a => a) >>= pure #eval run $ `(def foo := 1) #eval run $ `(def foo := 1 def bar := 2) #eval run $ do let a ← `(Nat.one); `($a) #eval run $ do let a ← `(Nat.one); `(f $a $a) #eval run $ do let a ← `(Nat.one); `(f $ f $a 1) #eval run $ do let a ← `(Nat.one); `(f $(id a)) #eval run $ do let a ← `(Nat.one); `($(a).b) #eval run $ do let a ← `(1 + 2); match_syntax a with `($a + $b) => `($b + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1); match_syntax a with `($f:command) => pure f | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1 def bar := 2); match_syntax a with `($f:command $g:command) => `($g:command $f:command) | _ => pure Syntax.missing #eval run $ do let a ← `(aa); match_syntax a with `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let a ← `(1 + 2); match_syntax a with `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let params ← #[`(a), `((b : Nat))].mapM id; `(fun $params* => 1) #eval run $ do let a ← `(fun (a : Nat) b => c); match_syntax a with `(fun $aa* => $e) => pure aa | _ => pure #[] #eval run $ do let a ← `(∀ a, c); match_syntax a with `(∀ $id:ident, $e) => pure id | _ => pure a #eval run $ do let a ← `(∀ _, c); match_syntax a with `(∀ $id:ident, $e) => pure id | _ => pure a -- this one should NOT check the kind of the matched node #eval run $ do let a ← `(∀ _, c); match_syntax a with `(∀ $a, $e) => pure a | _ => pure a #eval run $ do let a ← `(a); match_syntax a with `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(a.{0}); match_syntax a with `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(match a with | a => 1 | _ => 2); match_syntax a with `(match $e with $eqns:matchAlt*) => pure eqns | _ => pure #[] end Lean
3da058ea70c045d7cfd1691feefef7630ddd808b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/integral_domain.lean
513514a40bf7f1dadd95ffca9f7dfdc4e026655e
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,031
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes -/ import data.fintype.card import data.polynomial.ring_division import group_theory.order_of_element import algebra.geom_sum /-! # Integral domains Assorted theorems about integral domains. ## Main theorems * `is_cyclic_of_subgroup_integral_domain` : A finite subgroup of the units of an integral domain is cyclic. * `field_of_integral_domain` : A finite integral domain is a field. ## Tags integral domain, finite integral domain, finite field -/ section open finset polynomial function open_locale big_operators nat variables {R : Type*} {G : Type*} [integral_domain R] [group G] [fintype G] lemma card_nth_roots_subgroup_units (f : G →* R) (hf : injective f) {n : ℕ} (hn : 0 < n) (g₀ : G) : ({g ∈ univ | g ^ n = g₀} : finset G).card ≤ (nth_roots n (f g₀)).card := begin haveI : decidable_eq R := classical.dec_eq _, refine le_trans _ (nth_roots n (f g₀)).to_finset_card_le, apply card_le_card_of_inj_on f, { intros g hg, rw [sep_def, mem_filter] at hg, rw [multiset.mem_to_finset, mem_nth_roots hn, ← f.map_pow, hg.2] }, { intros, apply hf, assumption } end /-- A finite subgroup of the unit group of an integral domain is cyclic. -/ lemma is_cyclic_of_subgroup_integral_domain (f : G →* R) (hf : injective f) : is_cyclic G := begin classical, apply is_cyclic_of_card_pow_eq_one_le, intros n hn, convert (le_trans (card_nth_roots_subgroup_units f hf hn 1) (card_nth_roots n (f 1))) end /-- The unit group of a finite integral domain is cyclic. -/ instance [fintype R] : is_cyclic (units R) := is_cyclic_of_subgroup_integral_domain (units.coe_hom R) $ units.ext /-- Every finite integral domain is a field. -/ def field_of_integral_domain [decidable_eq R] [fintype R] : field R := { inv := λ a, if h : a = 0 then 0 else fintype.bij_inv (show function.bijective (* a), from fintype.injective_iff_bijective.1 $ λ _ _, mul_right_cancel' h) 1, mul_inv_cancel := λ a ha, show a * dite _ _ _ = _, by rw [dif_neg ha, mul_comm]; exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1, inv_zero := dif_pos rfl, ..show integral_domain R, by apply_instance } section variables (S : set (units R)) [is_subgroup S] [fintype S] local attribute [instance] subtype.group /-- A finite subgroup of the units of an integral domain is cyclic. -/ instance subgroup_units_cyclic : is_cyclic S := begin refine is_cyclic_of_subgroup_integral_domain ⟨(coe : S → R), _, _⟩ (units.ext.comp subtype.val_injective), { simp only [is_submonoid.coe_one, units.coe_one, coe_coe] }, { intros, simp only [is_submonoid.coe_mul, units.coe_mul, coe_coe] }, end end lemma card_fiber_eq_of_mem_range {H : Type*} [group H] [decidable_eq H] (f : G →* H) {x y : H} (hx : x ∈ set.range f) (hy : y ∈ set.range f) : (univ.filter $ λ g, f g = x).card = (univ.filter $ λ g, f g = y).card := begin rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩, refine card_congr (λ g _, g * x⁻¹ * y) _ _ (λ g hg, ⟨g * y⁻¹ * x, _⟩), { simp only [mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, monoid_hom.map_mul_inv, and_self, forall_true_iff] {contextual := tt} }, { simp only [mul_left_inj, imp_self, forall_2_true_iff], }, { simp only [true_and, mem_filter, mem_univ] at hg, simp only [hg, mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv, eq_self_iff_true, exists_prop_of_true, monoid_hom.map_mul_inv, and_self, mul_inv_cancel_right, inv_mul_cancel_right], } end section local attribute [instance] subtype.group subtype.monoid range.is_submonoid /-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/ lemma sum_hom_units_eq_zero (f : G →* R) (hf : f ≠ 1) : ∑ g : G, f g = 0 := begin classical, obtain ⟨x, hx⟩ : ∃ x : set.range f.to_hom_units, ∀ y : set.range f.to_hom_units, y ∈ powers x, from is_cyclic.exists_monoid_generator, have hx1 : x ≠ 1, { rintro rfl, apply hf, ext g, rw [monoid_hom.one_apply], cases hx ⟨f.to_hom_units g, g, rfl⟩ with n hn, rwa [subtype.ext_iff, units.ext_iff, subtype.coe_mk, monoid_hom.coe_to_hom_units, is_submonoid.coe_pow, units.coe_pow, is_submonoid.coe_one, units.coe_one, one_pow, eq_comm] at hn, }, replace hx1 : (x : R) - 1 ≠ 0, from λ h, hx1 (subtype.eq (units.ext (sub_eq_zero.1 h))), let c := (univ.filter (λ g, f.to_hom_units g = 1)).card, calc ∑ g : G, f g = ∑ g : G, f.to_hom_units g : rfl ... = ∑ u : units R in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u : sum_comp (coe : units R → R) f.to_hom_units ... = ∑ u : units R in univ.image f.to_hom_units, c • u : sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below ... = ∑ b : set.range f.to_hom_units, c • ↑b : finset.sum_subtype _ (by simp only [mem_image, set.mem_range, forall_const, iff_self, mem_univ, exists_prop_of_true]) _ ... = c • ∑ b : set.range f.to_hom_units, (b : R) : smul_sum.symm ... = c • 0 : congr_arg2 _ rfl _ -- remaining goal 2, proven below ... = 0 : smul_zero _, { -- remaining goal 1 show (univ.filter (λ (g : G), f.to_hom_units g = u)).card = c, apply card_fiber_eq_of_mem_range f.to_hom_units, { simpa only [mem_image, mem_univ, exists_prop_of_true, set.mem_range] using hu, }, { exact ⟨1, f.to_hom_units.map_one⟩ } }, -- remaining goal 2 show ∑ b : set.range f.to_hom_units, (b : R) = 0, calc ∑ b : set.range f.to_hom_units, (b : R) = ∑ n in range (order_of x), x ^ n : eq.symm $ sum_bij (λ n _, x ^ n) (by simp only [mem_univ, forall_true_iff]) (by simp only [is_submonoid.coe_pow, eq_self_iff_true, units.coe_pow, coe_coe, forall_true_iff]) (λ m n hm hn, pow_injective_of_lt_order_of _ (by simpa only [mem_range] using hm) (by simpa only [mem_range] using hn)) (λ b hb, let ⟨n, hn⟩ := hx b in ⟨n % order_of x, mem_range.2 (nat.mod_lt _ (order_of_pos _)), by rw [← pow_eq_mod_order_of, hn]⟩) ... = 0 : _, rw [← mul_left_inj' hx1, zero_mul, ← geom_sum, geom_sum_mul, coe_coe], norm_cast, rw [pow_order_of_eq_one, is_submonoid.coe_one, units.coe_one, sub_self], end end /-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero, unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/ lemma sum_hom_units (f : G →* R) [decidable (f = 1)] : ∑ g : G, f g = if f = 1 then fintype.card G else 0 := begin split_ifs with h h, { simp [h, card_univ] }, { exact sum_hom_units_eq_zero f h } end end
dc1064d5eb9ed8a13f89870d5518f9c5dc34abb9
ac89c256db07448984849346288e0eeffe8b20d0
/src/Lean/Meta/SynthInstance.lean
c2a20250fffa58d2e2798255005504ba6d55c5e9
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,318
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ import Lean.Meta.Basic import Lean.Meta.Instances import Lean.Meta.LevelDefEq import Lean.Meta.AbstractMVars import Lean.Meta.WHNF import Lean.Util.Profile namespace Lean.Meta register_builtin_option synthInstance.maxHeartbeats : Nat := { defValue := 500 descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } register_builtin_option synthInstance.maxSize : Nat := { defValue := 128 descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure" } namespace SynthInstance def getMaxHeartbeats (opts : Options) : Nat := synthInstance.maxHeartbeats.get opts * 1000 open Std (HashMap) builtin_initialize inferTCGoalsRLAttr : TagAttribute ← registerTagAttribute `inferTCGoalsRL "instruct type class resolution procedure to solve goals from right to left for this instance" def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsRLAttr.hasTag env constName structure GeneratorNode where mvar : Expr key : Expr mctx : MetavarContext instances : Array Expr currInstanceIdx : Nat deriving Inhabited structure ConsumerNode where mvar : Expr key : Expr mctx : MetavarContext subgoals : List Expr size : Nat -- instance size so far deriving Inhabited inductive Waiter where | consumerNode : ConsumerNode → Waiter | root : Waiter def Waiter.isRoot : Waiter → Bool | Waiter.consumerNode _ => false | Waiter.root => true /- In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State where nextIdx : Nat := 0 lmap : HashMap MVarId Level := {} emap : HashMap MVarId Expr := {} abbrev M := ReaderT MetavarContext (StateM State) partial def normLevel (u : Level) : M Level := do if !u.hasMVar then pure u else match u with | Level.succ v _ => return u.updateSucc! (← normLevel v) | Level.max v w _ => return u.updateMax! (← normLevel v) (← normLevel w) | Level.imax v w _ => return u.updateIMax! (← normLevel v) (← normLevel w) | Level.mvar mvarId _ => let mctx ← read if !mctx.isLevelAssignable mvarId then pure u else let s ← get match s.lmap.find? mvarId with | some u' => pure u' | none => let u' := mkLevelParam $ Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' } pure u' | u => pure u partial def normExpr (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.const _ us _ => return e.updateConst! (← us.mapM normLevel) | Expr.sort u _ => return e.updateSort! (← normLevel u) | Expr.app f a _ => return e.updateApp! (← normExpr f) (← normExpr a) | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b) | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b) | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b) | Expr.mdata _ b _ => return e.updateMData! (← normExpr b) | Expr.proj _ _ b _ => return e.updateProj! (← normExpr b) | Expr.mvar mvarId _ => let mctx ← read if !mctx.isExprAssignable mvarId then pure e else let s ← get match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar $ Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' } pure e' | _ => pure e end MkTableKey /- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr := MkTableKey.normExpr e mctx |>.run' {} structure Answer where result : AbstractMVarsResult resultType : Expr size : Nat instance : Inhabited Answer where default := { result := arbitrary, resultType := arbitrary, size := 0 } structure TableEntry where waiters : Array Waiter answers : Array Answer := #[] structure Context where maxResultSize : Nat maxHeartbeats : Nat /- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State where result : Option Expr := none generatorStack : Array GeneratorNode := #[] resumeStack : Array (ConsumerNode × Answer) := #[] tableEntries : HashMap Expr TableEntry := {} abbrev SynthM := ReaderT Context $ StateRefT State MetaM def checkMaxHeartbeats : SynthM Unit := do Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats @[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α := monadMap @f instance : Inhabited (SynthM α) where default := fun _ _ => arbitrary /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := do -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances let localInstances ← getLocalInstances forallTelescopeReducing type fun _ type => do let className? ← isClass? type match className? with | none => throwError "type class instance expected{indentExpr type}" | some className => let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type -- Using insertion sort because it is stable and the array `result` should be mostly sorted. -- Most instances have default priority. let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority let result ← result.mapM fun e => match e.val with | Expr.const constName us _ => return e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar)) | _ => panic! "global instance is not a constant" trace[Meta.synthInstance.globalInstances] "{type}, {result}" let result := localInstances.foldl (init := result) fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result pure result def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType let instances ← getInstances mvarType if instances.isEmpty then pure none else let mctx ← getMCtx pure $ some { mvar := mvar, key := key, mctx := mctx, instances := instances, currInstanceIdx := instances.size } /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx do trace[Meta.synthInstance.newSubgoal] key match (← mkGeneratorNode? key mvar) with | none => pure () | some node => let entry : TableEntry := { waiters := #[waiter] } modify fun s => { s with generatorStack := s.generatorStack.push node, tableEntries := s.tableEntries.insert key entry } def findEntry? (key : Expr) : SynthM (Option TableEntry) := do return (← get).tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do match (← findEntry? key) with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType return mkTableKey mctx mvarType /- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult where subgoals : List Expr instVal : Expr instTypeBody : Expr private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args let mvarType ← mkForallFVars xs d let mvar ← mkFreshExprMVarAt lctx localInsts mvarType let arg := mkAppN mvar xs let instVal := mkApp instVal arg let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals let args := args.push (mkAppN mvar xs) getSubgoalsAux lctx localInsts xs args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args let type ← whnf type if type.isForall then getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type else pure ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do let instType ← inferType inst let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType match inst.getAppFn with | Expr.const constName _ _ => let env ← getEnv if hasInferTCGoalsRLAttribute env constName then pure result else pure { result with subgoals := result.subgoals.reverse } | _ => pure result def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do let mvar ← instantiateMVars mvar if !(← hasAssignableMVar mvar) then /- The metavariable `mvar` may have been assinged when solving typing constraints. This may happen when a local instance type depends on other local instances. For example, in Mathlib, we have ``` @Submodule.setLike : {R : Type u_1} → {M : Type u_2} → [_inst_1 : Semiring R] → [_inst_2 : AddCommMonoid M] → [_inst_3 : @ModuleS R M _inst_1 _inst_2] → SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M ``` TODO: discuss what is the correct behavior here. There are other possibilities. 1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check whether it is defeq to the one inferred by typing constraints. That is, we remove this `if`-statement. We discarded this one because some Mathlib theorems failed to be elaborated using it. 2) Generate an error/warning message when instances such as `Submodule.setLike` are declared, and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`. -/ return some ((← getMCtx), []) let mvarType ← inferType mvar let lctx ← getLCtx let localInsts ← getLocalInstances forallTelescopeReducing mvarType fun xs mvarTypeBody => do let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst trace[Meta.synthInstance.tryResolve] "{mvarTypeBody} =?= {instTypeBody}" if (← isDefEq mvarTypeBody instTypeBody) then let instVal ← mkLambdaFVars xs instVal if (← isDefEq mvar instVal) then trace[Meta.synthInstance.tryResolve] "success" pure (some ((← getMCtx), subgoals)) else trace[Meta.synthInstance.tryResolve] "failure assigning" pure none else trace[Meta.synthInstance.tryResolve] "failure" pure none /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` contains `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) := traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx do let (_, _, val) ← openAbstractMVarsResult answer.result if (← isDefEq mvar val) then pure (some (← getMCtx)) else pure none /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter → SynthM Unit | Waiter.root => do if answer.result.paramNames.isEmpty && answer.result.numMVars == 0 then modify fun s => { s with result := answer.result.expr } else let (_, _, answerExpr) ← openAbstractMVarsResult answer.result trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}" pure () | Waiter.consumerNode cNode => modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all fun oldAnswer => do -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType private def mkAnswer (cNode : ConsumerNode) : MetaM Answer := withMCtx cNode.mctx do traceM `Meta.synthInstance.newAnswer do m!"size: {cNode.size}, {← inferType cNode.mvar}" let val ← instantiateMVars cNode.mvar trace[Meta.synthInstance.newAnswer] "val: {val}" let result ← abstractMVars val -- assignable metavariables become parameters let resultType ← inferType result.expr pure { result := result, resultType := resultType, size := cNode.size + 1 } /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do if cNode.size ≥ (← read).maxResultSize then traceM `Meta.synthInstance.discarded do m!"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}" return () else let answer ← mkAnswer cNode -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key let entry ← getEntry key if isNewAnswer entry.answers answer then let newEntry := { entry with answers := entry.answers.push answer } modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry } entry.waiters.forM (wakeUp answer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => do let waiter := Waiter.consumerNode cNode let key ← mkTableKeyFor cNode.mctx mvar let entry? ← findEntry? key match entry? with | none => newSubgoal cNode.mctx key mvar waiter | some entry => modify fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := do pure (← get).generatorStack.back @[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit := modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do let gNode ← getTop if gNode.currInstanceIdx == 0 then modify fun s => { s with generatorStack := s.generatorStack.pop } else do let key := gNode.key let idx := gNode.currInstanceIdx - 1 let inst := gNode.instances.get! idx let mctx := gNode.mctx let mvar := gNode.mvar trace[Meta.synthInstance.generate] "instance {inst}" modifyTop fun gNode => { gNode with currInstanceIdx := idx } match (← tryResolve mctx mvar inst) with | none => pure () | some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx, size := 0 } def getNextToResume : SynthM (ConsumerNode × Answer) := do let s ← get let r := s.resumeStack.back modify fun s => { s with resumeStack := s.resumeStack.pop } pure r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do let (cNode, answer) ← getNextToResume match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => match (← tryAnswer cNode.mctx mvar answer) with | none => pure () | some mctx => withMCtx mctx <| traceM `Meta.synthInstance.resume do let goal ← inferType cNode.mvar let subgoal ← inferType mvar pure m!"size: {cNode.size + answer.size}, {goal} <== {subgoal}" consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx, size := cNode.size + answer.size } def step : SynthM Bool := do checkMaxHeartbeats let s ← get if !s.resumeStack.isEmpty then resume pure true else if !s.generatorStack.isEmpty then generate pure true else pure false def getResult : SynthM (Option Expr) := do pure (← get).result partial def synth : SynthM (Option Expr) := do if (← step) then match (← getResult) with | none => synth | some result => pure result else trace[Meta.synthInstance] "failed" pure none def main (type : Expr) (maxResultSize : Nat) : MetaM (Option Expr) := withCurrHeartbeats <| traceCtx `Meta.synthInstance do trace[Meta.synthInstance] "main goal {type}" let mvar ← mkFreshExprMVar type let mctx ← getMCtx let key := mkTableKey mctx type let action : SynthM (Option Expr) := do newSubgoal mctx key mvar Waiter.root synth action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {} end SynthInstance /- Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type fun xs type => do let type ← whnf type mkForallFVars xs type private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do let mut r := #[] let mut modified := false for u in us do let u ← instantiateLevelMVars u if u.hasMVar then r := r.push (← mkFreshLevelMVar) modified := true else r := r.push u return (r.toList, modified) private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do if h : i < args.size then let type ← whnf type match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩ let arg ← if isOutParam d then mkFreshExprMVar d else pure arg let args := args.set ⟨i, h⟩ arg preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message else return args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type fun xs typeBody => do match typeBody.getAppFn with | c@(Expr.const constName us _) => let env ← getEnv if !hasOutParams env constName then /- We treat all universe level parameters as "outParam" -/ let (us, modified) ← preprocessLevels us if modified then let c := mkConst constName us mkForallFVars xs (mkAppN c typeBody.getAppArgs) else return type else do let args := typeBody.getAppArgs let (us, _) ← preprocessLevels us let c := mkConst constName us let cType ← inferType c let args ← preprocessArgs cType 0 args mkForallFVars xs (mkAppN c args) | _ => return type /- Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used. Remark: we use a different option for controlling the maximum result size for coercions. -/ def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do let opts ← getOptions let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts) let inputConfig ← getConfig withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances, foApprox := true, ctxApprox := true, constApprox := false }) do let type ← instantiateMVars type let type ← preprocess type let s ← get match s.cache.synthInstance.find? type with | some result => pure result | none => let result? ← withNewMCtxDepth do let normType ← preprocessOutParam type trace[Meta.synthInstance] "{type} ==> {normType}" match (← SynthInstance.main normType maxResultSize) with | none => pure none | some result => trace[Meta.synthInstance] "FOUND result {result}" let result ← instantiateMVars result if (← hasAssignableMVar result) then trace[Meta.synthInstance] "Failed has assignable mvar {result.setOption `pp.all true}" pure none else pure (some result) let result? ← match result? with | none => pure none | some result => do trace[Meta.synthInstance] "result {result}" let resultType ← inferType result if (← withConfig (fun _ => inputConfig) <| isDefEq type resultType) then let result ← instantiateMVars result pure (some result) else trace[Meta.synthInstance] "result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}" pure none if type.hasMVar then pure result? else do modify fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } } pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do catchInternalId isDefEqStuckExceptionId (toLOptionM <| synthInstance? type maxResultSize?) (fun _ => pure LOption.undef) def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr := catchInternalId isDefEqStuckExceptionId (do let result? ← synthInstance? type maxResultSize? match result? with | some result => pure result | none => throwError "failed to synthesize{indentExpr type}") (fun _ => throwError "failed to synthesize{indentExpr type}") @[export lean_synth_pending] private def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => return false | _ => /- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/ match (← isClass? mvarDecl.type) with | none => return false | some _ => /- TODO: use a configuration option instead of the hard-coded limit `1`. -/ if (← read).synthPendingDepth > 1 then trace[Meta.synthPending] "too many nested synthPending invocations" return false else withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do trace[Meta.synthPending] "synthPending {mkMVar mvarId}" let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none) match val? with | none => return false | some val => if (← isExprMVarAssigned mvarId) then return false else assignExprMVar mvarId val return true builtin_initialize registerTraceClass `Meta.synthInstance registerTraceClass `Meta.synthInstance.globalInstances registerTraceClass `Meta.synthInstance.newSubgoal registerTraceClass `Meta.synthInstance.tryResolve registerTraceClass `Meta.synthInstance.resume registerTraceClass `Meta.synthInstance.generate registerTraceClass `Meta.synthPending end Lean.Meta
abd91add6b98c8124699785588d8841c5a468fc5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/convex/basic.lean
e037d194855428a353a2b3140850a7e165e2c6e6
[ "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
39,825
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies -/ import algebra.order.module import linear_algebra.affine_space.affine_subspace /-! # Convex sets and functions in vector spaces In a 𝕜-vector space, we define the following objects and properties. * `segment 𝕜 x y`: Closed segment joining `x` and `y`. * `open_segment 𝕜 x y`: Open segment joining `x` and `y`. * `convex 𝕜 s`: A set `s` is convex if for any two points `x y ∈ s` it includes `segment 𝕜 x y`. * `std_simplex 𝕜 ι`: The standard simplex in `ι → 𝕜` (currently requires `fintype ι`). It is the intersection of the positive quadrant with the hyperplane `s.sum = 1`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex. ## Notations We provide the following notation: * `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex` ## TODO Generalize all this file to affine spaces. Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also define `clopen_segment`/`convex.Ico`/`convex.Ioc`? -/ variables {𝕜 E F β : Type*} open linear_map set open_locale big_operators classical pointwise /-! ### Segment -/ section ordered_semiring variables [ordered_semiring 𝕜] [add_comm_monoid E] section has_scalar variables (𝕜) [has_scalar 𝕜 E] /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} /-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when the base semiring has some element between `0` and `1`. -/ def open_segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} localized "notation `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_symm (x y : E) : open_segment 𝕜 x y = open_segment 𝕜 y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_subset_segment (x y : E) : open_segment 𝕜 x y ⊆ [x -[𝕜] y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ end has_scalar open_locale convex section mul_action_with_zero variables (𝕜) [mul_action_with_zero 𝕜 E] lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] := segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x end mul_action_with_zero section module variables (𝕜) [module 𝕜 E] lemma segment_same (x : E) : [x -[𝕜] x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩ lemma mem_open_segment_of_ne_left_right {x y z : E} (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) : z ∈ open_segment 𝕜 x y := begin obtain ⟨a, b, ha, hb, hab, hz⟩ := hz, by_cases ha' : a = 0, { rw [ha', zero_add] at hab, rw [ha', hab, zero_smul, one_smul, zero_add] at hz, exact (hy hz).elim }, by_cases hb' : b = 0, { rw [hb', add_zero] at hab, rw [hb', hab, zero_smul, one_smul, add_zero] at hz, exact (hx hz).elim }, exact ⟨a, b, ha.lt_of_ne (ne.symm ha'), hb.lt_of_ne (ne.symm hb'), hab, hz⟩, end variables {𝕜} lemma open_segment_subset_iff_segment_subset {x y : E} {s : set E} (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s := begin refine ⟨λ h z hz, _, (open_segment_subset_segment 𝕜 x y).trans⟩, obtain rfl | hxz := eq_or_ne x z, { exact hx }, obtain rfl | hyz := eq_or_ne y z, { exact hy }, exact h (mem_open_segment_of_ne_left_right 𝕜 hxz hyz hz), end lemma convex.combo_self {a b : 𝕜} (h : a + b = 1) (x : E) : a • x + b • x = x := by rw [←add_smul, h, one_smul] end module end ordered_semiring open_locale convex section ordered_ring variables [ordered_ring 𝕜] section add_comm_group variables (𝕜) [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section densely_ordered variables [nontrivial 𝕜] [densely_ordered 𝕜] @[simp] lemma open_segment_same (x : E) : open_segment 𝕜 x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ (h : z = x), begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩, rw [←add_smul, add_sub_cancel'_right, one_smul, h], end⟩ end densely_ordered lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image₂ (x y : E) : [x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma open_segment_eq_image₂ (x y : E) : open_segment 𝕜 x y = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_image' (x y : E) : [x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 := by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image' (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 := by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] := set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) @[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) := set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] := set.ext $ λ x, mem_segment_translate 𝕜 a lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c := set.ext $ λ x, mem_open_segment_translate 𝕜 a lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] := segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) := open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] @[simp] lemma left_mem_open_segment_iff [no_zero_smul_divisors 𝕜 E] {x y : E} : x ∈ open_segment 𝕜 x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, { rintro rfl, rw open_segment_same, exact mem_singleton _ } end @[simp] lemma right_mem_open_segment_iff {x y : E} : y ∈ open_segment 𝕜 x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] end add_comm_group end linear_ordered_field /-! #### Segments in an ordered space Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo` -/ section ordered_semiring variables [ordered_semiring 𝕜] section ordered_add_comm_monoid variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] lemma segment_subset_Icc {x y : E} (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x :(convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _ ... = y : convex.combo_self hab _, end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] lemma open_segment_subset_Ioo {x y : E} (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x : (convex.combo_self hab _).symm ... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _, calc a • x + b • y < a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _ ... = y : convex.combo_self hab _, end end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜} lemma segment_subset_interval (x y : E) : [x -[𝕜] y] ⊆ interval x y := begin cases le_total x y, { rw interval_of_le h, exact segment_subset_Icc h }, { rw [interval_of_ge h, segment_symm], exact segment_subset_Icc h } end lemma convex.min_le_combo (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min x y ≤ a • x + b • y := (segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).1 lemma convex.combo_le_max (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ≤ max x y := (segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).2 end linear_ordered_add_comm_monoid end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] lemma Icc_subset_segment {x y : 𝕜} : Icc x y ⊆ [x -[𝕜] y] := begin rintro z ⟨hxz, hyz⟩, obtain rfl | h := (hxz.trans hyz).eq_or_lt, { rw segment_same, exact hyz.antisymm hxz }, rw ←sub_nonneg at hxz hyz, rw ←sub_pos at h, refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩, { rw [←add_div, sub_add_sub_cancel, div_self h.ne'] }, { rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div, div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] } end @[simp] lemma segment_eq_Icc {x y : 𝕜} (h : x ≤ y) : [x -[𝕜] y] = Icc x y := (segment_subset_Icc h).antisymm Icc_subset_segment lemma Ioo_subset_open_segment {x y : 𝕜} : Ioo x y ⊆ open_segment 𝕜 x y := λ z hz, mem_open_segment_of_ne_left_right _ hz.1.ne hz.2.ne' (Icc_subset_segment $ Ioo_subset_Icc_self hz) @[simp] lemma open_segment_eq_Ioo {x y : 𝕜} (h : x < y) : open_segment 𝕜 x y = Ioo x y := (open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) := begin cases le_total x y, { rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] }, { rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] } end lemma open_segment_eq_Ioo' {x y : 𝕜} (hxy : x ≠ y) : open_segment 𝕜 x y = Ioo (min x y) (max x y) := begin cases hxy.lt_or_lt, { rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] }, { rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] } end lemma segment_eq_interval (x y : 𝕜) : [x -[𝕜] y] = interval x y := segment_eq_Icc' _ _ /-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {x y : 𝕜} (h : x ≤ y) {z : 𝕜} : z ∈ Icc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←segment_eq_Icc h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints. -/ lemma convex.mem_Ioo {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioo x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←open_segment_eq_Ioo h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ioc {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz), obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rw [hab, one_mul, zero_mul, add_zero] at hz, exact (hz.1.ne rfl).elim }, { exact ⟨a, b, ha, hb', hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] }, { exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } } end /-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ico {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ico x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz), obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rw [hab, one_mul, zero_mul, zero_add] at hz, exact (hz.2.ne rfl).elim }, { exact ⟨a, b, ha', hb, hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] }, { exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } } end end linear_ordered_field /-! ### Convexity of sets -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_scalar variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 F] (s : set E) /-- Convexity of sets. -/ def convex : Prop := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s variables {𝕜 s} lemma convex_iff_segment_subset : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x -[𝕜] y] ⊆ s := begin split, { rintro h x y hx hy z ⟨a, b, ha, hb, hab, rfl⟩, exact h hx hy ha hb hab }, { rintro h x y hx hy a b ha hb hab, exact h hx hy ⟨a, b, ha, hb, hab, rfl⟩ } end lemma convex.segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x -[𝕜] y] ⊆ s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s := (open_segment_subset_segment 𝕜 x y).trans (h.segment_subset hx hy) /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset : convex 𝕜 s ↔ ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintro hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) lemma convex_empty : convex 𝕜 (∅ : set E) := by finish lemma convex_univ : convex 𝕜 (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex 𝕜 s) : convex 𝕜 (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i : ι, convex 𝕜 (s i)) : convex 𝕜 (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex_pi {ι : Type*} {E : ι → Type*} [Π i, add_comm_monoid (E i)] [Π i, has_scalar 𝕜 (E i)] {s : set ι} {t : Π i, set (E i)} (ht : ∀ i, convex 𝕜 (t i)) : convex 𝕜 (s.pi t) := λ x y hx hy a b ha hb hab i hi, ht i (hx i hi) (hy i hi) ha hb hab lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hc : ∀ ⦃i : ι⦄, convex 𝕜 (s i)) : convex 𝕜 (⋃ i, s i) := begin rintro x y hx hy a b ha hb hab, rw mem_Union at ⊢ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on (⊆) c) (hc : ∀ ⦃A : set E⦄, A ∈ c → convex 𝕜 A) : convex 𝕜 (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2), end end has_scalar section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex_iff_forall_pos : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy ha.le hb.le hab, _⟩, intros h x y hx hy a b ha hb hab, cases ha.eq_or_lt with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases hb.eq_or_lt with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_pairwise_pos : convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s) := begin refine ⟨λ h x hx y hy _ a b ha hb hab, h hx hy ha.le hb.le hab, _⟩, intros h x y hx hy a b ha hb hab, obtain rfl | ha' := ha.eq_or_lt, { rw [zero_add] at hab, rwa [hab, zero_smul, one_smul, zero_add] }, obtain rfl | hb' := hb.eq_or_lt, { rw [add_zero] at hab, rwa [hab, zero_smul, one_smul, add_zero] }, obtain rfl | hxy := eq_or_ne x y, { rwa convex.combo_self hab }, exact h _ hx _ hy hxy ha' hb' hab, end lemma convex_iff_open_segment_subset : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment 𝕜 x y ⊆ s := begin rw convex_iff_segment_subset, exact forall₂_congr (λ x y, forall₂_congr $ λ hx hy, (open_segment_subset_iff_segment_subset hx hy).symm), end lemma convex_singleton (c : E) : convex 𝕜 ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex.linear_image (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (s.image f) := begin intros x y hx hy a b ha hb hab, obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx, obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy, exact ⟨a • x' + b • y', hs hx' hy' ha hb hab, by rw [f.map_add, f.map_smul, f.map_smul]⟩, end lemma convex.is_linear_image (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) : convex 𝕜 (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (s.preimage f) := begin intros x y hx hy a b ha hb hab, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy ha hb hab, end lemma convex.is_linear_preimage {s : set F} (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) : convex 𝕜 (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.add {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.translate (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) '' s) := begin intros x y hx hy a b ha hb hab, obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx, obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy, refine ⟨a • x' + b • y', hs hx' hy' ha hb hab, _⟩, rw [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul], end /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x y hx hy a b ha hb hab, have h := hs hx hy ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right z section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_Iic (r : β) : convex 𝕜 (Iic r) := λ x y hx hy a b ha hb hab, calc a • x + b • y ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx ha) (smul_le_smul_of_nonneg hy hb) ... = r : convex.combo_self hab _ lemma convex_Ici (r : β) : convex 𝕜 (Ici r) := @convex_Iic 𝕜 (order_dual β) _ _ _ _ r lemma convex_Icc (r s : β) : convex 𝕜 (Icc r s) := Ici_inter_Iic.subst ((convex_Ici r).inter $ convex_Iic s) lemma convex_halfspace_le {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_ge {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w = r} := begin simp_rw le_antisymm_iff, exact (convex_halfspace_le h r).inter (convex_halfspace_ge h r), end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_Iio (r : β) : convex 𝕜 (Iio r) := begin intros x y hx hy a b ha hb hab, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [zero_smul, zero_add, hab, one_smul] }, rw mem_Iio at hx hy, calc a • x + b • y < a • r + b • r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb) ... = r : convex.combo_self hab _ end lemma convex_Ioi (r : β) : convex 𝕜 (Ioi r) := @convex_Iio 𝕜 (order_dual β) _ _ _ _ r lemma convex_Ioo (r s : β) : convex 𝕜 (Ioo r s) := Ioi_inter_Iio.subst ((convex_Ioi r).inter $ convex_Iio s) lemma convex_Ico (r s : β) : convex 𝕜 (Ico r s) := Ici_inter_Iio.subst ((convex_Ici r).inter $ convex_Iio s) lemma convex_Ioc (r s : β) : convex 𝕜 (Ioc r s) := Ioi_inter_Iic.subst ((convex_Ioi r).inter $ convex_Iic s) lemma convex_halfspace_lt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_gt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | r < f w} := (convex_Ioi r).is_linear_preimage h end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_interval (r s : β) : convex 𝕜 (interval r s) := convex_Icc _ _ end linear_ordered_add_comm_monoid end module end add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} {f : E → β} lemma monotone_on.convex_le (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | f x ≤ r} := λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab, (hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans (max_rec' _ hx.2 hy.2)⟩ lemma monotone_on.convex_lt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | f x < r} := λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab, (hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans_lt (max_rec' _ hx.2 hy.2)⟩ lemma monotone_on.convex_ge (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | r ≤ f x} := @monotone_on.convex_le 𝕜 (order_dual E) (order_dual β) _ _ _ _ _ _ _ hf.dual hs r lemma monotone_on.convex_gt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | r < f x} := @monotone_on.convex_lt 𝕜 (order_dual E) (order_dual β) _ _ _ _ _ _ _ hf.dual hs r lemma antitone_on.convex_le (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | f x ≤ r} := @monotone_on.convex_ge 𝕜 E (order_dual β) _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_lt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | f x < r} := @monotone_on.convex_gt 𝕜 E (order_dual β) _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_ge (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | r ≤ f x} := @monotone_on.convex_le 𝕜 E (order_dual β) _ _ _ _ _ _ _ hf hs r lemma antitone_on.convex_gt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) : convex 𝕜 {x ∈ s | r < f x} := @monotone_on.convex_lt 𝕜 E (order_dual β) _ _ _ _ _ _ _ hf hs r lemma monotone.convex_le (hf : monotone f) (r : β) : convex 𝕜 {x | f x ≤ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma monotone.convex_lt (hf : monotone f) (r : β) : convex 𝕜 {x | f x ≤ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma monotone.convex_ge (hf : monotone f ) (r : β) : convex 𝕜 {x | r ≤ f x} := set.sep_univ.subst ((hf.monotone_on univ).convex_ge convex_univ r) lemma monotone.convex_gt (hf : monotone f) (r : β) : convex 𝕜 {x | f x ≤ r} := set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r) lemma antitone.convex_le (hf : antitone f) (r : β) : convex 𝕜 {x | f x ≤ r} := set.sep_univ.subst ((hf.antitone_on univ).convex_le convex_univ r) lemma antitone.convex_lt (hf : antitone f) (r : β) : convex 𝕜 {x | f x < r} := set.sep_univ.subst ((hf.antitone_on univ).convex_lt convex_univ r) lemma antitone.convex_ge (hf : antitone f) (r : β) : convex 𝕜 {x | r ≤ f x} := set.sep_univ.subst ((hf.antitone_on univ).convex_ge convex_univ r) lemma antitone.convex_gt (hf : antitone f) (r : β) : convex 𝕜 {x | r < f x} := set.sep_univ.subst ((hf.antitone_on univ).convex_gt convex_univ r) end linear_ordered_add_comm_monoid section add_comm_group variables [add_comm_group E] [module 𝕜 E] {s t : set E} lemma convex.combo_eq_vadd {a b : 𝕜} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h] lemma convex.sub (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 ((λ x : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex_segment (x y : E) : convex 𝕜 [x -[𝕜] y] := begin rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ a b ha hb hab, refine ⟨a * ap + b * aq, a * bp + b * bq, add_nonneg (mul_nonneg ha hap) (mul_nonneg hb haq), add_nonneg (mul_nonneg ha hbp) (mul_nonneg hb hbq), _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add], exact add_add_add_comm _ _ _ _ } end lemma convex_open_segment (a b : E) : convex 𝕜 (open_segment 𝕜 a b) := begin rw convex_iff_open_segment_subset, rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ z ⟨a, b, ha, hb, hab, rfl⟩, refine ⟨a * ap + b * aq, a * bp + b * bq, add_pos (mul_pos ha hap) (mul_pos hb haq), add_pos (mul_pos ha hbp) (mul_pos hb hbq), _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add], exact add_add_add_comm _ _ _ _ } end end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex.smul (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.affinity (hs : convex 𝕜 s) (z : E) (c : 𝕜) : convex 𝕜 ((λ x, z + c • x) '' s) := begin have h := (hs.smul c).translate z, rwa [←image_smul, image_image] at h, end end add_comm_monoid end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex.add_smul_mem (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • y ∈ s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, exact hs hx hy (sub_nonneg_of_le ht.2) ht.1 (sub_add_cancel _ _), end lemma convex.smul_mem_of_zero_mem (hs : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : t • x ∈ s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.add_smul_sub_mem (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', exact mem_image_of_mem _ ht, end /-- Affine subspaces are convex. -/ lemma affine_subspace.convex (Q : affine_subspace 𝕜 E) : convex 𝕜 (Q : set E) := begin intros x y hx hy a b ha hb hab, rw [eq_sub_of_add_eq hab, ← affine_map.line_map_apply_module], exact affine_map.line_map_mem b hx hy, end /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : 𝕜} {x y : E} {f : E →ᵃ[𝕜] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_eq_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[𝕜] F) {s : set F} (hs : convex 𝕜 s) : convex 𝕜 (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[𝕜] F) {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (f '' s) := begin rintro x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.neg (hs : convex 𝕜 s) : convex 𝕜 ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex 𝕜 s) : convex 𝕜 ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div : convex 𝕜 s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨λ h x y hx hy a b ha hb hab, begin apply h hx hy, { have ha', from mul_le_mul_of_nonneg_left ha (inv_pos.2 hab).le, rwa [mul_zero, ←div_eq_inv_mul] at ha' }, { have hb', from mul_le_mul_of_nonneg_left hb (inv_pos.2 hab).le, rwa [mul_zero, ←div_eq_inv_mul] at hb' }, { rw ←add_div, exact div_self hab.ne' } end, λ h x y hx hy a b ha hb hab, begin have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ lemma convex.mem_smul_of_zero_mem (h : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : 𝕜} (ht : 1 ≤ t) : x ∈ t • s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end lemma convex.add_smul (h_conv : convex 𝕜 s) {p q : 𝕜} (hp : 0 ≤ p) (hq : 0 ≤ q) : (p + q) • s = p • s + q • s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty, add_empty] }, obtain rfl | hp' := hp.eq_or_lt, { rw [zero_add, zero_smul_set hs, zero_add] }, obtain rfl | hq' := hq.eq_or_lt, { rw [add_zero, zero_smul_set hs, add_zero] }, ext, split, { rintro ⟨v, hv, rfl⟩, exact ⟨p • v, q • v, smul_mem_smul_set hv, smul_mem_smul_set hv, (add_smul _ _ _).symm⟩ }, { rintro ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩, have hpq := add_pos hp' hq', exact mem_smul_set.2 ⟨_, h_conv h₁₂ h₂₂ (div_pos hp' hpq).le (div_pos hq' hpq).le (by rw [←div_self hpq.ne', add_div] : p / (p + q) + q / (p + q) = 1), by simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne']⟩ } end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `ord_connected`. -/ section lemma set.ord_connected.convex_of_chain [ordered_semiring 𝕜] [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) (h : zorn.chain (≤) s) : convex 𝕜 s := begin intros x y hx hy a b ha hb hab, obtain hxy | hyx := h.total_of_refl hx hy, { refine hs.out hx hy (mem_Icc.2 ⟨_, _⟩), calc x = a • x + b • x : (convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg hxy hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg hxy ha) _ ... = y : convex.combo_self hab _ }, { refine hs.out hy hx (mem_Icc.2 ⟨_, _⟩), calc y = a • y + b • y : (convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_right (smul_le_smul_of_nonneg hyx ha) _, calc a • x + b • y ≤ a • x + b • x : add_le_add_left (smul_le_smul_of_nonneg hyx hb) _ ... = x : convex.combo_self hab _ } end lemma set.ord_connected.convex [ordered_semiring 𝕜] [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) : convex 𝕜 s := hs.convex_of_chain (zorn.chain_of_trichotomous s) lemma convex_iff_ord_connected [linear_ordered_field 𝕜] {s : set 𝕜} : convex 𝕜 s ↔ s.ord_connected := begin simp_rw [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias convex_iff_ord_connected ↔ convex.ord_connected _ end /-! #### Convexity of submodules/subspaces -/ section submodule open submodule lemma submodule.convex [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] (K : submodule 𝕜 E) : convex 𝕜 (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] (K : subspace 𝕜 E) : convex 𝕜 (↑K : set E) := K.convex end submodule /-! ### Simplex -/ section simplex variables (𝕜) (ι : Type*) [ordered_semiring 𝕜] [fintype ι] /-- The standard simplex in the space of functions `ι → 𝕜` is the set of vectors with non-negative coordinates with total sum `1`. This is the free object in the category of convex spaces. -/ def std_simplex : set (ι → 𝕜) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex 𝕜 ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex 𝕜 (std_simplex 𝕜 ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:𝕜) 0) ∈ std_simplex 𝕜 ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ end simplex
5ebc8fa4c25becfcab12a448b43a9b4216b6f2c9
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/periodic.lean
469b0640f5d512a5483b0985d159a9a4597fd438
[ "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
14,756
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import data.int.parity import algebra.module.opposites import algebra.archimedean /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul' [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul' ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul' a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul' [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv'] using h.const_smul' a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul' a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul' $ opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul' $ opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.gsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, gsmul_coe_nat] using h.nsmul n }, { simpa only [gsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [gsmul_eq_mul] using h.gsmul n lemma periodic.sub_gsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.gsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.gsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.gsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.gsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.gsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H⟩ := linear_ordered_add_comm_group.exists_int_smul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_gsmul_eq n).symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [add_group β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [add_group β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin rcases nat.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [hk, hi] using (h.nat_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.nat_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [add_group β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [add_group β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [add_group β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [add_group β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul' [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul' ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul' ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul' [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv'] using h.const_smul' (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul' ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul' $ (opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul' $ (opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function
dc66e8b9a99aa3dbd51f2dad970f73183ece7f46
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/ring_theory/polynomial/cyclotomic.lean
025749d65833792ac2e9db47055bdc38b6b2f1df
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,491
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import field_theory.splitting_field import ring_theory.roots_of_unity import algebra.polynomial.big_operators import number_theory.arithmetic_function import data.polynomial.lifts import analysis.complex.roots_of_unity import field_theory.separable /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators noncomputable theory universe u namespace polynomial section cyclotomic' section is_domain variables {R : Type*} [comm_ring R] [is_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : polynomial R := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [comm_ring R] [is_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, cyclotomic'_zero, nat.totient_zero, nat_degree_one] }, rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h hpos, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } end is_domain section field variables {K : Type*} [field K] /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n K, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : K)).monic := monic_X_pow_sub_C (1 : K) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C K _ _ n 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := begin by_cases hzero : n = 0, { simp only [hzero, ring_hom.map_one, splits_zero, pow_zero, sub_self] }, rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C], end /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots hpos h] }, intros x hx y hy hdiff, simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hx hy, refine is_primitive_root.disjoint _ _ hdiff, { exact @nat.pos_of_mem_divisors n x (nat.mem_divisors.2 hx) }, { exact @nat.pos_of_mem_divisors n y (nat.mem_divisors.2 hy) } end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {ζ : K} {n : ℕ} (hpos: 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], refine ⟨by rw mul_comm, _⟩, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a monic polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic' {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), induction n using nat.strong_induction_on with k hk generalizing ζ h, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, coe_map_ring_hom, map_one, and_self] }, by_cases hone : k = 1, { use X - 1, simp only [hone, cyclotomic'_one K, set.mem_univ, pnat.one_coe, subsemiring.coe_top, eq_self_iff_true, map_X, coe_map_ring_hom, map_one, and_self, map_sub], }, let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos h hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos h), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq, simp only [lifts, ring_hom.mem_srange], use Q₁, rw [coe_map_ring_hom, (map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic' h, refine ⟨P, hP.1, λ Q hQ, _⟩, apply (map_injective (int.cast_ring_hom K) int.cast_injective), rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R := if h : n = 0 then 1 else map (int.cast_ring_hom R) ((int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, map_one, and_self] }, rw int_cyclotomic_rw hzero, exact (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n hzero)).some_spec end lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, map_one, map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_add, map_X, map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, apply monic_map, exact (int_cyclotomic_spec n).2.2 end /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := monic.ne_zero (cyclotomic.monic n R) /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, exact_mod_cast hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R, exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, map_pow, nat.cast_id, map_X, map_one, map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [map_pow, map_X, map_one, map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] [nontrivial R] {K : Type*} [field K] [algebra (polynomial R) K] [is_fraction_ring (polynomial R) K] : algebra_map _ K (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (algebra_map (polynomial R) K (X ^ i.snd - 1)) ^ μ i.fst := begin have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, algebra_map _ K (cyclotomic i R) = algebra_map _ _ (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, is_fraction_ring.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin nontriviality R, rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [field K] {ζ : K} {n : ℕ} (hz : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', induction n using nat.strong_induction_on with k hk generalizing ζ hz, obtain hzero | hpos := k.eq_zero_or_pos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end /-- Any `n`-th primitive root of unity is a root of `cyclotomic n ℤ`.-/ lemma is_root_cyclotomic {n : ℕ} {K : Type*} [field K] (hpos : 0 < n) {μ : K} (h : is_primitive_root μ n) : is_root (cyclotomic n K) μ := begin rw [← mem_roots (cyclotomic_ne_zero n K), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) (P : polynomial R) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin nontriviality R, refine ⟨λ hcycl, _, λ hP, _⟩, { rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], refine ⟨by rwa [zero_add, mul_comm], _⟩, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_sum X p`. -/ lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = geom_sum X p := begin refine ((eq_cyclotomic_iff hp.pos _).mpr _).symm, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end /-- If `p ^ k` is prime power, then `cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p`. -/ lemma cyclotomic_prime_pow_eq_geom_sum {R : Type*} [comm_ring R] {p n : ℕ} (hp : nat.prime p) : cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p := begin have : ∀ m, cyclotomic (p ^ (m + 1)) R = geom_sum (X ^ (p ^ m)) p ↔ geom_sum (X ^ p ^ m) p * ∏ (x : ℕ) in finset.range (m + 1), cyclotomic (p ^ x) R = X ^ p ^ (m + 1) - 1, { intro m, have := eq_cyclotomic_iff (pow_pos hp.pos (m + 1)) _, rw eq_comm at this, rw [this, nat.prod_proper_divisors_prime_pow hp], }, induction n with n_n n_ih, { simp [cyclotomic_eq_geom_sum hp], }, rw ((eq_cyclotomic_iff (pow_pos hp.pos (n_n.succ + 1)) _).mpr _).symm, rw [nat.prod_proper_divisors_prime_pow hp, finset.prod_range_succ, n_ih], rw this at n_ih, rw [mul_comm _ (geom_sum _ _), n_ih, geom_sum_mul, sub_left_inj, ← pow_mul, pow_add, pow_one], end /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg_eq_neg_mul_symm, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [hprime.1.coprime_iff_not_dvd], intro h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, ring_hom.eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, ring_hom.eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime that does not divide `n`, then the multiplicative order of `a` modulo `p` is exactly `n`. -/ lemma order_of_root_cyclotomic_eq {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hn : ¬ p ∣ n) (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) = n := begin set m := order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)), have ha := coprime_of_root_cyclotomic hpos hroot, have hdivcycl : map (int.cast_ring_hom (zmod p)) (X - a) ∣ (cyclotomic n (zmod p)), { replace hrootdiv := dvd_iff_is_root.2 hroot, simp only [C_eq_nat_cast, ring_hom.eq_nat_cast] at hrootdiv, simp only [hrootdiv, map_nat_cast, map_X, map_sub] }, by_contra hdiff, have hdiv : map (int.cast_ring_hom (zmod p)) (X - a) ∣ ∏ i in nat.proper_divisors n, cyclotomic i (zmod p), { suffices hdivm : map (int.cast_ring_hom (zmod p)) (X - a) ∣ X ^ m - 1, { exact hdivm.trans (X_pow_sub_one_dvd_prod_cyclotomic (zmod p) hpos (order_of_root_cyclotomic_dvd hpos hroot) hdiff) }, rw [map_sub, map_X, map_nat_cast, ← C_eq_nat_cast, dvd_iff_is_root, is_root.def, eval_sub, eval_pow, eval_one, eval_X, sub_eq_zero, ← zmod.coe_unit_of_coprime a ha, ← units.coe_pow, units.coe_eq_one], exact pow_order_of_eq_one (zmod.unit_of_coprime a ha) }, have habs : (map (int.cast_ring_hom (zmod p)) (X - a)) ^ 2 ∣ X ^ n - 1, { obtain ⟨P, hP⟩ := hdivcycl, obtain ⟨Q, hQ⟩ := hdiv, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, hP, hQ], exact ⟨P * Q, by ring⟩ }, have hnzero : ↑n ≠ (0 : (zmod p)), { intro ha, exact hn (int.coe_nat_dvd.1 ((zmod.int_coe_zmod_eq_zero_iff_dvd n p).1 ha)) }, rw [sq] at habs, replace habs := squarefree_X_pow_sub_C (1 : (zmod p)) hnzero one_ne_zero (map (int.cast_ring_hom (zmod p)) (X - a)) habs, simp only [map_nat_cast, map_X, map_sub] at habs, replace habs := degree_eq_zero_of_is_unit habs, rw [← C_eq_nat_cast, degree_X_sub_C] at habs, exact one_ne_zero habs end end order section minpoly open is_primitive_root complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma _root_.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.gcd_domain_dvd ℚ (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive, simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (minpoly_dvd_cyclotomic h hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h hpos end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n hpos.ne').is_integral hpos, end end minpoly section eval_one open finset nat @[simp] lemma eval_one_cyclotomic_prime {R : Type*} [comm_ring R] {n : ℕ} [hn : fact (nat.prime n)] : eval 1 (cyclotomic n R) = n := begin simp only [cyclotomic_eq_geom_sum hn.out, geom_sum_def, eval_X, one_pow, sum_const, eval_pow, eval_finset_sum, card_range, smul_one_eq_coe], end @[simp] lemma eval₂_one_cyclotomic_prime {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S) {n : ℕ} [fact n.prime] : eval₂ f 1 (cyclotomic n R) = n := by simp @[simp] lemma eval_one_cyclotomic_prime_pow {R : Type*} [comm_ring R] {n : ℕ} (k : ℕ) [hn : fact n.prime] : eval 1 (cyclotomic (n ^ (k + 1)) R) = n := begin simp only [cyclotomic_prime_pow_eq_geom_sum hn.out, geom_sum_def, eval_X, one_pow, sum_const, eval_pow, eval_finset_sum, card_range, smul_one_eq_coe] end @[simp] lemma eval₂_one_cyclotomic_prime_pow {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S) {n : ℕ} (k : ℕ) [fact n.prime] : eval₂ f 1 (cyclotomic (n ^ (k + 1)) R) = n := by simp -- TODO show that `eval 1 (cyclotomic n R) = 1` when `n` is not a power of a prime end eval_one end polynomial
892e40cc1ccdff67bc7207866bebcb10d63d6038
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/geometry/manifold/whitney_embedding.lean
d3b090ae9ba5e65cdee770e5605a2d9a01dc2fd1
[ "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
6,345
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.diffeomorph import geometry.manifold.instances.real import geometry.manifold.partition_of_unity /-! # Whitney embedding theorem In this file we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. ## Tags partition of unity, smooth bump function, whitney theorem -/ universes uι uE uH uM variables {ι : Type uι} {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory namespace smooth_bump_covering /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ variables [t2_space M] [fintype ι] {s : set M} (f : smooth_bump_covering ι I M s) /-- Smooth embedding of `M` into `(E × ℝ) ^ ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, ι → (E × ℝ)), ι → (E × ℝ)⟯ := { to_fun := λ x i, (f i x • ext_chart_at I (f.c i) x, f i x), times_cont_mdiff_to_fun := times_cont_mdiff_pi_space.2 $ λ i, ((f i).smooth_smul times_cont_mdiff_on_ext_chart_at).prod_mk_space ((f i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑f.embedding_pi_tangent = λ x i, (f i x • ext_chart_at I (f.c i) x, f i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on f.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (f.ind x hx)), rw [f.apply_ind x hx] at h₂, rw [← h₂, f.apply_ind x hx, one_smul, one_smul] at h₁, have := f.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (f.c _)).inj_on (f.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective (f : smooth_bump_covering ι I M) : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))).comp (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) = mfderiv I I (chart_at H (f.c (f.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (f.ind x hx))), have := L.has_mfderiv_at.comp x f.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at, convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (f.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (f.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (f.c (f.ind x hx))).ker_mfderiv_eq_bot (f.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, ι → (E × ℝ)) f.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (f.embedding_pi_tangent_ker_mfderiv x hx) /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_euclidean (f : smooth_bump_covering ι I M) : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (ι → (E × ℝ))), letI : is_noetherian ℝ (E × ℝ) := is_noetherian.iff_fg.2 infer_instance, letI : finite_dimensional ℝ (ι → E × ℝ) := is_noetherian.iff_fg.1 infer_instance, set eEF : (ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_euclidean_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases smooth_bump_covering.exists_is_subordinate I is_closed_univ (λ (x : M) _, univ_mem) with ⟨ι, f, -⟩, haveI := f.fintype, rcases f.exists_immersion_euclidean with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
86327e1f3b8dec3266de6b4fac5e35cf87db4352
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/tactic/monotonicity/lemmas.lean
12d1f686a47c201e470ec5b0f5b0562934b87da7
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
2,251
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity.basic import data.set.lattice import order.bounds variables {α : Type*} @[mono] lemma mul_mono_nonneg {x y z : α} [ordered_semiring α] (h' : 0 ≤ z) (h : x ≤ y) : x * z ≤ y * z := by apply mul_le_mul_of_nonneg_right; assumption lemma lt_of_mul_lt_mul_neg_right {a b c : α} [linear_ordered_ring α] (h : a * c < b * c) (hc : c ≤ 0) : b < a := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(b * c) < -(a * c), from neg_lt_neg h, have h3 : b * (-c) < a * (-c), from calc b * (-c) = - (b * c) : by rewrite neg_mul_eq_mul_neg ... < - (a * c) : h2 ... = a * (-c) : by rewrite neg_mul_eq_mul_neg, lt_of_mul_lt_mul_right h3 nhc @[mono] lemma mul_mono_nonpos {x y z : α} [linear_ordered_ring α] (h' : z ≤ 0) (h : y ≤ x) : x * z ≤ y * z := begin classical, by_contradiction h'', revert h, apply not_le_of_lt, apply lt_of_mul_lt_mul_neg_right _ h', apply lt_of_not_ge h'' end @[mono] lemma nat.sub_mono_left_strict {x y z : ℕ} (h' : z ≤ x) (h : x < y) : x - z < y - z := begin have : z ≤ y, { transitivity, assumption, apply le_of_lt h, }, apply @nat.lt_of_add_lt_add_left z, rw [nat.add_sub_of_le,nat.add_sub_of_le]; solve_by_elim end @[mono] lemma nat.sub_mono_right_strict {x y z : ℕ} (h' : x ≤ z) (h : y < x) : z - x < z - y := begin have h'' : y ≤ z, { transitivity, apply le_of_lt h, assumption }, apply @nat.lt_of_add_lt_add_right _ x, rw [nat.sub_add_cancel h'], apply @lt_of_le_of_lt _ _ _ (z - y + y), rw [nat.sub_add_cancel h''], apply nat.add_lt_add_left h end open set attribute [mono] inter_subset_inter union_subset_union sUnion_mono bUnion_mono sInter_subset_sInter bInter_mono image_subset preimage_mono prod_mono monotone_prod seq_mono image2_subset attribute [mono] upper_bounds_mono_set lower_bounds_mono_set upper_bounds_mono_mem lower_bounds_mono_mem upper_bounds_mono lower_bounds_mono bdd_above.mono bdd_below.mono
8d422e52317b1cd23a7901ee007526f2f5596d0c
3268ab3a126f0fef71459fbf170dc38efe5d0506
/algebra/subgroup.hlean
e58ccb12eabf6ca8903fee679086c6bc51ed52d0
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,106
hlean
/- Copyright (c) 2015 Egbert Rijke. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Jeremy Avigad Basic concepts of group theory -/ import algebra.group_theory ..move_to_lib ..property open eq algebra is_trunc sigma sigma.ops prod trunc property namespace group /- #Subgroups -/ /-- Recall that a subtype of a type A is the same thing as a family of mere propositions over A. Thus, we define a subgroup of a group G to be a family of mere propositions over (the underlying type of) G, closed under the constants and operations --/ structure is_subgroup [class] (G : Group) (H : property G) : Type := (one_mem : 1 ∈ H) (mul_mem : Π{g h}, g ∈ H → h ∈ H → g * h ∈ H) (inv_mem : Π{g}, g ∈ H → g⁻¹ ∈ H) definition is_prop_is_subgroup [instance] (G : Group) (H : property G) : is_prop (is_subgroup G H) := proof -- this results in a simpler choice of universe metavariables have 1 ∈ H × (Π{g h}, g ∈ H → h ∈ H → g * h ∈ H) × (Π{g}, g ∈ H → g⁻¹ ∈ H) ≃ is_subgroup G H, begin fapply equiv.MK, { intro p, cases p with p1 p2, cases p2 with p2 p3, exact is_subgroup.mk p1 @p2 @p3 }, { intro p, split, exact is_subgroup.one_mem H, split, apply @is_subgroup.mul_mem G H p, apply @is_subgroup.inv_mem G H p}, { intro b, cases b, reflexivity }, { intro a, cases a with a1 a2, cases a2, reflexivity } end, is_trunc_equiv_closed _ this _ qed /-- Every group G has at least two subgroups, the trivial subgroup containing only one, and the full subgroup. --/ definition trivial_subgroup [instance] (G : Group) : is_subgroup G '{1} := begin fapply is_subgroup.mk, { esimp, apply mem_insert }, { intros g h p q, esimp at *, apply mem_singleton_of_eq, rewrite [eq_of_mem_singleton p, eq_of_mem_singleton q, mul_one]}, { intros g p, esimp at *, apply mem_singleton_of_eq, rewrite [eq_of_mem_singleton p, one_inv] } end definition full_subgroup [instance] (G : Group) : is_subgroup G univ := begin fapply is_subgroup.mk, { apply logic.trivial }, { intros, apply logic.trivial }, { intros, apply logic.trivial } end /-- Every group homomorphism f : G -> H determines a subgroup of H, the image of f, and a subgroup of G, the kernel of f. In the following definition we define the image of f. Since a subgroup is required to be closed under the group operations, showing that the image of f is closed under the group operations is part of the definition of the image of f. --/ definition is_subgroup_image [instance] {G : Group} {H : Group} (f : G →g H) : is_subgroup H (image f) := begin fapply is_subgroup.mk, -- subproperty contains 1 { fapply image.mk, exact 1, apply respect_one}, -- subproperty is closed under multiplication { intro h h', intro u v, induction u with x p, induction v with y q, induction p, induction q, apply image.mk (x * y), apply respect_mul}, -- subproperty is closed under inverses { intro g, intro t, induction t with x p, induction p, apply image.mk x⁻¹, apply respect_inv } end section kernels variables {G₁ G₂ : Group} -- TODO: maybe define this in more generality for pointed propertys? definition kernel [constructor] (φ : G₁ →g G₂) : property G₁ := { g | trunctype.mk (φ g = 1) _} theorem mul_mem_kernel (φ : G₁ →g G₂) (g h : G₁) (H₁ : g ∈ kernel φ) (H₂ : h ∈ kernel φ) : g * h ∈ kernel φ := calc φ (g * h) = (φ g) * (φ h) : to_respect_mul ... = 1 * (φ h) : H₁ ... = 1 * 1 : H₂ ... = 1 : one_mul theorem inv_mem_kernel (φ : G₁ →g G₂) (g : G₁) (H : g ∈ kernel φ) : g⁻¹ ∈ kernel φ := calc φ g⁻¹ = (φ g)⁻¹ : to_respect_inv ... = 1⁻¹ : H ... = 1 : one_inv definition is_subgroup_kernel [constructor] [instance] (φ : G₁ →g G₂) : is_subgroup G₁ (kernel φ) := ⦃ is_subgroup, one_mem := respect_one φ, mul_mem := mul_mem_kernel φ, inv_mem := inv_mem_kernel φ ⦄ end kernels /-- Now we should be able to show that if f is a homomorphism for which the kernel is trivial and the image is full, then f is an isomorphism, except that no one defined the proposition that f is an isomorphism :/ --/ /- definition is_iso_from_kertriv_imfull {G H : Group} (f : G →g H) : is_trivial_subgroup G (kernel f) → is_full_subgroup H (image_subgroup f) → unit /- replace unit by is_isomorphism f -/ := sorry -/ /- #Normal subgroups -/ /-- Next, we formalize some aspects of normal subgroups. Recall that a normal subgroup H of a group G is a subgroup which is invariant under all inner automorophisms on G. --/ definition is_normal.{u v} [constructor] (G : Group) (N : property.{u v} G) : Prop := trunctype.mk (Π{g} h, g ∈ N → h * g * h⁻¹ ∈ N) _ structure is_normal_subgroup [class] (G : Group) (N : property G) extends is_subgroup G N := (is_normal : is_normal G N) abbreviation subgroup_one_mem [unfold 2] := @is_subgroup.one_mem abbreviation subgroup_mul_mem [unfold 2] := @is_subgroup.mul_mem abbreviation subgroup_inv_mem [unfold 2] := @is_subgroup.inv_mem abbreviation subgroup_is_normal [unfold 2] := @is_normal_subgroup.is_normal section variables {G G' G₁ G₂ G₃ : Group} {H N : property G} [is_subgroup G H] [is_normal_subgroup G N] {g g' h h' k : G} {A B : AbGroup} theorem is_normal_subgroup' (h : G) (r : g ∈ N) : h⁻¹ * g * h ∈ N := inv_inv h ▸ subgroup_is_normal N h⁻¹ r definition is_normal_subgroup_ab [constructor] {C : property A} (subgrpA : is_subgroup A C) : is_normal_subgroup A C := ⦃ is_normal_subgroup, subgrpA, is_normal := abstract begin intros g h r, xrewrite [mul.comm h g, mul_inv_cancel_right], exact r end end⦄ theorem is_normal_subgroup_rev (h : G) (r : h * g * h⁻¹ ∈ N) : g ∈ N := have H : h⁻¹ * (h * g * h⁻¹) * h = g, from calc h⁻¹ * (h * g * h⁻¹) * h = h⁻¹ * (h * g) * h⁻¹ * h : by rewrite [-mul.assoc h⁻¹] ... = h⁻¹ * (h * g) : by rewrite [inv_mul_cancel_right] ... = g : inv_mul_cancel_left, H ▸ is_normal_subgroup' h r theorem is_normal_subgroup_rev' (h : G) (r : h⁻¹ * g * h ∈ N) : g ∈ N := is_normal_subgroup_rev h⁻¹ ((inv_inv h)⁻¹ ▸ r) theorem normal_subgroup_insert (r : k ∈ N) (r' : g * h ∈ N) : g * (k * h) ∈ N := have H1 : (g * h) * (h⁻¹ * k * h) ∈ N, from subgroup_mul_mem r' (is_normal_subgroup' h r), have H2 : (g * h) * (h⁻¹ * k * h) = g * (k * h), from calc (g * h) * (h⁻¹ * k * h) = g * (h * (h⁻¹ * k * h)) : mul.assoc ... = g * (h * (h⁻¹ * (k * h))) : by rewrite [mul.assoc h⁻¹] ... = g * (k * h) : by rewrite [mul_inv_cancel_left], show N (g * (k * h)), from H2 ▸ H1 /-- In the following, we show that the kernel of any group homomorphism f : G₁ →g G₂ is a normal subgroup of G₁ --/ theorem is_normal_subgroup_kernel {G₁ G₂ : Group} (φ : G₁ →g G₂) (g : G₁) (h : G₁) : g ∈ kernel φ → h * g * h⁻¹ ∈ kernel φ := begin esimp at *, intro p, exact calc φ (h * g * h⁻¹) = (φ (h * g)) * φ (h⁻¹) : to_respect_mul ... = (φ h) * (φ g) * (φ h⁻¹) : to_respect_mul ... = (φ h) * 1 * (φ h⁻¹) : p ... = (φ h) * (φ h⁻¹) : mul_one ... = (φ h) * (φ h)⁻¹ : to_respect_inv ... = 1 : mul.right_inv end -- this is just (Σ(g : G), H g), but only defined if (H g) is a prop definition sg {G : Group} (H : property G) : Type := subtype (λ x, x ∈ H) local attribute sg [reducible] definition subgroup_one [constructor] : sg H := ⟨one, subgroup_one_mem H⟩ definition subgroup_inv [unfold 3] : sg H → sg H := λv, ⟨v.1⁻¹, subgroup_inv_mem v.2⟩ definition subgroup_mul [unfold 3 4] : sg H → sg H → sg H := λv w, ⟨v.1 * w.1, subgroup_mul_mem v.2 w.2⟩ definition subgroup_elt (x : sg H) : G := x.1 section local notation 1 := subgroup_one local postfix ⁻¹ := subgroup_inv local infix * := subgroup_mul theorem subgroup_mul_assoc (g₁ g₂ g₃ : sg H) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := subtype_eq !mul.assoc theorem subgroup_one_mul (g : sg H) : 1 * g = g := subtype_eq !one_mul theorem subgroup_mul_one (g : sg H) : g * 1 = g := subtype_eq !mul_one theorem subgroup_mul_left_inv (g : sg H) : g⁻¹ * g = 1 := subtype_eq !mul.left_inv theorem subgroup_mul_comm {G : AbGroup} {H : property G} [subgrpH : is_subgroup G H] (g h : sg H) : subgroup_mul g h = subgroup_mul h g := subtype_eq !mul.comm end variable (H) definition group_sg [constructor] : group (sg H) := group.mk _ subgroup_mul subgroup_mul_assoc subgroup_one subgroup_one_mul subgroup_mul_one subgroup_inv subgroup_mul_left_inv definition subgroup [constructor] : Group := Group.mk _ (group_sg H) variable {H} definition ab_group_sg [constructor] {G : AbGroup} (H : property G) [is_subgroup G H] : ab_group (sg H) := ⦃ab_group, (group_sg H), mul_comm := subgroup_mul_comm⦄ definition ab_subgroup [constructor] {G : AbGroup} (H : property G) [is_subgroup G H] : AbGroup := AbGroup.mk _ (ab_group_sg H) definition Kernel {G H : Group} (f : G →g H) : Group := subgroup (kernel f) definition ab_Kernel {G H : AbGroup} (f : G →g H) : AbGroup := ab_subgroup (kernel f) definition incl_of_subgroup [constructor] {G : Group} (H : property G) [is_subgroup G H] : subgroup H →g G := begin fapply homomorphism.mk, -- the underlying function { intro h, induction h with g, exact g}, -- is a homomorphism intro g h, reflexivity end definition is_embedding_incl_of_subgroup {G : Group} (H : property G) [is_subgroup G H] : is_embedding (incl_of_subgroup H) := begin fapply function.is_embedding_of_is_injective, intro h h', fapply subtype_eq end definition ab_Kernel_incl {G H : AbGroup} (f : G →g H) : ab_Kernel f →g G := begin fapply incl_of_subgroup, end definition is_embedding_ab_kernel_incl {G H : AbGroup} (f : G →g H) : is_embedding (ab_Kernel_incl f) := begin fapply is_embedding_incl_of_subgroup, end definition is_subgroup_of_is_subgroup {G : Group} {H1 H2 : property G} [is_subgroup G H1] [is_subgroup G H2] (hyp : Π (g : G), g ∈ H1 → g ∈ H2) : is_subgroup (subgroup H2) {h | incl_of_subgroup H2 h ∈ H1} := is_subgroup.mk (subgroup_one_mem H1) (begin intros g h p q, apply mem_property_of, apply subgroup_mul_mem (of_mem_property_of p) (of_mem_property_of q), end) (begin intros h p, apply mem_property_of, apply subgroup_inv_mem (of_mem_property_of p) end) definition Image {G H : Group} (f : G →g H) : Group := subgroup (image f) definition ab_Image {G : AbGroup} {H : Group} (f : G →g H) : AbGroup := AbGroup_of_Group (Image f) begin intro g h, induction g with x t, induction h with y s, fapply subtype_eq, induction t with g p, induction s with h q, induction p, induction q, refine (((respect_mul f g h)⁻¹ ⬝ _) ⬝ (respect_mul f h g)), apply (ap f), induction G, induction struct', apply mul_comm end definition image_incl {G H : Group} (f : G →g H) : Image f →g H := incl_of_subgroup (image f) definition ab_Image_incl {A B : AbGroup} (f : A →g B) : ab_Image f →g B := incl_of_subgroup (image f) definition is_equiv_surjection_ab_image_incl {A B : AbGroup} (f : A →g B) (H : is_surjective f) : is_equiv (ab_Image_incl f ) := begin fapply is_equiv.adjointify (ab_Image_incl f), intro b, fapply sigma.mk, exact b, exact H b, intro b, reflexivity, intro x, apply subtype_eq, reflexivity end definition iso_surjection_ab_image_incl [constructor] {A B : AbGroup} (f : A →g B) (H : is_surjective f) : ab_Image f ≃g B := begin fapply isomorphism.mk, exact (ab_Image_incl f), exact is_equiv_surjection_ab_image_incl f H end definition hom_lift [constructor] {G H : Group} (f : G →g H) (K : property H) [is_subgroup H K] (Hyp : Π (g : G), K (f g)) : G →g subgroup K := begin fapply homomorphism.mk, intro g, fapply sigma.mk, exact f g, fapply Hyp, intro g h, apply subtype_eq, esimp, apply respect_mul end definition hom_factors_through_lift {G H : Group} (f : G →g H) (K : property H) [is_subgroup H K] (Hyp : Π (g : G), K (f g)) : f = incl_of_subgroup K ∘g hom_lift f K Hyp := begin fapply homomorphism_eq, reflexivity end definition ab_hom_lift [constructor] {G H : AbGroup} (f : G →g H) (K : property H) [is_subgroup H K] (Hyp : Π (g : G), K (f g)) : G →g ab_subgroup K := begin fapply homomorphism.mk, intro g, fapply sigma.mk, exact f g, fapply Hyp, intro g h, apply subtype_eq, apply respect_mul, end definition ab_hom_factors_through_lift {G H : AbGroup} (f : G →g H) (K : property H) [is_subgroup H K] (Hyp : Π (g : G), K (f g)) : f = incl_of_subgroup K ∘g hom_lift f K Hyp := begin fapply homomorphism_eq, reflexivity end definition ab_hom_lift_kernel [constructor] {A B C : AbGroup} (f : A →g B) (g : B →g C) (Hyp : Π (a : A), g (f a) = 1) : A →g ab_Kernel g := begin fapply ab_hom_lift, exact f, intro a, exact Hyp a, end definition ab_hom_lift_kernel_factors {A B C : AbGroup} (f : A →g B) (g : B →g C) (Hyp : Π (a : A), g (f a) = 1) : f = ab_Kernel_incl g ∘g ab_hom_lift_kernel f g Hyp := begin fapply ab_hom_factors_through_lift, end definition image_lift [constructor] {G H : Group} (f : G →g H) : G →g Image f := begin fapply hom_lift f, intro g, apply tr, fapply fiber.mk, exact g, reflexivity end definition ab_image_lift [constructor] {G H : AbGroup} (f : G →g H) : G →g Image f := begin fapply hom_lift f, intro g, apply tr, fapply fiber.mk, exact g, reflexivity end definition is_surjective_image_lift {G H : Group} (f : G →g H) : is_surjective (image_lift f) := begin intro h, induction h with h p, induction p with g, fapply image.mk, exact g, induction p, reflexivity end definition image_factor {G H : Group} (f : G →g H) : f = (image_incl f) ∘g (image_lift f) := begin fapply homomorphism_eq, reflexivity end definition image_incl_injective {G H : Group} (f : G →g H) : Π (x y : Image f), (image_incl f x = image_incl f y) → (x = y) := begin intro x y, intro p, fapply subtype_eq, exact p end definition image_incl_eq_one {G H : Group} (f : G →g H) : Π (x : Image f), (image_incl f x = 1) → x = 1 := begin intro x, fapply image_incl_injective f x 1, end definition image_elim_lemma {f₁ : G₁ →g G₂} {f₂ : G₁ →g G₃} (h : Π⦃g⦄, f₁ g = 1 → f₂ g = 1) (g g' : G₁) (p : f₁ g = f₁ g') : f₂ g = f₂ g' := have f₁ (g * g'⁻¹) = 1, from !to_respect_mul ⬝ ap (mul _) !to_respect_inv ⬝ mul_inv_eq_of_eq_mul (p ⬝ !one_mul⁻¹), have f₂ (g * g'⁻¹) = 1, from h this, eq_of_mul_inv_eq_one (ap (mul _) !to_respect_inv⁻¹ ⬝ !to_respect_mul⁻¹ ⬝ this) open image definition image_elim {f₁ : G₁ →g G₂} (f₂ : G₁ →g G₃) (h : Π⦃g⦄, f₁ g = 1 → f₂ g = 1) : Image f₁ →g G₃ := homomorphism.mk (total_image.elim_set f₂ (image_elim_lemma h)) begin refine total_image.rec _, intro g, refine total_image.rec _, intro g', exact to_respect_mul f₂ g g' end end definition image_homomorphism {A B C : AbGroup} (f : A →g B) (g : B →g C) : ab_Image f →g ab_Image (g ∘g f) := begin fapply image_elim, exact image_lift (g ∘g f), intro a p, fapply subtype_eq, unfold image_lift, exact calc g (f a) = g 1 : by exact ap g p ... = 1 : to_respect_one, end definition image_homomorphism_square {A B C : AbGroup} (f : A →g B) (g : B →g C) : g ∘g image_incl f ~ image_incl (g ∘g f ) ∘g image_homomorphism f g := begin intro x, induction x with b p, induction p with x, induction p, reflexivity end variables {G H K : Group} {R : property G} [is_subgroup G R] {S : property H} [is_subgroup H S] {T : property K} [is_subgroup K T] open function definition subgroup_functor_fun [unfold 7] (φ : G →g H) (h : Πg, g ∈ R → φ g ∈ S) (x : subgroup R) : subgroup S := begin induction x with g hg, exact ⟨φ g, h g hg⟩ end definition subgroup_functor [constructor] (φ : G →g H) (h : Πg, g ∈ R → φ g ∈ S) : subgroup R →g subgroup S := begin fapply homomorphism.mk, { exact subgroup_functor_fun φ h }, { intro x₁ x₂, induction x₁ with g₁ hg₁, induction x₂ with g₂ hg₂, exact sigma_eq !to_respect_mul !is_prop.elimo } end definition ab_subgroup_functor [constructor] {G H : AbGroup} {R : property G} [is_subgroup G R] {S : property H} [is_subgroup H S] (φ : G →g H) (h : Πg, g ∈ R → φ g ∈ S) : ab_subgroup R →g ab_subgroup S := subgroup_functor φ h theorem subgroup_functor_compose (ψ : H →g K) (φ : G →g H) (hψ : Πg, g ∈ S → ψ g ∈ T) (hφ : Πg, g ∈ R → φ g ∈ S) : subgroup_functor ψ hψ ∘g subgroup_functor φ hφ ~ subgroup_functor (ψ ∘g φ) (λg, proof hψ (φ g) qed ∘ hφ g) := begin intro g, induction g with g hg, reflexivity end definition subgroup_functor_gid : subgroup_functor (gid G) (λg, id) ~ gid (subgroup R) := begin intro g, induction g with g hg, reflexivity end definition subgroup_functor_mul {G H : AbGroup} {R : property G} [subgroupR : is_subgroup G R] {S : property H} [subgroupS : is_subgroup H S] (ψ φ : G →g H) (hψ : Πg, g ∈ R → ψ g ∈ S) (hφ : Πg, g ∈ R → φ g ∈ S) : homomorphism_mul (ab_subgroup_functor ψ hψ) (ab_subgroup_functor φ hφ) ~ ab_subgroup_functor (homomorphism_mul ψ φ) (λg hg, subgroup_mul_mem (hψ g hg) (hφ g hg)) := begin intro g, induction g with g hg, reflexivity end definition subgroup_functor_homotopy {ψ φ : G →g H} (hψ : Πg, R g → S (ψ g)) (hφ : Πg, g ∈ R → φ g ∈ S) (p : φ ~ ψ) : subgroup_functor φ hφ ~ subgroup_functor ψ hψ := begin intro g, induction g with g hg, exact subtype_eq (p g) end definition subgroup_of_subgroup_incl {R S : property G} [is_subgroup G R] [is_subgroup G S] (H : Π (g : G), g ∈ R → g ∈ S) : subgroup R →g subgroup S := subgroup_functor (gid G) H definition is_embedding_subgroup_of_subgroup_incl {R S : property G} [is_subgroup G R] [is_subgroup G S] (H : Π (g : G), g ∈ R -> g ∈ S) : is_embedding (subgroup_of_subgroup_incl H) := begin fapply is_embedding_of_is_injective, intro x y p, induction x with x r, induction y with y s, fapply subtype_eq, esimp, unfold subgroup_of_subgroup_incl at p, exact ap pr1 p, end definition ab_subgroup_of_subgroup_incl {A : AbGroup} {R S : property A} [is_subgroup A R] [is_subgroup A S] (H : Π (a : A), a ∈ R → a ∈ S) : ab_subgroup R →g ab_subgroup S := ab_subgroup_functor (gid A) H definition is_embedding_ab_subgroup_of_subgroup_incl {A : AbGroup} {R S : property A} [is_subgroup A R] [is_subgroup A S] (H : Π (a : A), a ∈ R → a ∈ S) : is_embedding (ab_subgroup_of_subgroup_incl H) := begin fapply is_embedding_subgroup_of_subgroup_incl end definition ab_subgroup_iso {A : AbGroup} {R S : property A} [is_subgroup A R] [is_subgroup A S] (H : Π (a : A), a ∈ R → a ∈ S) (K : Π (a : A), a ∈ S → a ∈ R) : ab_subgroup R ≃g ab_subgroup S := begin fapply isomorphism.mk, exact subgroup_of_subgroup_incl H, fapply is_equiv.adjointify, exact subgroup_of_subgroup_incl K, intro s, induction s with a p, fapply subtype_eq, reflexivity, intro r, induction r with a p, fapply subtype_eq, reflexivity end definition ab_subgroup_iso_triangle {A : AbGroup} {R S : property A} [is_subgroup A R] [is_subgroup A S] (H : Π (a : A), a ∈ R → a ∈ S) (K : Π (a : A), a ∈ S → a ∈ R) : incl_of_subgroup R ~ incl_of_subgroup S ∘g ab_subgroup_iso H K := begin intro r, induction r, reflexivity end end group open group attribute is_subgroup_image [constructor] attribute is_subgroup_kernel [constructor]
d7725f7050a817097ecba548e794a2e3bf0bb358
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/group_action/group.lean
2e669b76397d1df251aae2bab1b1f57649b807d7
[ "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
9,227
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.equiv.mul_add_aut import group_theory.group_action.units /-! # Group actions applied to various types of group This file contains lemmas about `smul` on `group_with_zero`, and `group`. -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section mul_action /-- `monoid.to_mul_action` is faithful on cancellative monoids. -/ @[to_additive /-" `add_monoid.to_add_action` is faithful on additive cancellative monoids. "-/] instance right_cancel_monoid.to_has_faithful_scalar [right_cancel_monoid α] : has_faithful_scalar α α := ⟨λ x y h, mul_right_cancel (h 1)⟩ section group variables [group α] [mul_action α β] @[simp, to_additive] lemma inv_smul_smul (c : α) (x : β) : c⁻¹ • c • x = x := by rw [smul_smul, mul_left_inv, one_smul] @[simp, to_additive] lemma smul_inv_smul (c : α) (x : β) : c • c⁻¹ • x = x := by rw [smul_smul, mul_right_inv, one_smul] /-- Given an action of a group `α` on `β`, each `g : α` defines a permutation of `β`. -/ @[to_additive, simps] def mul_action.to_perm (a : α) : equiv.perm β := ⟨λ x, a • x, λ x, a⁻¹ • x, inv_smul_smul a, smul_inv_smul a⟩ /-- Given an action of an additive group `α` on `β`, each `g : α` defines a permutation of `β`. -/ add_decl_doc add_action.to_perm /-- `mul_action.to_perm` is injective on faithful actions. -/ @[to_additive] lemma mul_action.to_perm_injective [has_faithful_scalar α β] : function.injective (mul_action.to_perm : α → equiv.perm β) := (show function.injective (equiv.to_fun ∘ mul_action.to_perm), from smul_left_injective').of_comp variables (α) (β) /-- Given an action of a group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ @[simps] def mul_action.to_perm_hom : α →* equiv.perm β := { to_fun := mul_action.to_perm, map_one' := equiv.ext $ one_smul α, map_mul' := λ u₁ u₂, equiv.ext $ mul_smul (u₁:α) u₂ } /-- Given an action of a additive group `α` on a set `β`, each `g : α` defines a permutation of `β`. -/ @[simps] def add_action.to_perm_hom (α : Type*) [add_group α] [add_action α β] : α →+ additive (equiv.perm β) := { to_fun := λ a, additive.of_mul $ add_action.to_perm a, map_zero' := equiv.ext $ zero_vadd α, map_add' := λ a₁ a₂, equiv.ext $ add_vadd a₁ a₂ } /-- The tautological action by `equiv.perm α` on `α`. This generalizes `function.End.apply_mul_action`.-/ instance equiv.perm.apply_mul_action (α : Type*) : mul_action (equiv.perm α) α := { smul := λ f a, f a, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma equiv.perm.smul_def {α : Type*} (f : equiv.perm α) (a : α) : f • a = f a := rfl /-- `equiv.perm.apply_mul_action` is faithful. -/ instance equiv.perm.apply_has_faithful_scalar (α : Type*) : has_faithful_scalar (equiv.perm α) α := ⟨λ x y, equiv.ext⟩ variables {α} {β} @[to_additive] lemma inv_smul_eq_iff {a : α} {x y : β} : a⁻¹ • x = y ↔ x = a • y := (mul_action.to_perm a).symm_apply_eq @[to_additive] lemma eq_inv_smul_iff {a : α} {x y : β} : x = a⁻¹ • y ↔ a • x = y := (mul_action.to_perm a).eq_symm_apply lemma smul_inv [group β] [smul_comm_class α β β] [is_scalar_tower α β β] (c : α) (x : β) : (c • x)⁻¹ = c⁻¹ • x⁻¹ := by rw [inv_eq_iff_mul_eq_one, smul_mul_smul, mul_right_inv, mul_right_inv, one_smul] lemma smul_zpow [group β] [smul_comm_class α β β] [is_scalar_tower α β β] (c : α) (x : β) (p : ℤ) : (c • x) ^ p = c ^ p • x ^ p := by { cases p; simp [smul_pow, smul_inv] } @[to_additive] protected lemma mul_action.bijective (g : α) : function.bijective (λ b : β, g • b) := (mul_action.to_perm g).bijective @[to_additive] protected lemma mul_action.injective (g : α) : function.injective (λ b : β, g • b) := (mul_action.bijective g).injective @[to_additive] lemma smul_left_cancel (g : α) {x y : β} (h : g • x = g • y) : x = y := mul_action.injective g h @[simp, to_additive] lemma smul_left_cancel_iff (g : α) {x y : β} : g • x = g • y ↔ x = y := (mul_action.injective g).eq_iff @[to_additive] lemma smul_eq_iff_eq_inv_smul (g : α) {x y : β} : g • x = y ↔ x = g⁻¹ • y := (mul_action.to_perm g).apply_eq_iff_eq_symm_apply end group /-- `monoid.to_mul_action` is faithful on nontrivial cancellative monoids with zero. -/ instance cancel_monoid_with_zero.to_has_faithful_scalar [cancel_monoid_with_zero α] [nontrivial α] : has_faithful_scalar α α := ⟨λ x y h, mul_left_injective₀ one_ne_zero (h 1)⟩ section gwz variables [group_with_zero α] [mul_action α β] @[simp] lemma inv_smul_smul₀ {c : α} (hc : c ≠ 0) (x : β) : c⁻¹ • c • x = x := inv_smul_smul (units.mk0 c hc) x @[simp] lemma smul_inv_smul₀ {c : α} (hc : c ≠ 0) (x : β) : c • c⁻¹ • x = x := smul_inv_smul (units.mk0 c hc) x lemma inv_smul_eq_iff₀ {a : α} (ha : a ≠ 0) {x y : β} : a⁻¹ • x = y ↔ x = a • y := (mul_action.to_perm (units.mk0 a ha)).symm_apply_eq lemma eq_inv_smul_iff₀ {a : α} (ha : a ≠ 0) {x y : β} : x = a⁻¹ • y ↔ a • x = y := (mul_action.to_perm (units.mk0 a ha)).eq_symm_apply end gwz end mul_action section distrib_mul_action section group variables [group α] [add_monoid β] [distrib_mul_action α β] variables (β) /-- Each element of the group defines an additive monoid isomorphism. This is a stronger version of `mul_action.to_perm`. -/ @[simps {simp_rhs := tt}] def distrib_mul_action.to_add_equiv (x : α) : β ≃+ β := { .. distrib_mul_action.to_add_monoid_hom β x, .. mul_action.to_perm_hom α β x } variables (α β) /-- Each element of the group defines an additive monoid isomorphism. This is a stronger version of `mul_action.to_perm_hom`. -/ @[simps] def distrib_mul_action.to_add_aut : α →* add_aut β := { to_fun := distrib_mul_action.to_add_equiv β, map_one' := add_equiv.ext (one_smul _), map_mul' := λ a₁ a₂, add_equiv.ext (mul_smul _ _) } variables {α β} theorem smul_eq_zero_iff_eq (a : α) {x : β} : a • x = 0 ↔ x = 0 := ⟨λ h, by rw [← inv_smul_smul a x, h, smul_zero], λ h, h.symm ▸ smul_zero _⟩ theorem smul_ne_zero_iff_ne (a : α) {x : β} : a • x ≠ 0 ↔ x ≠ 0 := not_congr $ smul_eq_zero_iff_eq a end group section gwz variables [group_with_zero α] [add_monoid β] [distrib_mul_action α β] theorem smul_eq_zero_iff_eq' {a : α} (ha : a ≠ 0) {x : β} : a • x = 0 ↔ x = 0 := smul_eq_zero_iff_eq (units.mk0 a ha) theorem smul_ne_zero_iff_ne' {a : α} (ha : a ≠ 0) {x : β} : a • x ≠ 0 ↔ x ≠ 0 := smul_ne_zero_iff_ne (units.mk0 a ha) end gwz end distrib_mul_action section mul_distrib_mul_action variables [group α] [monoid β] [mul_distrib_mul_action α β] variables (β) /-- Each element of the group defines a multiplicative monoid isomorphism. This is a stronger version of `mul_action.to_perm`. -/ @[simps {simp_rhs := tt}] def mul_distrib_mul_action.to_mul_equiv (x : α) : β ≃* β := { .. mul_distrib_mul_action.to_monoid_hom β x, .. mul_action.to_perm_hom α β x } variables (α β) /-- Each element of the group defines an multiplicative monoid isomorphism. This is a stronger version of `mul_action.to_perm_hom`. -/ @[simps] def mul_distrib_mul_action.to_mul_aut : α →* mul_aut β := { to_fun := mul_distrib_mul_action.to_mul_equiv β, map_one' := mul_equiv.ext (one_smul _), map_mul' := λ a₁ a₂, mul_equiv.ext (mul_smul _ _) } variables {α β} end mul_distrib_mul_action section arrow /-- If `G` acts on `A`, then it acts also on `A → B`, by `(g • F) a = F (g⁻¹ • a)`. -/ @[simps] def arrow_action {G A B : Type*} [group G] [mul_action G A] : mul_action G (A → B) := { smul := λ g F a, F (g⁻¹ • a), one_smul := by { intro, simp only [one_inv, one_smul] }, mul_smul := by { intros, simp only [mul_smul, mul_inv_rev] } } local attribute [instance] arrow_action /-- When `B` is a monoid, `arrow_action` is additionally a `mul_distrib_mul_action`. -/ def arrow_mul_distrib_mul_action {G A B : Type*} [group G] [mul_action G A] [monoid B] : mul_distrib_mul_action G (A → B) := { smul_one := λ g, rfl, smul_mul := λ g f₁ f₂, rfl } local attribute [instance] arrow_mul_distrib_mul_action /-- Given groups `G H` with `G` acting on `A`, `G` acts by multiplicative automorphisms on `A → H`. -/ @[simps] def mul_aut_arrow {G A H} [group G] [mul_action G A] [monoid H] : G →* mul_aut (A → H) := mul_distrib_mul_action.to_mul_aut _ _ end arrow namespace is_unit section mul_action variables [monoid α] [mul_action α β] @[to_additive] lemma smul_left_cancel {a : α} (ha : is_unit a) {x y : β} : a • x = a • y ↔ x = y := let ⟨u, hu⟩ := ha in hu ▸ smul_left_cancel_iff u end mul_action section distrib_mul_action variables [monoid α] [add_monoid β] [distrib_mul_action α β] @[simp] theorem smul_eq_zero {u : α} (hu : is_unit u) {x : β} : u • x = 0 ↔ x = 0 := exists.elim hu $ λ u hu, hu ▸ smul_eq_zero_iff_eq u end distrib_mul_action end is_unit
adab594cb351e2f29dc2ecd618261ad529b2c65e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/rbtree/basic_auto.lean
87e4ccd7fe0600d9da05cdd8c0313190ea2e87a7
[]
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,595
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default universes u namespace Mathlib namespace rbnode inductive is_node_of {α : Type u} : rbnode α → rbnode α → α → rbnode α → Prop where | of_red : ∀ (l : rbnode α) (v : α) (r : rbnode α), is_node_of (red_node l v r) l v r | of_black : ∀ (l : rbnode α) (v : α) (r : rbnode α), is_node_of (black_node l v r) l v r def lift {α : Type u} (lt : α → α → Prop) : Option α → Option α → Prop := sorry inductive is_searchable {α : Type u} (lt : α → α → Prop) : rbnode α → Option α → Option α → Prop where | leaf_s : ∀ {lo hi : Option α}, lift lt lo hi → is_searchable lt leaf lo hi | red_s : ∀ {l r : rbnode α} {v : α} {lo hi : Option α}, is_searchable lt l lo (some v) → is_searchable lt r (some v) hi → is_searchable lt (red_node l v r) lo hi | black_s : ∀ {l r : rbnode α} {v : α} {lo hi : Option α}, is_searchable lt l lo (some v) → is_searchable lt r (some v) hi → is_searchable lt (black_node l v r) lo hi theorem lo_lt_hi {α : Type u} {t : rbnode α} {lt : α → α → Prop} [is_trans α lt] {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → lift lt lo hi := sorry theorem is_searchable_of_is_searchable_of_incomp {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {lo : Option α} {hi : α} {hi' : α} (hc : ¬lt hi' hi ∧ ¬lt hi hi') (hs : is_searchable lt t lo (some hi)) : is_searchable lt t lo (some hi') := sorry theorem is_searchable_of_incomp_of_is_searchable {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {lo : α} {lo' : α} {hi : Option α} (hc : ¬lt lo' lo ∧ ¬lt lo lo') (hs : is_searchable lt t (some lo) hi) : is_searchable lt t (some lo') hi := sorry theorem is_searchable_some_low_of_is_searchable_of_lt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} [is_trans α lt] {lo : α} {hi : Option α} {lo' : α} (hlt : lt lo' lo) (hs : is_searchable lt t (some lo) hi) : is_searchable lt t (some lo') hi := sorry theorem is_searchable_none_low_of_is_searchable_some_low {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} {y : α} {hi : Option α} (hlt : is_searchable lt t (some y) hi) : is_searchable lt t none hi := sorry theorem is_searchable_some_high_of_is_searchable_of_lt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} [is_trans α lt] {lo : Option α} {hi : α} {hi' : α} (hlt : lt hi hi') (hs : is_searchable lt t lo (some hi)) : is_searchable lt t lo (some hi') := sorry theorem is_searchable_none_high_of_is_searchable_some_high {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} {lo : Option α} {y : α} (hlt : is_searchable lt t lo (some y)) : is_searchable lt t lo none := sorry theorem range {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {x : α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → mem lt x t → lift lt lo (some x) ∧ lift lt (some x) hi := sorry theorem lt_of_mem_left {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {x : α}, mem lt x l → lt x y := sorry theorem lt_of_mem_right {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {z : α}, mem lt z r → lt y z := sorry theorem lt_of_mem_left_right {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {x z : α}, mem lt x l → mem lt z r → lt x z := sorry inductive is_red_black {α : Type u} : rbnode α → color → ℕ → Prop where | leaf_rb : is_red_black leaf color.black 0 | red_rb : ∀ {v : α} {l r : rbnode α} {n : ℕ}, is_red_black l color.black n → is_red_black r color.black n → is_red_black (red_node l v r) color.red n | black_rb : ∀ {v : α} {l r : rbnode α} {n : ℕ} {c₁ c₂ : color}, is_red_black l c₁ n → is_red_black r c₂ n → is_red_black (black_node l v r) color.black (Nat.succ n) theorem depth_min {α : Type u} {c : color} {n : ℕ} {t : rbnode α} : is_red_black t c n → depth min t ≥ n := sorry theorem depth_max' {α : Type u} {c : color} {n : ℕ} {t : rbnode α} : is_red_black t c n → depth max t ≤ upper c n := sorry theorem depth_max {α : Type u} {c : color} {n : ℕ} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ bit0 1 * n + 1 := le_trans (depth_max' h) (upper_le c n) theorem balanced {α : Type u} {c : color} {n : ℕ} {t : rbnode α} (h : is_red_black t c n) : bit0 1 * depth min t + 1 ≥ depth max t := le_trans (depth_max h) (nat.succ_le_succ (nat.mul_le_mul_left (bit0 1) (depth_min h))) end Mathlib
d726ab5d202f745ddce96dfb8d576fe5d82d4c44
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/group_action/sub_mul_action.lean
357f5b1b1053863b3a9db8cf52dc7920042786b4
[ "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
6,002
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.group_action_hom import algebra.module.basic import data.set_like.basic import group_theory.group_action.basic /-! # Sets invariant to a `mul_action` In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with respect to scalar multiplication. For most uses, typically `submodule R M` is more powerful. ## Main definitions * `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype. * `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when `is_scalar_tower S R M`. * `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype. ## Tags submodule, mul_action -/ open function universes u u' u'' v variables {S : Type u'} {T : Type u''} {R : Type u} {M : Type v} set_option old_structure_cmd true /-- A sub_mul_action is a set which is closed under scalar multiplication. -/ structure sub_mul_action (R : Type u) (M : Type v) [has_scalar R M] : Type v := (carrier : set M) (smul_mem' : ∀ (c : R) {x : M}, x ∈ carrier → c • x ∈ carrier) namespace sub_mul_action variables [has_scalar R M] instance : set_like (sub_mul_action R M) M := ⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[ext] theorem ext {p q : sub_mul_action R M} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a sub_mul_action with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : sub_mul_action R M := { carrier := s, smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : (p.copy s hs : set M) = s := rfl lemma copy_eq (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : p.copy s hs = p := set_like.coe_injective hs instance : has_bot (sub_mul_action R M) := ⟨{ carrier := ∅, smul_mem' := λ c, set.not_mem_empty}⟩ instance : inhabited (sub_mul_action R M) := ⟨⊥⟩ end sub_mul_action namespace sub_mul_action section has_scalar variables [has_scalar R M] variables (p : sub_mul_action R M) variables {r : R} {x : M} lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h instance : has_scalar R p := { smul := λ c x, ⟨c • x.1, smul_mem _ c x.2⟩ } variables {p} @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl variables (p) /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((sub_mul_action.subtype p) : p → M) = subtype.val := rfl end has_scalar section mul_action variables [monoid R] [mul_action R M] section variables [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) lemma smul_of_tower_mem (s : S) {x : M} (h : x ∈ p) : s • x ∈ p := by { rw [←one_smul R x, ←smul_assoc], exact p.smul_mem _ h } instance has_scalar' : has_scalar S p := { smul := λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩ } instance : is_scalar_tower S R p := { smul_assoc := λ s r x, subtype.ext $ smul_assoc s r ↑x } @[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s • x : p) : M) = s • ↑x := rfl @[simp] lemma smul_mem_iff' {G} [group G] [has_scalar G R] [mul_action G M] [is_scalar_tower G R M] (g : G) {x : M} : g • x ∈ p ↔ x ∈ p := ⟨λ h, inv_smul_smul g x ▸ p.smul_of_tower_mem g⁻¹ h, p.smul_of_tower_mem g⟩ instance [has_scalar Sᵐᵒᵖ R] [has_scalar Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S p := { op_smul_eq_smul := λ r x, subtype.ext $ op_smul_eq_smul r x } end section variables [monoid S] [has_scalar S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) /-- If the scalar product forms a `mul_action`, then the subset inherits this action -/ instance mul_action' : mul_action S p := { smul := (•), one_smul := λ x, subtype.ext $ one_smul _ x, mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul c₁ c₂ x } instance : mul_action R p := p.mul_action' end end mul_action section module variables [semiring R] [add_comm_monoid M] variables [module R M] variables (p : sub_mul_action R M) lemma zero_mem (h : (p : set M).nonempty) : (0 : M) ∈ p := let ⟨x, hx⟩ := h in zero_smul R (x : M) ▸ p.smul_mem 0 hx /-- If the scalar product forms a `module`, and the `sub_mul_action` is not `⊥`, then the subset inherits the zero. -/ instance [n_empty : nonempty p] : has_zero p := { zero := ⟨0, n_empty.elim $ λ x, p.zero_mem ⟨x, x.prop⟩⟩ } end module section add_comm_group variables [ring R] [add_comm_group M] variables [module R M] variables (p p' : sub_mul_action R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := by { rw ← neg_one_smul R, exact p.smul_mem _ hx } @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by { rw ←neg_neg x, exact neg_mem _ h}, neg_mem _⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl end add_comm_group end sub_mul_action namespace sub_mul_action variables [division_ring S] [semiring R] [mul_action R M] variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 s s0) end sub_mul_action
4cc9df441430e86887c4d38302bc5bfdb2ae1e38
a8c03ed21a1bd6fc45901943b79dd6574ea3f0c2
/factoring.lean
711859c037d3eee5c9a5da747797bd2bb2cf458a
[]
no_license
gebner/resolution.lean
716c355fbb5204e5c4d0c5a7f3f3cc825892a2bf
c6fafe06fba1cfad73db68f2aa474b29fe892a2b
refs/heads/master
1,601,111,444,528
1,475,256,701,000
1,475,256,701,000
67,711,151
0
0
null
null
null
null
UTF-8
Lean
false
false
1,862
lean
import clause prover_state subsumption open tactic expr monad variable gt : expr → expr → bool meta def inst_lit (c : clause) (i : nat) (e : expr) : tactic clause := do opened ← clause.open_constn c i, return $ clause.close_constn (clause.inst opened.1 e) opened.2 private meta def try_factor' (c : clause) (i j : nat) : tactic clause := do qf ← clause.open_metan c c↣num_quants, unify_lit (qf↣1↣get_lit i) (qf↣1↣get_lit j), qfi ← clause.inst_mvars qf.1, guard $ clause.is_maximal gt qfi i, at_j ← clause.open_constn qf.1 j, hyp_i ← option.to_monad (list.nth at_j.2 i), clause.meta_closure qf↣2 $ (at_j↣1↣inst hyp_i)↣close_constn at_j↣2 meta def try_factor (c : clause) (i j : nat) : tactic clause := if i > j then try_factor' gt c j i else try_factor' gt c i j meta def try_infer_factor (c : active_cls) (i j : nat) : resolution_prover unit := do f ← ↑(try_factor gt c↣c i j), ss : bool ← ↑(does_subsume f c↣c), add_inferred f [c], if ss then remove_redundant c↣id [] else return () meta def factor_inf : inference := take given, do gt ← get_term_order, sequence' $ do i ← active_cls.selected given, j ← list.range given↣c↣num_lits, return $ try_infer_factor gt given i j <|> return () meta def factor_dup_lits' : clause → tactic clause | c := match (do i ← c↣get_lits↣zip_with_index, j ← c↣get_lits↣zip_with_index, guard $ i↣2 < j↣2, guard $ i↣1 = j↣1, [(i↣2,j↣2)]) with | ((i,j)::_) := try_factor (λx y, ff) c i j >>= factor_dup_lits' | [] := return c end meta def factor_dup_lits (c : clause) : tactic clause := do qf ← c↣open_constn c↣num_quants, qf' ← factor_dup_lits' qf↣1, return $ qf'↣close_constn qf↣2 meta def factor_dup_lits_pre := preprocessing_rule $ take new, do ↑(mapM factor_dup_lits new)
7819a96cbf6ac3c08b5e2e9da5e1fb32d5b2a371
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/nat/basic.lean
d107bbf71668db9f1dfc6068dbe479f819855520
[ "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
67,733
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.order_functions import data.set.basic /-! # Basic operations on the natural numbers This files has some basic lemmas about natural numbers, definition of the `choice` function, and extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers. * `decreasing_induction` : recursion growing downwards. * `strong_rec'` : recursion based on strong inequalities. -/ universes u v attribute [protected] nat.pow_zero nat.pow_succ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm } instance : decidable_linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := nat.zero_lt_succ 0, mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, ..nat.comm_semiring, ..nat.decidable_linear_order } -- all the fields are already included in the decidable_linear_ordered_semiring instance instance : decidable_linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.decidable_linear_ordered_semiring } /- Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_decidable_linear_order } namespace nat variables {m n k : ℕ} theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma zero_max {m : nat} : max 0 m = m := max_eq_right (zero_le _) theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] theorem pos_iff_ne_zero : 0 < n ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := mt (nat.dvd_add_right two_dvd_bit0).1 dec_trivial /-- A natural number m divides the sum m + n if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number m divides the sum n + m if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := rfl | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm section facts -- Inject some simple facts into the typeclass system. -- This `fact` should not be confused with the factorial function `nat.fact`! instance succ_pos'' (n : ℕ) : _root_.fact (0 < n.succ) := n.succ_pos instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h end facts instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := begin dsimp, apply option.bind_eq_some.trans, simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one] end theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, nat.pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : 0 < p) : ∀ n : ℕ, 0 < p ^ n | 0 := by simp | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma lt_two_pow (n : ℕ) : n < 2^n := lt_pow_self dec_trivial n lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n := one_pow n ▸ pow_le_pow_of_le_left h n lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m) lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n := one_pow n ▸ pow_lt_pow_of_lt_left h₁ h₀ lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) := one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (nat.pow x) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (nat.pow x) := strict_mono.injective (pow_right_strict_mono k) lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l | (x+1) w := begin split, { intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, }, { intro a, cases x with x, { simp only [one_pow], }, { have le := (pow_le_iff_le_right (le_add_left _ _)).mp a, use (x+2)^(l-k), rw [←nat.pow_add, add_comm k, nat.sub_add_cancel le], } } end /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l := by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w] lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl theorem fact_pos : ∀ n, 0 < fact n | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, 0 < m → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_fact : monotone fact := λ n m, fact_le lemma fact_lt (h0 : 0 < n) : n.fact < m.fact ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (fact_le hmn) }, { have : ∀(n : ℕ), 0 < n → n.fact < n.succ.fact, { intros k hk, rw [fact_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (fact_pos k) }, induction h generalizing h0, { exact this _ h0, }, { refine lt_trans (h_ih h0) (this _ _), exact lt_trans h0 (lt_of_succ_le h_a) }} end lemma one_lt_fact : 1 < n.fact ↔ 1 < n := by { convert fact_lt _, refl, exact one_pos } lemma fact_eq_one : n.fact = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_fact, h], apply lt_irrefl }, { cases h with h h, refl, cases h, refl } end lemma fact_inj (h0 : 1 < n.fact) : n.fact = m.fact ↔ n = m := begin split; intro h, { rcases lt_trichotomy n m with hnm|hnm|hnm, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_fact] at h0, exact lt_trans one_pos h0 }, { exact hnm }, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [h, one_lt_fact] at h0, exact lt_trans one_pos h0 }}, { rw h } end /- choose -/ /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n := by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk); simp [fact_succ, mul_comm, mul_left_comm], have h₁ : fact (n - k) = (n - k) * fact (n - succ k) := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ], have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n := by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁); simp [fact_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) := begin have : fact n = choose n k * (fact k * fact (n - k)) := by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm end theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _ @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_fact_div_fact hk, choose_eq_fact_div_fact (sub_le _ _), nat.sub_sub_self hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw nat.add_sub_cancel} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib, nat.add_sub_add_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, by_cases hk : n < k + 1, { rw [choose_eq_zero_of_lt hk, sub_eq_zero_of_le hk, zero_mul, mul_zero] }, push_neg at hk, replace hk : k + 1 ≤ n + 1 := _root_.le_add_right hk, rw [choose_succ_succ], rw [add_mul, succ_sub_succ], rw [← choose_succ_right_eq], rw [← succ_sub_succ, nat.mul_sub_left_distrib], symmetry, apply nat.add_sub_cancel', exact mul_le_mul_left _ hk, end theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) section find @[simp] lemma find_eq_zero {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : nat.find h = 0 ↔ p 0 := begin split, { intro h0, rw [← h0], apply nat.find_spec }, { intro hp, apply nat.eq_zero_of_le_zero, exact nat.find_min' _ hp } end @[simp] lemma find_pos {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [nat.pos_iff_ne_zero, not_iff_not, nat.find_eq_zero] end find section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk lemma find_greatest_eq_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b}, (∀ n ≤ b, ¬ P n) → nat.find_greatest P b = 0 | 0 h := find_greatest_zero | (n + 1) h := begin have := nat.find_greatest_of_not (h (n + 1) (le_refl _)), rw this, exact find_greatest_eq_zero (assume k hk, h k (le_trans hk $ nat.le_succ _)) end lemma find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b m}, nat.find_greatest P b = m → m ≠ 0 → P m | 0 m rfl h := by { have := @find_greatest_zero P _, contradiction } | (b + 1) m rfl h := decidable.by_cases (assume hb : P (b + 1), by { have := find_greatest_eq hb, rw this, exact hb }) (assume hb : ¬ P (b + 1), find_greatest_of_ne_zero (find_greatest_of_not hb).symm h) end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0 | none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial) | n none := iff_of_false (by cases n; exact dec_trivial) (λ h, absurd h.2 dec_trivial) | (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧ (m : with_bot ℕ) = (0 : ℕ), by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)] lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0) | none none := dec_trivial | none (some m) := dec_trivial | (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial) (λ h, absurd h.2 dec_trivial)) | (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp | (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero] @[simp] lemma with_bot.coe_nonneg {n : ℕ} : 0 ≤ (n : with_bot ℕ) := by rw [← with_bot.coe_zero, with_bot.coe_le_coe]; exact nat.zero_le _ @[simp] lemma with_bot.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)) -- induction /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } end nat
472ccfce84bdeb275f27732c50edf8fba4f4d4d4
aa2345b30d710f7e75f13157a35845ee6d48c017
/category_theory/types.lean
25d92e3dea734831209bf2cccdc5e97a2c2c7675
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
2,290
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl import category_theory.functor_category category_theory.embedding namespace category_theory universes u v u' v' w instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id {α : Type u} (a : α) : (𝟙 α : α → α) a = a := rfl @[simp] lemma types_comp {α β γ : Type u} (f : α → β) (g : β → γ) (a : α) : (((f : α ⟶ β) ≫ (g : β ⟶ γ)) : α ⟶ γ) a = g (f a) := rfl @[simp] lemma types.iso_mk_coe (α β : Type u) (f : α → β) (g : β → α) (hom_inv_id) (inv_hom_id) (a : α) : (({ iso . hom := f, inv := g, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id } : α ≅ β) : α ⟶ β) a = f a := rfl namespace functor_to_types variables {C : Type u} [𝒞 : category.{u v} C] (F G H : C ⥤ (Type w)) {X Y Z : C} include 𝒞 variables (σ : F ⟹ G) (τ : G ⟹ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F X) : σ Y ((F.map f) x) = (G.map f) (σ X x) := congr_fun (σ.naturality f) x @[simp] lemma vcomp (x : F X) : (σ ⊟ τ) X x = τ X (σ X x) := rfl variables {D : Type u'} [𝒟 : category.{u' v'} D] (I J : D ⥤ C) (ρ : I ⟹ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F) W) : (ρ ◫ σ) W x = (G.map (ρ W)) (σ (I W) x) := rfl end functor_to_types def ulift_functor : (Type u) ⥤ (Type (max u v)) := { obj := λ X, ulift.{v} X, map' := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } section forget variables (C : Type u → Type v) {hom : ∀α β, C α → C β → (α → β) → Prop} [i : concrete_category hom] include i /-- The forgetful functor from a bundled category to `Type`. -/ def forget : bundled C ⥤ Type u := { obj := bundled.α, map' := λa b h, h.1 } instance forget.faithful : faithful (forget C) := {} end forget end category_theory
a1e71187a519d8e4199c62c19c12b00efbe762cd
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/box_integral/partition/split.lean
5b9c62fdbc9b28e9f85f1ed7e31f3ef3dea87e78
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,638
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.basic /-! # Split a box along one or more hyperplanes ## Main definitions A hyperplane `{x : ι → ℝ | x i = a}` splits a rectangular box `I : box_integral.box ι` into two smaller boxes. If `a ∉ Ioo (I.lower i, I.upper i)`, then one of these boxes is empty, so it is not a box in the sense of `box_integral.box`. We introduce the following definitions. * `box_integral.box.split_lower I i a` and `box_integral.box.split_upper I i a` are these boxes (as `with_bot (box_integral.box ι)`); * `box_integral.prepartition.split I i a` is the partition of `I` made of these two boxes (or of one box `I` if one of these boxes is empty); * `box_integral.prepartition.split_many I s`, where `s : finset (ι × ℝ)` is a finite set of hyperplanes `{x : ι → ℝ | x i = a}` encoded as pairs `(i, a)`, is the partition of `I` made by cutting it along all the hyperplanes in `s`. ## Main results The main result `box_integral.prepartition.exists_Union_eq_diff` says that any prepartition `π` of `I` admits a prepartition `π'` of `I` that covers exactly `I \ π.Union`. One of these prepartitions is available as `box_integral.prepartition.compl`. ## Tags rectangular box, partition, hyperplane -/ noncomputable theory open_locale classical big_operators filter open function set filter namespace box_integral variables {ι M : Type*} {n : ℕ} namespace box variables {I : box ι} {i : ι} {x : ℝ} {y : ι → ℝ} /-- Given a box `I` and `x ∈ (I.lower i, I.upper i)`, the hyperplane `{y : ι → ℝ | y i = x}` splits `I` into two boxes. `box_integral.box.split_lower I i x` is the box `I ∩ {y | y i ≤ x}` (if it is nonempty). As usual, we represent a box that may be empty as `with_bot (box_integral.box ι)`. -/ def split_lower (I : box ι) (i : ι) (x : ℝ) : with_bot (box ι) := mk' I.lower (update I.upper i (min x (I.upper i))) @[simp] lemma coe_split_lower : (split_lower I i x : set (ι → ℝ)) = I ∩ {y | y i ≤ x} := begin rw [split_lower, coe_mk'], ext y, simp only [mem_univ_pi, mem_Ioc, mem_inter_eq, mem_coe, mem_set_of_eq, forall_and_distrib, ← pi.le_def, le_update_iff, le_min_iff, and_assoc, and_forall_ne i, mem_def], rw [and_comm (y i ≤ x), pi.le_def] end lemma split_lower_le : I.split_lower i x ≤ I := with_bot_coe_subset_iff.1 $ by simp @[simp] lemma split_lower_eq_bot {i x} : I.split_lower i x = ⊥ ↔ x ≤ I.lower i := begin rw [split_lower, mk'_eq_bot, exists_update_iff I.upper (λ j y, y ≤ I.lower j)], simp [(I.lower_lt_upper _).not_le] end @[simp] lemma split_lower_eq_self : I.split_lower i x = I ↔ I.upper i ≤ x := by simp [split_lower, update_eq_iff] lemma split_lower_def [decidable_eq ι] {i x} (h : x ∈ Ioo (I.lower i) (I.upper i)) (h' : ∀ j, I.lower j < update I.upper i x j := (forall_update_iff I.upper (λ j y, I.lower j < y)).2 ⟨h.1, λ j hne, I.lower_lt_upper _⟩) : I.split_lower i x = (⟨I.lower, update I.upper i x, h'⟩ : box ι) := by { simp only [split_lower, mk'_eq_coe, min_eq_left h.2.le], use rfl, congr } /-- Given a box `I` and `x ∈ (I.lower i, I.upper i)`, the hyperplane `{y : ι → ℝ | y i = x}` splits `I` into two boxes. `box_integral.box.split_upper I i x` is the box `I ∩ {y | x < y i}` (if it is nonempty). As usual, we represent a box that may be empty as `with_bot (box_integral.box ι)`. -/ def split_upper (I : box ι) (i : ι) (x : ℝ) : with_bot (box ι) := mk' (update I.lower i (max x (I.lower i))) I.upper @[simp] lemma coe_split_upper : (split_upper I i x : set (ι → ℝ)) = I ∩ {y | x < y i} := begin rw [split_upper, coe_mk'], ext y, simp only [mem_univ_pi, mem_Ioc, mem_inter_eq, mem_coe, mem_set_of_eq, forall_and_distrib, forall_update_iff I.lower (λ j z, z < y j), max_lt_iff, and_assoc (x < y i), and_forall_ne i, mem_def], exact and_comm _ _ end lemma split_upper_le : I.split_upper i x ≤ I := with_bot_coe_subset_iff.1 $ by simp @[simp] lemma split_upper_eq_bot {i x} : I.split_upper i x = ⊥ ↔ I.upper i ≤ x := begin rw [split_upper, mk'_eq_bot, exists_update_iff I.lower (λ j y, I.upper j ≤ y)], simp [(I.lower_lt_upper _).not_le] end @[simp] lemma split_upper_eq_self : I.split_upper i x = I ↔ x ≤ I.lower i := by simp [split_upper, update_eq_iff] lemma split_upper_def [decidable_eq ι] {i x} (h : x ∈ Ioo (I.lower i) (I.upper i)) (h' : ∀ j, update I.lower i x j < I.upper j := (forall_update_iff I.lower (λ j y, y < I.upper j)).2 ⟨h.2, λ j hne, I.lower_lt_upper _⟩) : I.split_upper i x = (⟨update I.lower i x, I.upper, h'⟩ : box ι) := by { simp only [split_upper, mk'_eq_coe, max_eq_left h.1.le], refine ⟨_, rfl⟩, congr } lemma disjoint_split_lower_split_upper (I : box ι) (i : ι) (x : ℝ) : disjoint (I.split_lower i x) (I.split_upper i x) := begin rw [← disjoint_with_bot_coe, coe_split_lower, coe_split_upper], refine (disjoint.inf_left' _ _).inf_right' _, exact λ y (hy : y i ≤ x ∧ x < y i), not_lt_of_le hy.1 hy.2 end lemma split_lower_ne_split_upper (I : box ι) (i : ι) (x : ℝ) : I.split_lower i x ≠ I.split_upper i x := begin cases le_or_lt x (I.lower i), { rw [split_upper_eq_self.2 h, split_lower_eq_bot.2 h], exact with_bot.bot_ne_coe _ }, { refine (disjoint_split_lower_split_upper I i x).ne _, rwa [ne.def, split_lower_eq_bot, not_le] } end end box namespace prepartition variables {I J : box ι} {i : ι} {x : ℝ} /-- The partition of `I : box ι` into the boxes `I ∩ {y | y ≤ x i}` and `I ∩ {y | x i < y}`. One of these boxes can be empty, then this partition is just the single-box partition `⊤`. -/ def split (I : box ι) (i : ι) (x : ℝ) : prepartition I := of_with_bot {I.split_lower i x, I.split_upper i x} begin simp only [finset.mem_insert, finset.mem_singleton], rintro J (rfl|rfl), exacts [box.split_lower_le, box.split_upper_le] end begin simp only [finset.coe_insert, finset.coe_singleton, true_and, set.mem_singleton_iff, pairwise_on_insert_of_symmetric symmetric_disjoint, pairwise_on_singleton], rintro J rfl -, exact I.disjoint_split_lower_split_upper i x end @[simp] lemma mem_split_iff : J ∈ split I i x ↔ ↑J = I.split_lower i x ∨ ↑J = I.split_upper i x := by simp [split] lemma mem_split_iff' : J ∈ split I i x ↔ (J : set (ι → ℝ)) = I ∩ {y | y i ≤ x} ∨ (J : set (ι → ℝ)) = I ∩ {y | x < y i} := by simp [mem_split_iff, ← box.with_bot_coe_inj] @[simp] lemma Union_split (I : box ι) (i : ι) (x : ℝ) : (split I i x).Union = I := by simp [split, ← inter_union_distrib_left, ← set_of_or, le_or_lt] lemma is_partition_split (I : box ι) (i : ι) (x : ℝ) : is_partition (split I i x) := is_partition_iff_Union_eq.2 $ Union_split I i x lemma sum_split_boxes {M : Type*} [add_comm_monoid M] (I : box ι) (i : ι) (x : ℝ) (f : box ι → M) : ∑ J in (split I i x).boxes, f J = (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f := by rw [split, sum_of_with_bot, finset.sum_pair (I.split_lower_ne_split_upper i x)] /-- If `x ∉ (I.lower i, I.upper i)`, then the hyperplane `{y | y i = x}` does not split `I`. -/ lemma split_of_not_mem_Ioo (h : x ∉ Ioo (I.lower i) (I.upper i)) : split I i x = ⊤ := begin refine ((is_partition_top I).eq_of_boxes_subset (λ J hJ, _)).symm, rcases mem_top.1 hJ with rfl, clear hJ, rw [mem_boxes, mem_split_iff], rw [mem_Ioo, not_and_distrib, not_lt, not_lt] at h, cases h; [right, left], { rwa [eq_comm, box.split_upper_eq_self] }, { rwa [eq_comm, box.split_lower_eq_self] } end lemma coe_eq_of_mem_split_of_mem_le {y : ι → ℝ} (h₁ : J ∈ split I i x) (h₂ : y ∈ J) (h₃ : y i ≤ x) : (J : set (ι → ℝ)) = I ∩ {y | y i ≤ x} := (mem_split_iff'.1 h₁).resolve_right $ λ H, by { rw [← box.mem_coe, H] at h₂, exact h₃.not_lt h₂.2 } lemma coe_eq_of_mem_split_of_lt_mem {y : ι → ℝ} (h₁ : J ∈ split I i x) (h₂ : y ∈ J) (h₃ : x < y i) : (J : set (ι → ℝ)) = I ∩ {y | x < y i} := (mem_split_iff'.1 h₁).resolve_left $ λ H, by { rw [← box.mem_coe, H] at h₂, exact h₃.not_le h₂.2 } @[simp] lemma restrict_split (h : I ≤ J) (i : ι) (x : ℝ) : (split J i x).restrict I = split I i x := begin refine ((is_partition_split J i x).restrict h).eq_of_boxes_subset _, simp only [finset.subset_iff, mem_boxes, mem_restrict', exists_prop, mem_split_iff'], have : ∀ s, (I ∩ s : set (ι → ℝ)) ⊆ J, from λ s, (inter_subset_left _ _).trans h, rintro J₁ ⟨J₂, (H₂|H₂), H₁⟩; [left, right]; simp [H₁, H₂, inter_left_comm ↑I, this], end lemma inf_split (π : prepartition I) (i : ι) (x : ℝ) : π ⊓ split I i x = π.bUnion (λ J, split J i x) := bUnion_congr_of_le rfl $ λ J hJ, restrict_split hJ i x /-- Split a box along many hyperplanes `{y | y i = x}`; each hyperplane is given by the pair `(i x)`. -/ def split_many (I : box ι) (s : finset (ι × ℝ)) : prepartition I := s.inf (λ p, split I p.1 p.2) @[simp] lemma split_many_empty (I : box ι) : split_many I ∅ = ⊤ := finset.inf_empty @[simp] lemma split_many_insert (I : box ι) (s : finset (ι × ℝ)) (p : ι × ℝ) : split_many I (insert p s) = split_many I s ⊓ split I p.1 p.2 := by rw [split_many, finset.inf_insert, inf_comm, split_many] lemma split_many_le_split (I : box ι) {s : finset (ι × ℝ)} {p : ι × ℝ} (hp : p ∈ s) : split_many I s ≤ split I p.1 p.2 := finset.inf_le hp lemma is_partition_split_many (I : box ι) (s : finset (ι × ℝ)) : is_partition (split_many I s) := finset.induction_on s (by simp only [split_many_empty, is_partition_top]) $ λ a s ha hs, by simpa only [split_many_insert, inf_split] using hs.bUnion (λ J hJ, is_partition_split _ _ _) @[simp] lemma Union_split_many (I : box ι) (s : finset (ι × ℝ)) : (split_many I s).Union = I := (is_partition_split_many I s).Union_eq lemma inf_split_many {I : box ι} (π : prepartition I) (s : finset (ι × ℝ)) : π ⊓ split_many I s = π.bUnion (λ J, split_many J s) := begin induction s using finset.induction_on with p s hp ihp, { simp }, { simp_rw [split_many_insert, ← inf_assoc, ihp, inf_split, bUnion_assoc] } end /-- Let `s : finset (ι × ℝ)` be a set of hyperplanes `{x : ι → ℝ | x i = r}` in `ι → ℝ` encoded as pairs `(i, r)`. Suppose that this set contains all faces of a box `J`. The hyperplanes of `s` split a box `I` into subboxes. Let `Js` be one of them. If `J` and `Js` have nonempty intersection, then `Js` is a subbox of `J`. -/ lemma not_disjoint_imp_le_of_subset_of_mem_split_many {I J Js : box ι} {s : finset (ι × ℝ)} (H : ∀ i, {(i, J.lower i), (i, J.upper i)} ⊆ s) (HJs : Js ∈ split_many I s) (Hn : ¬disjoint (J : with_bot (box ι)) Js) : Js ≤ J := begin simp only [finset.insert_subset, finset.singleton_subset_iff] at H, rcases box.not_disjoint_coe_iff_nonempty_inter.mp Hn with ⟨x, hx, hxs⟩, refine λ y hy i, ⟨_, _⟩, { rcases split_many_le_split I (H i).1 HJs with ⟨Jl, Hmem : Jl ∈ split I i (J.lower i), Hle⟩, have := Hle hxs, rw [← box.coe_subset_coe, coe_eq_of_mem_split_of_lt_mem Hmem this (hx i).1] at Hle, exact (Hle hy).2 }, { rcases split_many_le_split I (H i).2 HJs with ⟨Jl, Hmem : Jl ∈ split I i (J.upper i), Hle⟩, have := Hle hxs, rw [← box.coe_subset_coe, coe_eq_of_mem_split_of_mem_le Hmem this (hx i).2] at Hle, exact (Hle hy).2 } end section fintype variable [fintype ι] /-- Let `s` be a finite set of boxes in `ℝⁿ = ι → ℝ`. Then there exists a finite set `t₀` of hyperplanes (namely, the set of all hyperfaces of boxes in `s`) such that for any `t ⊇ t₀` and any box `I` in `ℝⁿ` the following holds. The hyperplanes from `t` split `I` into subboxes. Let `J'` be one of them, and let `J` be one of the boxes in `s`. If these boxes have a nonempty intersection, then `J' ≤ J`. -/ lemma eventually_not_disjoint_imp_le_of_mem_split_many (s : finset (box ι)) : ∀ᶠ t : finset (ι × ℝ) in at_top, ∀ (I : box ι) (J ∈ s) (J' ∈ split_many I t), ¬disjoint (J : with_bot (box ι)) J' → J' ≤ J := begin refine eventually_at_top.2 ⟨s.bUnion (λ J, finset.univ.bUnion (λ i, {(i, J.lower i), (i, J.upper i)})), λ t ht I J hJ J' hJ', not_disjoint_imp_le_of_subset_of_mem_split_many (λ i, _) hJ'⟩, exact λ p hp, ht (finset.mem_bUnion.2 ⟨J, hJ, finset.mem_bUnion.2 ⟨i, finset.mem_univ _, hp⟩⟩) end lemma eventually_split_many_inf_eq_filter (π : prepartition I) : ∀ᶠ t : finset (ι × ℝ) in at_top, π ⊓ (split_many I t) = (split_many I t).filter (λ J, ↑J ⊆ π.Union) := begin refine (eventually_not_disjoint_imp_le_of_mem_split_many π.boxes).mono (λ t ht, _), refine le_antisymm ((bUnion_le_iff _).2 $ λ J hJ, _) (le_inf (λ J hJ, _) (filter_le _ _)), { refine of_with_bot_mono _, simp only [finset.mem_image, exists_prop, mem_boxes, mem_filter], rintro _ ⟨J₁, h₁, rfl⟩ hne, refine ⟨_, ⟨J₁, ⟨h₁, subset.trans _ (π.subset_Union hJ)⟩, rfl⟩, le_rfl⟩, exact ht I J hJ J₁ h₁ (mt disjoint_iff.1 hne) }, { rw mem_filter at hJ, rcases set.mem_bUnion_iff.1 (hJ.2 J.upper_mem) with ⟨J', hJ', hmem⟩, refine ⟨J', hJ', ht I _ hJ' _ hJ.1 $ box.not_disjoint_coe_iff_nonempty_inter.2 _⟩, exact ⟨J.upper, hmem, J.upper_mem⟩ } end lemma exists_split_many_inf_eq_filter_of_finite (s : set (prepartition I)) (hs : s.finite) : ∃ t : finset (ι × ℝ), ∀ π ∈ s, π ⊓ (split_many I t) = (split_many I t).filter (λ J, ↑J ⊆ π.Union) := begin have := λ π (hπ : π ∈ s), eventually_split_many_inf_eq_filter π, exact (hs.eventually_all.2 this).exists end /-- If `π` is a partition of `I`, then there exists a finite set `s` of hyperplanes such that `split_many I s ≤ π`. -/ lemma is_partition.exists_split_many_le {I : box ι} {π : prepartition I} (h : is_partition π) : ∃ s, split_many I s ≤ π := (eventually_split_many_inf_eq_filter π).exists.imp $ λ s hs, by { rwa [h.Union_eq, filter_of_true, inf_eq_right] at hs, exact λ J hJ, le_of_mem _ hJ } /-- For every prepartition `π` of `I` there exists a prepartition that covers exactly `I \ π.Union`. -/ lemma exists_Union_eq_diff (π : prepartition I) : ∃ π' : prepartition I, π'.Union = I \ π.Union := begin rcases π.eventually_split_many_inf_eq_filter.exists with ⟨s, hs⟩, use (split_many I s).filter (λ J, ¬(J : set (ι → ℝ)) ⊆ π.Union), simp [← hs] end /-- If `π` is a prepartition of `I`, then `π.compl` is a prepartition of `I` such that `π.compl.Union = I \ π.Union`. -/ def compl (π : prepartition I) : prepartition I := π.exists_Union_eq_diff.some @[simp] lemma Union_compl (π : prepartition I) : π.compl.Union = I \ π.Union := π.exists_Union_eq_diff.some_spec /-- Since the definition of `box_integral.prepartition.compl` uses `Exists.some`, the result depends only on `π.Union`. -/ lemma compl_congr {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) : π₁.compl = π₂.compl := by { dunfold compl, congr' 1, rw h } lemma is_partition.compl_eq_bot {π : prepartition I} (h : is_partition π) : π.compl = ⊥ := by rw [← Union_eq_empty, Union_compl, h.Union_eq, diff_self] @[simp] lemma compl_top : (⊤ : prepartition I).compl = ⊥ := (is_partition_top I).compl_eq_bot end fintype end prepartition end box_integral
6d1d681e260158522851995c8d938ce475baf659
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/associated.lean
9111d49e04fb0f9bf33e4b6ea256f6aec8aeac6c
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,174
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, Jens Wagemaker -/ import algebra.big_operators.basic import algebra.divisibility import algebra.invertible /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} theorem is_unit_iff_dvd_one [comm_monoid α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_monoid α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, h.trans (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {α} [comm_monoid α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ xy.trans $ is_unit_iff_dvd_one.1 hu lemma is_unit_of_dvd_one [comm_monoid α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [comm_cancel_monoid_with_zero α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ dvd_not_unit x y := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, mul_left_cancel₀ hx0 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [comm_cancel_monoid_with_zero α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x ^ m * x ∣ x ^ m * 1, { rw [← pow_succ', mul_one], exact (pow_dvd_pow _ (nat.succ_le_of_lt hmn)).trans h }, rwa [mul_dvd_mul_iff_left, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end section prime variables [comm_monoid_with_zero α] /-- prime element of a `comm_monoid_with_zero` -/ def prime (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime variables {p : α} (hp : prime p) include hp lemma ne_zero : p ≠ 0 := hp.1 lemma not_unit : ¬ is_unit p := hp.2.1 lemma not_dvd_one : ¬ p ∣ 1 := mt (is_unit_of_dvd_one _) hp.not_unit lemma ne_one : p ≠ 1 := λ h, hp.2.1 (h.symm ▸ is_unit_one) lemma dvd_or_dvd (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h lemma dvd_of_dvd_pow (hp : prime p) {a : α} {n : ℕ} (h : p ∣ a^n) : p ∣ a := begin induction n with n ih, { rw pow_zero at h, have := is_unit_of_dvd_one _ h, have := not_unit hp, contradiction }, rw pow_succ at h, cases dvd_or_dvd hp h with dvd_a dvd_pow, { assumption }, exact ih dvd_pow end lemma exists_mem_multiset_dvd {s : multiset α} : p ∣ s.prod → ∃ a ∈ s, p ∣ a := multiset.induction_on s (λ h, (hp.not_dvd_one h).elim) $ λ a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.dvd_or_dvd this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma exists_mem_multiset_map_dvd {s : multiset β} {f : β → α} : p ∣ (s.map f).prod → ∃ a ∈ s, p ∣ f a := λ h, by simpa only [exists_prop, multiset.mem_map, exists_exists_and_eq_and] using hp.exists_mem_multiset_dvd h lemma exists_mem_finset_dvd {s : finset β} {f : β → α} : p ∣ s.prod f → ∃ i ∈ s, p ∣ f i := hp.exists_mem_multiset_map_dvd end prime @[simp] lemma not_prime_zero : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one end prime lemma prime.left_dvd_or_dvd_right_of_dvd_mul [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {a b : α} : a ∣ p * b → p ∣ a ∨ a ∣ b := begin rintro ⟨c, hc⟩, rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩, { exact or.inl h }, { rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc, exact or.inr (hc.symm ▸ dvd_mul_right _ _) } end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ class irreducible [monoid α] (p : α) : Prop := (not_unit' : ¬ is_unit p) (is_unit_or_is_unit' : ∀a b, p = a * b → is_unit a ∨ is_unit b) namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := irreducible.is_unit_or_is_unit' a b h end irreducible lemma irreducible_iff [monoid α] {p : α} : irreducible p ↔ ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible_iff] @[simp] theorem not_irreducible_zero [monoid_with_zero α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [monoid_with_zero α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible_iff] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end protected lemma prime.irreducible [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.dvd_or_dvd (hab ▸ dvd_rfl)).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel₀ (show a ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel₀ (show b ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [mul_right_inj' hp0] at h⟩, (hp.dvd_or_dvd hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/ lemma irreducible.dvd_symm [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q → q ∣ p := begin tactic.unfreeze_local_instances, rintros ⟨q', rfl⟩, rw is_unit.mul_right_dvd (or.resolve_left (of_irreducible_mul hq) hp.not_unit), end lemma irreducible.dvd_comm [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q ↔ q ∣ p := ⟨hp.dvd_symm hq, hq.dvd_symm hp⟩ /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ /-- The setoid of the relation `x ~ᵤ y` iff there is a unit `u` such that `x * u = y` -/ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [monoid_with_zero α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_unit_left {β : Type*} [monoid β] (a u : β) (hu : is_unit u) : associated (a * u) a := let ⟨u', hu⟩ := hu in ⟨u'⁻¹, hu ▸ units.mul_inv_cancel_right _ _⟩ lemma associated_unit_mul_left {β : Type*} [comm_monoid β] (a u : β) (hu : is_unit u) : associated (u * a) a := begin rw mul_comm, exact associated_mul_unit_left _ _ hu end lemma associated_mul_unit_right {β : Type*} [monoid β] (a u : β) (hu : is_unit u) : associated a (a * u) := (associated_mul_unit_left a u hu).symm lemma associated_unit_mul_right {β : Type*} [comm_monoid β] (a u : β) (hu : is_unit u) : associated a (u * a) := (associated_unit_mul_left a u hu).symm lemma associated.mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ lemma associated.mul_left [comm_monoid α] (a : α) {b c : α} (h : b ~ᵤ c) : (a * b) ~ᵤ (a * c) := (associated.refl a).mul_mul h lemma associated.mul_right [comm_monoid α] {a b : α} (h : a ~ᵤ b) (c : α) : (a * c) ~ᵤ (b * c) := h.mul_mul (associated.refl c) lemma associated.pow_pow [comm_monoid α] {a b : α} {n : ℕ} (h : a ~ᵤ b) : a ^ n ~ᵤ b ^ n := begin induction n with n ih, { simp [h] }, convert h.mul_mul ih; rw pow_succ end protected lemma associated.dvd [monoid α] {a b : α} : a ~ᵤ b → a ∣ b := λ ⟨u, hu⟩, ⟨u, hu.symm⟩ protected lemma associated.dvd_dvd [monoid α] {a b : α} (h : a ~ᵤ b) : a ∣ b ∧ b ∣ a := ⟨h.dvd, h.symm.dvd⟩ theorem associated_of_dvd_dvd [cancel_monoid_with_zero α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have hac0 : a * c ≠ 0, { intro con, rw [con, zero_mul] at a_eq, apply ha0 a_eq, }, have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hcd : (c * d) = 1, from mul_left_cancel₀ ha0 this, have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hdc : d * c = 1, from mul_left_cancel₀ hac0 this, exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩ end theorem dvd_dvd_iff_associated [cancel_monoid_with_zero α] {a b : α} : a ∣ b ∧ b ∣ a ↔ a ~ᵤ b := ⟨λ ⟨h1, h2⟩, associated_of_dvd_dvd h1 h2, associated.dvd_dvd⟩ lemma exists_associated_mem_of_dvd_prod [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.dvd_or_dvd hps with h h, { use [a, by simp], cases h with u hu, cases (((hs a (multiset.mem_cons.2 (or.inl rfl))).irreducible) .is_unit_or_is_unit hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma associated.dvd_iff_dvd_left [monoid α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.mul_right_dvd.symm lemma associated.dvd_iff_dvd_right [monoid α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.dvd_mul_right.symm lemma associated.eq_zero_iff [monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma associated.ne_zero_iff [monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := not_congr h.eq_zero_iff protected lemma associated.prime [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨h.ne_zero_iff.1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [units.mul_right_dvd], intros a b, exact hp.dvd_or_dvd }⟩⟩ lemma irreducible.associated_of_dvd [cancel_monoid_with_zero α] {p q : α} (p_irr : irreducible p) (q_irr : irreducible q) (dvd : p ∣ q) : associated p q := associated_of_dvd_dvd dvd (p_irr.dvd_symm q_irr dvd) lemma prime.associated_of_dvd [comm_cancel_monoid_with_zero α] {p q : α} (p_prime : prime p) (q_prime : prime q) (dvd : p ∣ q) : associated p q := p_prime.irreducible.associated_of_dvd q_prime.irreducible dvd lemma associated.prime_iff [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨h.prime, h.symm.prime⟩ protected lemma associated.is_unit [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a → is_unit b := let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩ lemma associated.is_unit_iff [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨h.is_unit, h.symm.is_unit⟩ protected lemma associated.irreducible [monoid α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt h.symm.is_unit hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.is_unit_or_is_unit hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ protected lemma associated.irreducible_iff [monoid α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨h.irreducible, h.symm.irreducible⟩ lemma associated.of_mul_left [comm_cancel_monoid_with_zero α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), mul_left_cancel₀ ha begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated.of_mul_right [comm_cancel_monoid_with_zero α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated.of_mul_left section unique_units variables [monoid α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 theorem associated_iff_eq {x y : α} : x ~ᵤ y ↔ x = y := begin split, { rintro ⟨c, rfl⟩, rw [units_eq_one c, units.coe_one, mul_one] }, { rintro rfl, refl }, end theorem associated_eq_eq : (associated : α → α → Prop) = eq := by { ext, rw associated_iff_eq } end unique_units /-- The quotient of a monoid by the `associated` relation. Two elements `x` and `y` are associated iff there is a unit `u` such that `x * u = y`. There is a natural monoid structure on `associates α`. -/ def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated /-- The canonical quotient map from a monoid `α` into the `associates` of `α` -/ protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) theorem mk_surjective [monoid α] : function.surjective (@associates.mk α _) := forall_associated.2 (λ a, ⟨a, rfl⟩) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ lemma exists_rep [monoid α] (a : associates α) : ∃ a0 : α, associates.mk a0 = a := quot.exists_rep a section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := has_dvd.dvd, le_refl := dvd_refl, le_trans := λ a b c, dvd_trans} @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl /-- `associates.mk` as a `monoid_hom`. -/ protected def mk_monoid_hom : α →* (associates α) := ⟨associates.mk, mk_one, λ x y, mk_mul_mk⟩ @[simp] lemma mk_monoid_hom_apply (a : α) : associates.mk_monoid_hom a = associates.mk a := rfl lemma associated_map_mk {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a ~ᵤ f (associates.mk a) := associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by { rw [← multiset.rel_eq, multiset.rel_map], simp only [mk_eq_mk_iff_associated] } theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem units_eq_one (u : units (associates α)) : u = 1 := units.ext (mul_eq_one_iff.1 u.val_inv).1 instance unique_units : unique (units (associates α)) := { default := 1, uniq := associates.units_eq_one } theorem coe_unit_eq_one (u : units (associates α)): (u : associates α) = 1 := by simp theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx, hy, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := dvd.intro _ (one_mul a) theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [add_sub_cancel_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_monoid_with_zero variables [comm_monoid_with_zero α] @[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ instance : comm_monoid_with_zero (associates α) := { zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] }, mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] }, .. associates.comm_monoid, .. associates.has_zero } instance [nontrivial α] : nontrivial (associates α) := ⟨⟨0, 1, assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this⟩⟩ lemma exists_non_zero_rep {a : associates α} : a ≠ 0 → ∃ a0 : α, a0 ≠ 0 ∧ associates.mk a0 = a := quotient.induction_on a (λ b nz, ⟨b, mt (congr_arg quotient.mk) nz, rfl⟩) theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d) * c, calc b = (a * c) * ↑d : hd.symm ... = a * (↑d * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd theorem mk_dvd_mk {a b : α} : associates.mk a ∣ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq.symm).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match prime.le_or_le hp this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_eq_zero] }, apply and_congr, { rw [is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk], end theorem irreducible_mk (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp only [irreducible_iff, is_unit_mk], apply and_congr iff.rfl, split, { rintro h x y rfl, simpa [is_unit_mk] using h (associates.mk x) (associates.mk y) rfl }, { intros h x y, refine quotient.induction_on₂ x y (assume x y a_eq, _), rcases quotient.exact a_eq.symm with ⟨u, a_eq⟩, rw mul_assoc at a_eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ a_eq.symm } end theorem mk_dvd_not_unit_mk_iff {a b : α} : dvd_not_unit (associates.mk a) (associates.mk b) ↔ dvd_not_unit a b := begin rw [dvd_not_unit, dvd_not_unit, ne, ne, mk_eq_zero], apply and_congr_right, intro ane0, split, { contrapose!, rw forall_associated, intros h x hx hbax, rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax, cases hbax with u hu, apply h (x * ↑u⁻¹), { rw is_unit_mk at hx, rw associated.is_unit_iff, apply hx, use u, simp, }, simp [← mul_assoc, ← hu] }, { rintro ⟨x, ⟨hx, rfl⟩⟩, use associates.mk x, simp [is_unit_mk, mk_mul_mk, hx], } end theorem dvd_not_unit_of_lt {a b : associates α} (hlt : a < b) : dvd_not_unit a b := begin split, { rintro rfl, apply not_lt_of_le _ hlt, apply dvd_zero }, rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩, refine ⟨x, _, rfl⟩, contrapose! ndvd, rcases ndvd with ⟨u, rfl⟩, simp, end end comm_monoid_with_zero section comm_cancel_monoid_with_zero variable [comm_cancel_monoid_with_zero α] instance : partial_order (associates α) := { le_antisymm := λ a' b', quotient.induction_on₂ a' b' (λ a b hab hba, quot.sound $ associated_of_dvd_dvd (dvd_of_mk_le_mk hab) (dvd_of_mk_le_mk hba)) .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, (mul_zero a).symm⟩, .. associates.partial_order } instance : no_zero_divisors (associates α) := ⟨λ x y, (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩ theorem irreducible_iff_prime_iff : (∀ a : α, irreducible a ↔ prime a) ↔ (∀ a : (associates α), irreducible a ↔ prime a) := begin rw forall_associated, split; intros h a; have ha := h a; rw irreducible_mk at *; rw prime_mk at *; exact ha, end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, mul_left_cancel₀ (mt mk_eq_zero.2 ha) hu⟩ end lemma eq_of_mul_eq_mul_right : ∀(a b c : associates α), b ≠ 0 → a * b = c * b → a = c := λ a b c bne0, (mul_comm b a) ▸ (mul_comm b c) ▸ (eq_of_mul_eq_mul_left b a c bne0) lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d dvd_rfl with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end instance : comm_cancel_monoid_with_zero (associates α) := { mul_left_cancel_of_ne_zero := eq_of_mul_eq_mul_left, mul_right_cancel_of_ne_zero := eq_of_mul_eq_mul_right, .. (infer_instance : comm_monoid_with_zero (associates α)) } theorem dvd_not_unit_iff_lt {a b : associates α} : dvd_not_unit a b ↔ a < b := dvd_and_not_dvd_iff.symm end comm_cancel_monoid_with_zero end associates namespace multiset lemma prod_ne_zero_of_prime [comm_cancel_monoid_with_zero α] [nontrivial α] (s : multiset α) (h : ∀ x ∈ s, prime x) : s.prod ≠ 0 := multiset.prod_ne_zero (λ h0, prime.ne_zero (h 0 h0) rfl) end multiset
4fd153d1c076656447b5d971833cbc5d08bc3f2b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/equivalence.lean
52438ce9cf1711696d721eb77e1efe185b3ea174
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
8,482
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.fully_faithful import category_theory.natural_isomorphism import tactic.slice import tactic.converter.interactive namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation structure equivalence (C : Sort u₁) [category.{v₁} C] (D : Sort u₂) [category.{v₂} D] := (functor : C ⥤ D) (inverse : D ⥤ C) (fun_inv_id' : (functor ⋙ inverse) ≅ (category_theory.functor.id C) . obviously) (inv_fun_id' : (inverse ⋙ functor) ≅ (category_theory.functor.id D) . obviously) restate_axiom equivalence.fun_inv_id' restate_axiom equivalence.inv_fun_id' infixr ` ≌ `:10 := equivalence namespace equivalence variables {C : Sort u₁} [𝒞 : category.{v₁} C] include 𝒞 @[refl] def refl : C ≌ C := { functor := functor.id C, inverse := functor.id C } variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 @[symm] def symm (e : C ≌ D) : D ≌ C := { functor := e.inverse, inverse := e.functor, fun_inv_id' := e.inv_fun_id, inv_fun_id' := e.fun_inv_id } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = (e.inv_fun_id.hom.app X) ≫ f ≫ (e.inv_fun_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = (e.fun_inv_id.hom.app X) ≫ f ≫ (e.fun_inv_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end variables {E : Sort u₃} [ℰ : category.{v₃} E] include ℰ @[simp] private def effe_iso_id (e : C ≌ D) (f : D ≌ E) (X : C) : (e.inverse).obj ((f.inverse).obj ((f.functor).obj ((e.functor).obj X))) ≅ X := calc (e.inverse).obj ((f.inverse).obj ((f.functor).obj ((e.functor).obj X))) ≅ (e.inverse).obj ((e.functor).obj X) : e.inverse.map_iso (nat_iso.app f.fun_inv_id _) ... ≅ X : nat_iso.app e.fun_inv_id _ @[simp] private def feef_iso_id (e : C ≌ D) (f : D ≌ E) (X : E) : (f.functor).obj ((e.functor).obj ((e.inverse).obj ((f.inverse).obj X))) ≅ X := calc (f.functor).obj ((e.functor).obj ((e.inverse).obj ((f.inverse).obj X))) ≅ (f.functor).obj ((f.inverse).obj X) : f.functor.map_iso (nat_iso.app e.inv_fun_id _) ... ≅ X : nat_iso.app f.inv_fun_id _ @[trans] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, fun_inv_id' := nat_iso.of_components (effe_iso_id e f) begin /- `tidy` says -/ intros X Y f_1, dsimp at *, simp at *, dsimp at *, /- `rewrite_search` says -/ slice_lhs 3 4 { erw [is_iso.hom_inv_id] }, erw [category.id_comp, is_iso.hom_inv_id, category.comp_id], end, inv_fun_id' := nat_iso.of_components (feef_iso_id e f) begin /- `tidy` says -/ intros X Y f_1, dsimp at *, simp at *, dsimp at *, /- `rewrite_search` says -/ slice_lhs 3 4 { erw [is_iso.hom_inv_id] }, erw [category.id_comp, is_iso.hom_inv_id, category.comp_id] end } end equivalence variables {C : Sort u₁} [𝒞 : category.{v₁} C] include 𝒞 section variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 class is_equivalence (F : C ⥤ D) := (inverse : D ⥤ C) (fun_inv_id' : (F ⋙ inverse) ≅ (functor.id C) . obviously) (inv_fun_id' : (inverse ⋙ F) ≅ (functor.id D) . obviously) restate_axiom is_equivalence.fun_inv_id' restate_axiom is_equivalence.inv_fun_id' end namespace is_equivalence variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 instance of_equivalence (F : C ≌ D) : is_equivalence (F.functor) := { inverse := F.inverse, fun_inv_id' := F.fun_inv_id, inv_fun_id' := F.inv_fun_id } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence (F.inverse) := { inverse := F.functor, fun_inv_id' := F.inv_fun_id, inv_fun_id' := F.fun_inv_id } end is_equivalence namespace functor instance is_equivalence_refl : is_equivalence (functor.id C) := { inverse := functor.id C } end functor variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 namespace functor def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_symm (F : C ⥤ D) [is_equivalence F] : is_equivalence (F.inv) := { inverse := F, fun_inv_id' := is_equivalence.inv_fun_id F, inv_fun_id' := is_equivalence.fun_inv_id F } def fun_inv_id (F : C ⥤ D) [is_equivalence F] : (F ⋙ F.inv) ≅ functor.id C := is_equivalence.fun_inv_id F def inv_fun_id (F : C ⥤ D) [is_equivalence F] : (F.inv ⋙ F) ≅ functor.id D := is_equivalence.inv_fun_id F def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := { functor := F, inverse := is_equivalence.inverse F, fun_inv_id' := is_equivalence.fun_inv_id F, inv_fun_id' := is_equivalence.inv_fun_id F } variables {E : Sort u₃} [ℰ : category.{v₃} E] include ℰ instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace is_equivalence instance is_equivalence_functor (e : C ≌ D) : is_equivalence e.functor := { inverse := e.inverse, fun_inv_id' := e.fun_inv_id, inv_fun_id' := e.inv_fun_id } instance is_equivalence_inverse (e : C ≌ D) : is_equivalence e.inverse := { inverse := e.functor, fun_inv_id' := e.inv_fun_id, inv_fun_id' := e.fun_inv_id } @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = (F.inv_fun_id.hom.app X) ≫ f ≫ (F.inv_fun_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = (F.fun_inv_id.hom.app X) ≫ f ≫ (F.fun_inv_id.inv.app Y) := begin erw [nat_iso.naturality_2], refl end end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F.obj (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{v₁ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F.obj (F.obj_preimage d) ≅ d := ess_surj.iso F d end functor namespace equivalence def ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨ λ Y : D, F.inv.obj Y, λ Y : D, (nat_iso.app F.inv_fun_id Y) ⟩ instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { injectivity' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simp at *, assumption end }. instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, (nat_iso.app F.fun_inv_id X).inv ≫ (F.inv.map f) ≫ (nat_iso.app F.fun_inv_id Y).hom, witness' := λ X Y f, begin apply F.inv.injectivity, /- obviously can finish from here... -/ dsimp, simp, dsimp, slice_lhs 4 6 { rw [←functor.map_comp, ←functor.map_comp], rw [←is_equivalence.fun_inv_map], }, slice_lhs 1 2 { simp }, dsimp, simp, slice_lhs 2 4 { rw [←functor.map_comp, ←functor.map_comp], erw [nat_iso.naturality_2], }, erw [nat_iso.naturality_1], refl, end }. section @[simp] private def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.injectivity, tidy, end, map_comp' := λ X Y Z f g, by apply F.injectivity; simp }. def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful : faithful F] [ess_surj F] : is_equivalence F := { inverse := equivalence_inverse F, fun_inv_id' := nat_iso.of_components (λ X, preimage_iso (F.fun_obj_preimage_iso (F.obj X))) (λ X Y f, begin apply F.injectivity, obviously, end), inv_fun_id' := nat_iso.of_components (λ Y, (F.fun_obj_preimage_iso Y)) (by obviously) } end end equivalence end category_theory
f0f369f1b2bdda4fae156a1311ec7055c00880c6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/filter/ennreal.lean
a061290a9960bcd0f7f362f0844c7649aa98f5cd
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,897
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import data.real.ennreal import order.filter.countable_Inter import order.liminf_limsup /-! # Order properties of extended non-negative reals This file compiles filter-related results about `ℝ≥0∞` (see data/real/ennreal.lean). -/ open filter open_locale filter ennreal namespace ennreal variables {α : Type*} {f : filter α} lemma eventually_le_limsup [countable_Inter_filter f] (u : α → ℝ≥0∞) : ∀ᶠ y in f, u y ≤ f.limsup u := begin by_cases hx_top : f.limsup u = ⊤, { simp_rw hx_top, exact eventually_of_forall (λ a, le_top), }, have h_forall_le : ∀ᶠ y in f, ∀ n : ℕ, u y < f.limsup u + (1:ℝ≥0∞)/n, { rw eventually_countable_forall, refine λ n, eventually_lt_of_limsup_lt _, nth_rewrite 0 ←add_zero (f.limsup u), exact (ennreal.add_lt_add_iff_left hx_top).mpr (by simp), }, refine h_forall_le.mono (λ y hy, le_of_forall_pos_le_add (λ r hr_pos hx_top, _)), have hr_ne_zero : (r : ℝ≥0∞) ≠ 0, { rw [ne.def, coe_eq_zero], exact (ne_of_lt hr_pos).symm, }, cases (exists_inv_nat_lt hr_ne_zero) with i hi, rw inv_eq_one_div at hi, exact (hy i).le.trans (add_le_add_left hi.le (f.limsup u)), end lemma limsup_eq_zero_iff [countable_Inter_filter f] {u : α → ℝ≥0∞} : f.limsup u = 0 ↔ u =ᶠ[f] 0 := begin split; intro h, { have hu_zero := eventually_le.trans (eventually_le_limsup u) (eventually_of_forall (λ _, le_of_eq h)), exact hu_zero.mono (λ x hx, le_antisymm hx (zero_le _)), }, { rw limsup_congr h, simp_rw [pi.zero_apply, ←ennreal.bot_eq_zero, limsup_const_bot] }, end lemma limsup_const_mul_of_ne_top {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha_top : a ≠ ⊤) : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_zero : a = 0, { simp_rw [ha_zero, zero_mul, ←ennreal.bot_eq_zero], exact limsup_const_bot, }, let g := λ x : ℝ≥0∞, a * x, have hg_bij : function.bijective g, from function.bijective_iff_has_inverse.mpr ⟨(λ x, a⁻¹ * x), ⟨λ x, by simp [←mul_assoc, inv_mul_cancel ha_zero ha_top], λ x, by simp [g, ←mul_assoc, mul_inv_cancel ha_zero ha_top]⟩⟩, have hg_mono : strict_mono g, from monotone.strict_mono_of_injective (λ _ _ _, by rwa mul_le_mul_left ha_zero ha_top) hg_bij.1, let g_iso := strict_mono.order_iso_of_surjective g hg_mono hg_bij.2, refine (order_iso.limsup_apply g_iso _ _ _ _).symm, all_goals { is_bounded_default }, end lemma limsup_const_mul [countable_Inter_filter f] {u : α → ℝ≥0∞} {a : ℝ≥0∞} : f.limsup (λ (x : α), a * (u x)) = a * f.limsup u := begin by_cases ha_top : a ≠ ⊤, { exact limsup_const_mul_of_ne_top ha_top, }, push_neg at ha_top, by_cases hu : u =ᶠ[f] 0, { have hau : (λ x, a * (u x)) =ᶠ[f] 0, { refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, simp only [limsup_congr hu, limsup_congr hau, pi.zero_apply, ← bot_eq_zero, limsup_const_bot], simp, }, { simp_rw [ha_top, top_mul], have hu_mul : ∃ᶠ (x : α) in f, ⊤ ≤ ite (u x = 0) (0 : ℝ≥0∞) ⊤, { rw [eventually_eq, not_eventually] at hu, refine hu.mono (λ x hx, _), rw pi.zero_apply at hx, simp [hx], }, have h_top_le : f.limsup (λ (x : α), ite (u x = 0) (0 : ℝ≥0∞) ⊤) = ⊤, from eq_top_iff.mpr (le_limsup_of_frequently_le hu_mul), have hfu : f.limsup u ≠ 0, from mt limsup_eq_zero_iff.1 hu, simp only [h_top_le, hfu, if_false], }, end lemma limsup_mul_le [countable_Inter_filter f] (u v : α → ℝ≥0∞) : f.limsup (u * v) ≤ f.limsup u * f.limsup v := calc f.limsup (u * v) ≤ f.limsup (λ x, (f.limsup u) * v x) : begin refine limsup_le_limsup _ _, { filter_upwards [@eventually_le_limsup _ f _ u] with x hx, exact ennreal.mul_le_mul hx le_rfl, }, { is_bounded_default, }, end ... = f.limsup u * f.limsup v : limsup_const_mul lemma limsup_add_le [countable_Inter_filter f] (u v : α → ℝ≥0∞) : f.limsup (u + v) ≤ f.limsup u + f.limsup v := Inf_le ((eventually_le_limsup u).mp ((eventually_le_limsup v).mono (λ _ hxg hxf, add_le_add hxf hxg))) lemma limsup_liminf_le_liminf_limsup {β} [countable β] {f : filter α} [countable_Inter_filter f] {g : filter β} (u : α → β → ℝ≥0∞) : f.limsup (λ (a : α), g.liminf (λ (b : β), u a b)) ≤ g.liminf (λ b, f.limsup (λ a, u a b)) := begin have h1 : ∀ᶠ a in f, ∀ b, u a b ≤ f.limsup (λ a', u a' b), by { rw eventually_countable_forall, exact λ b, ennreal.eventually_le_limsup (λ a, u a b), }, refine Inf_le (h1.mono (λ x hx, filter.liminf_le_liminf (filter.eventually_of_forall hx) _)), filter.is_bounded_default, end end ennreal
bafa5e6cc41a0c1c644f8b4ab8d04bb61ca0a4d4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/forErrors.lean
8d36e094106f008154662710fc33d2ecf10f7bd0
[ "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
205
lean
def g (xs ys : List Nat) (a : α) : IO Nat := do let mut sum := 0 for x in xs, y in ys, c in a, z in ys do sum := x + sum IO.println s!"x: {x}, y: {y}, a: {a}, c: {c}, sum: {sum}" return sum
3883360f0e3dd720eb4900f5385881beb6f93c40
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/affine_space/ordered.lean
7b218d4cc0d0546086f80366fca431c49326576e
[ "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
12,429
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.order.invertible import algebra.order.module import linear_algebra.affine_space.midpoint import linear_algebra.affine_space.slope import tactic.field_simp /-! # Ordered modules as affine spaces In this file we prove some theorems about `slope` and `line_map` in the case when the module `E` acting on the codomain `PE` of a function is an ordered module over its domain `k`. We also prove inequalities that can be used to link convexity of a function on an interval to monotonicity of the slope, see section docstring below for details. ## Implementation notes We do not introduce the notion of ordered affine spaces (yet?). Instead, we prove various theorems for an ordered module interpreted as an affine space. ## Tags affine space, ordered module, slope -/ open affine_map variables {k E PE : Type*} /-! ### Monotonicity of `line_map` In this section we prove that `line_map a b r` is monotone (strictly or not) in its arguments if other arguments belong to specific domains. -/ section ordered_ring variables [ordered_ring k] [ordered_add_comm_group E] [module k E] [ordered_smul k E] variables {a a' b b' : E} {r r' : k} lemma line_map_mono_left (ha : a ≤ a') (hr : r ≤ 1) : line_map a b r ≤ line_map a' b r := begin simp only [line_map_apply_module], exact add_le_add_right (smul_le_smul_of_nonneg ha (sub_nonneg.2 hr)) _ end lemma line_map_strict_mono_left (ha : a < a') (hr : r < 1) : line_map a b r < line_map a' b r := begin simp only [line_map_apply_module], exact add_lt_add_right (smul_lt_smul_of_pos ha (sub_pos.2 hr)) _ end lemma line_map_mono_right (hb : b ≤ b') (hr : 0 ≤ r) : line_map a b r ≤ line_map a b' r := begin simp only [line_map_apply_module], exact add_le_add_left (smul_le_smul_of_nonneg hb hr) _ end lemma line_map_strict_mono_right (hb : b < b') (hr : 0 < r) : line_map a b r < line_map a b' r := begin simp only [line_map_apply_module], exact add_lt_add_left (smul_lt_smul_of_pos hb hr) _ end lemma line_map_mono_endpoints (ha : a ≤ a') (hb : b ≤ b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : line_map a b r ≤ line_map a' b' r := (line_map_mono_left ha h₁).trans (line_map_mono_right hb h₀) lemma line_map_strict_mono_endpoints (ha : a < a') (hb : b < b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) : line_map a b r < line_map a' b' r := begin rcases h₀.eq_or_lt with (rfl|h₀), { simpa }, exact (line_map_mono_left ha.le h₁).trans_lt (line_map_strict_mono_right hb h₀) end lemma line_map_lt_line_map_iff_of_lt (h : r < r') : line_map a b r < line_map a b r' ↔ a < b := begin simp only [line_map_apply_module], rw [← lt_sub_iff_add_lt, add_sub_assoc, ← sub_lt_iff_lt_add', ← sub_smul, ← sub_smul, sub_sub_sub_cancel_left, smul_lt_smul_iff_of_pos (sub_pos.2 h)], apply_instance, end lemma left_lt_line_map_iff_lt (h : 0 < r) : a < line_map a b r ↔ a < b := iff.trans (by rw line_map_apply_zero) (line_map_lt_line_map_iff_of_lt h) lemma line_map_lt_left_iff_lt (h : 0 < r) : line_map a b r < a ↔ b < a := @left_lt_line_map_iff_lt k Eᵒᵈ _ _ _ _ _ _ _ h lemma line_map_lt_right_iff_lt (h : r < 1) : line_map a b r < b ↔ a < b := iff.trans (by rw line_map_apply_one) (line_map_lt_line_map_iff_of_lt h) lemma right_lt_line_map_iff_lt (h : r < 1) : b < line_map a b r ↔ b < a := @line_map_lt_right_iff_lt k Eᵒᵈ _ _ _ _ _ _ _ h end ordered_ring section linear_ordered_ring variables [linear_ordered_ring k] [ordered_add_comm_group E] [module k E] [ordered_smul k E] [invertible (2:k)] {a a' b b' : E} {r r' : k} lemma midpoint_le_midpoint (ha : a ≤ a') (hb : b ≤ b') : midpoint k a b ≤ midpoint k a' b' := line_map_mono_endpoints ha hb (inv_of_nonneg.2 zero_le_two) $ inv_of_le_one one_le_two end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field k] [ordered_add_comm_group E] variables [module k E] [ordered_smul k E] section variables {a b : E} {r r' : k} lemma line_map_le_line_map_iff_of_lt (h : r < r') : line_map a b r ≤ line_map a b r' ↔ a ≤ b := begin simp only [line_map_apply_module], rw [← le_sub_iff_add_le, add_sub_assoc, ← sub_le_iff_le_add', ← sub_smul, ← sub_smul, sub_sub_sub_cancel_left, smul_le_smul_iff_of_pos (sub_pos.2 h)], apply_instance, end lemma left_le_line_map_iff_le (h : 0 < r) : a ≤ line_map a b r ↔ a ≤ b := iff.trans (by rw line_map_apply_zero) (line_map_le_line_map_iff_of_lt h) @[simp] lemma left_le_midpoint : a ≤ midpoint k a b ↔ a ≤ b := left_le_line_map_iff_le $ inv_pos.2 zero_lt_two lemma line_map_le_left_iff_le (h : 0 < r) : line_map a b r ≤ a ↔ b ≤ a := @left_le_line_map_iff_le k Eᵒᵈ _ _ _ _ _ _ _ h @[simp] lemma midpoint_le_left : midpoint k a b ≤ a ↔ b ≤ a := line_map_le_left_iff_le $ inv_pos.2 zero_lt_two lemma line_map_le_right_iff_le (h : r < 1) : line_map a b r ≤ b ↔ a ≤ b := iff.trans (by rw line_map_apply_one) (line_map_le_line_map_iff_of_lt h) @[simp] lemma midpoint_le_right : midpoint k a b ≤ b ↔ a ≤ b := line_map_le_right_iff_le $ inv_lt_one one_lt_two lemma right_le_line_map_iff_le (h : r < 1) : b ≤ line_map a b r ↔ b ≤ a := @line_map_le_right_iff_le k Eᵒᵈ _ _ _ _ _ _ _ h @[simp] lemma right_le_midpoint : b ≤ midpoint k a b ↔ b ≤ a := right_le_line_map_iff_le $ inv_lt_one one_lt_two end /-! ### Convexity and slope Given an interval `[a, b]` and a point `c ∈ (a, b)`, `c = line_map a b r`, there are a few ways to say that the point `(c, f c)` is above/below the segment `[(a, f a), (b, f b)]`: * compare `f c` to `line_map (f a) (f b) r`; * compare `slope f a c` to `slope `f a b`; * compare `slope f c b` to `slope f a b`; * compare `slope f a c` to `slope f c b`. In this section we prove equivalence of these four approaches. In order to make the statements more readable, we introduce local notation `c = line_map a b r`. Then we prove lemmas like ``` lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b := ``` For each inequality between `f c` and `line_map (f a) (f b) r` we provide 3 lemmas: * `*_left` relates it to an inequality on `slope f a c` and `slope f a b`; * `*_right` relates it to an inequality on `slope f a b` and `slope f c b`; * no-suffix version relates it to an inequality on `slope f a c` and `slope f c b`. These inequalities can by used in to restate `convex_on` in terms of monotonicity of the slope. -/ variables {f : k → E} {a b r : k} local notation `c` := line_map a b r /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f a b`. -/ lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b := begin rw [line_map_apply, line_map_apply, slope, slope, vsub_eq_sub, vsub_eq_sub, vsub_eq_sub, vadd_eq_add, vadd_eq_add, smul_eq_mul, add_sub_cancel, smul_sub, smul_sub, smul_sub, sub_le_iff_le_add, mul_inv_rev, mul_smul, mul_smul, ←smul_sub, ←smul_sub, ←smul_add, smul_smul, ← mul_inv_rev, inv_smul_le_iff h, smul_smul, mul_inv_cancel_right₀ (right_ne_zero_of_mul h.ne'), smul_add, smul_inv_smul₀ (left_ne_zero_of_mul h.ne')], apply_instance end /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f a c`. -/ lemma line_map_le_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) : line_map (f a) (f b) r ≤ f c ↔ slope f a b ≤ slope f a c := @map_le_line_map_iff_slope_le_slope_left k Eᵒᵈ _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f a b`. -/ lemma map_lt_line_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) : f c < line_map (f a) (f b) r ↔ slope f a c < slope f a b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_left h) (map_le_line_map_iff_slope_le_slope_left h) /-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f a c`. -/ lemma line_map_lt_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) : line_map (f a) (f b) r < f c ↔ slope f a b < slope f a c := @map_lt_line_map_iff_slope_lt_slope_left k Eᵒᵈ _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f c b`. -/ lemma map_le_line_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) : f c ≤ line_map (f a) (f b) r ↔ slope f a b ≤ slope f c b := begin rw [← line_map_apply_one_sub, ← line_map_apply_one_sub _ _ r], revert h, generalize : 1 - r = r', clear r, intro h, simp_rw [line_map_apply, slope, vsub_eq_sub, vadd_eq_add, smul_eq_mul], rw [sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_mul_neg, neg_sub, le_inv_smul_iff h, smul_smul, mul_inv_cancel_right₀, le_sub_comm, ← neg_sub (f b), smul_neg, neg_add_eq_sub], { exact right_ne_zero_of_mul h.ne' }, { apply_instance } end /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a b`. -/ lemma line_map_le_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) : line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a b := @map_le_line_map_iff_slope_le_slope_right k Eᵒᵈ _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f c b`. -/ lemma map_lt_line_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) : f c < line_map (f a) (f b) r ↔ slope f a b < slope f c b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_right h) (map_le_line_map_iff_slope_le_slope_right h) /-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a b`. -/ lemma line_map_lt_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) : line_map (f a) (f b) r < f c ↔ slope f c b < slope f a b := @map_lt_line_map_iff_slope_lt_slope_right k Eᵒᵈ _ _ _ _ f a b r h /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f c b`. -/ lemma map_le_line_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f c b := begin rw [map_le_line_map_iff_slope_le_slope_left (mul_pos h₀ (sub_pos.2 hab)), ← line_map_slope_line_map_slope_line_map f a b r, right_le_line_map_iff_le h₁], apply_instance, apply_instance, end /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a c`. -/ lemma line_map_le_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a c := @map_le_line_map_iff_slope_le_slope k Eᵒᵈ _ _ _ _ _ _ _ _ hab h₀ h₁ /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly below the segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f c b`. -/ lemma map_lt_line_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : f c < line_map (f a) (f b) r ↔ slope f a c < slope f c b := lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope hab h₀ h₁) (map_le_line_map_iff_slope_le_slope hab h₀ h₁) /-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly above the segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a c`. -/ lemma line_map_lt_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) : line_map (f a) (f b) r < f c ↔ slope f c b < slope f a c := @map_lt_line_map_iff_slope_lt_slope k Eᵒᵈ _ _ _ _ _ _ _ _ hab h₀ h₁ end linear_ordered_field
ced42e4d0d138803a3c531ff59bc02f1b6ec6e54
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/category/CompHaus/default.lean
33fb3285809a2e7d00b3f9c2ae041f1f0f43d3d8
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
9,608
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Bhavik Mehta -/ import category_theory.adjunction.reflective import topology.category.Top import topology.stone_cech import category_theory.monad.limits import topology.urysohns_lemma /-! # The category of Compact Hausdorff Spaces We construct the category of compact Hausdorff spaces. The type of compact Hausdorff spaces is denoted `CompHaus`, and it is endowed with a category instance making it a full subcategory of `Top`. The fully faithful functor `CompHaus ⥤ Top` is denoted `CompHaus_to_Top`. **Note:** The file `topology/category/Compactum.lean` provides the equivalence between `Compactum`, which is defined as the category of algebras for the ultrafilter monad, and `CompHaus`. `Compactum_to_CompHaus` is the functor from `Compactum` to `CompHaus` which is proven to be an equivalence of categories in `Compactum_to_CompHaus.is_equivalence`. See `topology/category/Compactum.lean` for a more detailed discussion where these definitions are introduced. -/ universes v u open category_theory /-- The type of Compact Hausdorff topological spaces. -/ structure CompHaus := (to_Top : Top) [is_compact : compact_space to_Top] [is_hausdorff : t2_space to_Top] namespace CompHaus instance : inhabited CompHaus := ⟨{to_Top := { α := pempty }}⟩ instance : has_coe_to_sort CompHaus Type* := ⟨λ X, X.to_Top⟩ instance {X : CompHaus} : compact_space X := X.is_compact instance {X : CompHaus} : t2_space X := X.is_hausdorff instance category : category CompHaus := induced_category.category to_Top instance concrete_category : concrete_category CompHaus := induced_category.concrete_category _ @[simp] lemma coe_to_Top {X : CompHaus} : (X.to_Top : Type*) = X := rfl variables (X : Type*) [topological_space X] [compact_space X] [t2_space X] /-- A constructor for objects of the category `CompHaus`, taking a type, and bundling the compact Hausdorff topology found by typeclass inference. -/ def of : CompHaus := { to_Top := Top.of X, is_compact := ‹_›, is_hausdorff := ‹_› } @[simp] lemma coe_of : (CompHaus.of X : Type _) = X := rfl /-- Any continuous function on compact Hausdorff spaces is a closed map. -/ lemma is_closed_map {X Y : CompHaus.{u}} (f : X ⟶ Y) : is_closed_map f := λ C hC, (hC.is_compact.image f.continuous).is_closed /-- Any continuous bijection of compact Hausdorff spaces is an isomorphism. -/ lemma is_iso_of_bijective {X Y : CompHaus.{u}} (f : X ⟶ Y) (bij : function.bijective f) : is_iso f := begin let E := equiv.of_bijective _ bij, have hE : continuous E.symm, { rw continuous_iff_is_closed, intros S hS, rw ← E.image_eq_preimage, exact is_closed_map f S hS }, refine ⟨⟨⟨E.symm, hE⟩, _, _⟩⟩, { ext x, apply E.symm_apply_apply }, { ext x, apply E.apply_symm_apply } end /-- Any continuous bijection of compact Hausdorff spaces induces an isomorphism. -/ noncomputable def iso_of_bijective {X Y : CompHaus.{u}} (f : X ⟶ Y) (bij : function.bijective f) : X ≅ Y := by letI := is_iso_of_bijective _ bij; exact as_iso f end CompHaus /-- The fully faithful embedding of `CompHaus` in `Top`. -/ @[simps {rhs_md := semireducible}, derive [full, faithful]] def CompHaus_to_Top : CompHaus.{u} ⥤ Top.{u} := induced_functor _ instance CompHaus.forget_reflects_isomorphisms : reflects_isomorphisms (forget CompHaus.{u}) := ⟨by introsI A B f hf; exact CompHaus.is_iso_of_bijective _ ((is_iso_iff_bijective f).mp hf)⟩ /-- (Implementation) The object part of the compactification functor from topological spaces to compact Hausdorff spaces. -/ @[simps] def StoneCech_obj (X : Top) : CompHaus := CompHaus.of (stone_cech X) /-- (Implementation) The bijection of homsets to establish the reflective adjunction of compact Hausdorff spaces in topological spaces. -/ noncomputable def stone_cech_equivalence (X : Top.{u}) (Y : CompHaus.{u}) : (StoneCech_obj X ⟶ Y) ≃ (X ⟶ CompHaus_to_Top.obj Y) := { to_fun := λ f, { to_fun := f ∘ stone_cech_unit, continuous_to_fun := f.2.comp (@continuous_stone_cech_unit X _) }, inv_fun := λ f, { to_fun := stone_cech_extend f.2, continuous_to_fun := continuous_stone_cech_extend f.2 }, left_inv := begin rintro ⟨f : stone_cech X ⟶ Y, hf : continuous f⟩, ext (x : stone_cech X), refine congr_fun _ x, apply continuous.ext_on dense_range_stone_cech_unit (continuous_stone_cech_extend _) hf, rintro _ ⟨y, rfl⟩, apply congr_fun (stone_cech_extend_extends (hf.comp _)) y, end, right_inv := begin rintro ⟨f : (X : Type*) ⟶ Y, hf : continuous f⟩, ext, exact congr_fun (stone_cech_extend_extends hf) _, end } /-- The Stone-Cech compactification functor from topological spaces to compact Hausdorff spaces, left adjoint to the inclusion functor. -/ noncomputable def Top_to_CompHaus : Top.{u} ⥤ CompHaus.{u} := adjunction.left_adjoint_of_equiv stone_cech_equivalence.{u} (λ _ _ _ _ _, rfl) lemma Top_to_CompHaus_obj (X : Top) : ↥(Top_to_CompHaus.obj X) = stone_cech X := rfl /-- The category of compact Hausdorff spaces is reflective in the category of topological spaces. -/ noncomputable instance CompHaus_to_Top.reflective : reflective CompHaus_to_Top := { to_is_right_adjoint := ⟨Top_to_CompHaus, adjunction.adjunction_of_equiv_left _ _⟩ } noncomputable instance CompHaus_to_Top.creates_limits : creates_limits CompHaus_to_Top := monadic_creates_limits _ instance CompHaus.has_limits : limits.has_limits CompHaus := has_limits_of_has_limits_creates_limits CompHaus_to_Top instance CompHaus.has_colimits : limits.has_colimits CompHaus := has_colimits_of_reflective CompHaus_to_Top namespace CompHaus /-- An explicit limit cone for a functor `F : J ⥤ CompHaus`, defined in terms of `Top.limit_cone`. -/ def limit_cone {J : Type v} [small_category J] (F : J ⥤ CompHaus.{max v u}) : limits.cone F := { X := { to_Top := (Top.limit_cone (F ⋙ CompHaus_to_Top)).X, is_compact := begin show compact_space ↥{u : Π j, (F.obj j) | ∀ {i j : J} (f : i ⟶ j), (F.map f) (u i) = u j}, rw ← is_compact_iff_compact_space, apply is_closed.is_compact, have : {u : Π j, F.obj j | ∀ {i j : J} (f : i ⟶ j), F.map f (u i) = u j} = ⋂ (i j : J) (f : i ⟶ j), {u | F.map f (u i) = u j}, { ext1, simp only [set.mem_Inter, set.mem_set_of_eq], }, rw this, apply is_closed_Inter, intros i, apply is_closed_Inter, intros j, apply is_closed_Inter, intros f, apply is_closed_eq, { exact (continuous_map.continuous (F.map f)).comp (continuous_apply i), }, { exact continuous_apply j, } end, is_hausdorff := show t2_space ↥{u : Π j, (F.obj j) | ∀ {i j : J} (f : i ⟶ j), (F.map f) (u i) = u j}, from infer_instance }, π := { app := λ j, (Top.limit_cone (F ⋙ CompHaus_to_Top)).π.app j, naturality' := by { intros _ _ _, ext ⟨x, hx⟩, simp only [comp_apply, functor.const_obj_map, id_apply], exact (hx f).symm, } } } /-- The limit cone `CompHaus.limit_cone F` is indeed a limit cone. -/ def limit_cone_is_limit {J : Type v} [small_category J] (F : J ⥤ CompHaus.{max v u}) : limits.is_limit (limit_cone F) := { lift := λ S, (Top.limit_cone_is_limit (F ⋙ CompHaus_to_Top)).lift (CompHaus_to_Top.map_cone S), uniq' := λ S m h, (Top.limit_cone_is_limit _).uniq (CompHaus_to_Top.map_cone S) _ h } lemma epi_iff_surjective {X Y : CompHaus.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { contrapose!, rintros ⟨y, hy⟩ hf, let C := set.range f, have hC : is_closed C := (is_compact_range f.continuous).is_closed, let D := {y}, have hD : is_closed D := is_closed_singleton, have hCD : disjoint C D, { rw set.disjoint_singleton_right, rintro ⟨y', hy'⟩, exact hy y' hy' }, haveI : normal_space ↥(Y.to_Top) := normal_of_compact_t2, obtain ⟨φ, hφ0, hφ1, hφ01⟩ := exists_continuous_zero_one_of_closed hC hD hCD, haveI : compact_space (ulift.{u} $ set.Icc (0:ℝ) 1) := homeomorph.ulift.symm.compact_space, haveI : t2_space (ulift.{u} $ set.Icc (0:ℝ) 1) := homeomorph.ulift.symm.t2_space, let Z := of (ulift.{u} $ set.Icc (0:ℝ) 1), let g : Y ⟶ Z := ⟨λ y', ⟨⟨φ y', hφ01 y'⟩⟩, continuous_ulift_up.comp (φ.continuous.subtype_mk (λ y', hφ01 y'))⟩, let h : Y ⟶ Z := ⟨λ _, ⟨⟨0, set.left_mem_Icc.mpr zero_le_one⟩⟩, continuous_const⟩, have H : h = g, { rw ← cancel_epi f, ext x, dsimp, simp only [comp_apply, continuous_map.coe_mk, subtype.coe_mk, hφ0 (set.mem_range_self x), pi.zero_apply], }, apply_fun (λ e, (e y).down) at H, dsimp at H, simp only [subtype.mk_eq_mk, hφ1 (set.mem_singleton y), pi.one_apply] at H, exact zero_ne_one H, }, { rw ← category_theory.epi_iff_surjective, apply (forget CompHaus).epi_of_epi_map } end lemma mono_iff_injective {X Y : CompHaus.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { introsI hf x₁ x₂ h, let g₁ : of punit ⟶ X := ⟨λ _, x₁, continuous_of_discrete_topology⟩, let g₂ : of punit ⟶ X := ⟨λ _, x₂, continuous_of_discrete_topology⟩, have : g₁ ≫ f = g₂ ≫ f, by { ext, exact h }, rw cancel_mono at this, apply_fun (λ e, e punit.star) at this, exact this }, { rw ← category_theory.mono_iff_injective, apply (forget CompHaus).mono_of_mono_map } end end CompHaus
2031a795eb47b8955e8733e90d36f790e6353dbc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/hom/group.lean
6495831cbf058cc4d3e9e39bd17b9fb746a22fd8
[ "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
53,850
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.ne_zero import algebra.group.basic import algebra.group_with_zero.defs import data.fun_like.basic /-! # Monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. This file also defines the lesser-used (and notation-less) homomorphism types which are used as building blocks for other homomorphisms: * `zero_hom` * `one_hom` * `add_hom` * `mul_hom` * `monoid_with_zero_hom` ## Notations * `→+`: Bundled `add_monoid` homs. Also use for `add_group` homs. * `→*`: Bundled `monoid` homs. Also use for `group` homs. * `→*₀`: Bundled `monoid_with_zero` homs. Also use for `group_with_zero` homs. * `→ₙ*`: Bundled `semigroup` homs. ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {α β M N P : Type*} -- monoids variables {G : Type*} {H : Type*} -- groups variables {F : Type*} -- homs -- for easy multiple inheritance set_option old_structure_cmd true section zero /-- `zero_hom M N` is the type of functions `M → N` that preserve zero. When possible, instead of parametrizing results over `(f : zero_hom M N)`, you should parametrize over `(F : Type*) [zero_hom_class F M N] (f : F)`. When you extend this structure, make sure to also extend `zero_hom_class`. -/ structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) /-- `zero_hom_class F M N` states that `F` is a type of zero-preserving homomorphisms. You should extend this typeclass when you extend `zero_hom`. -/ class zero_hom_class (F : Type*) (M N : out_param $ Type*) [has_zero M] [has_zero N] extends fun_like F M (λ _, N) := (map_zero : ∀ (f : F), f 0 = 0) -- Instances and lemmas are defined below through `@[to_additive]`. end zero namespace ne_zero lemma of_map {R M} [has_zero R] [has_zero M] [zero_hom_class F R M] (f : F) {r : R} [ne_zero (f r)] : ne_zero r := ⟨λ h, ne (f r) $ by convert zero_hom_class.map_zero f⟩ lemma of_injective {R M} [has_zero R] {r : R} [ne_zero r] [has_zero M] [zero_hom_class F R M] {f : F} (hf : function.injective f) : ne_zero (f r) := ⟨by { rw ← zero_hom_class.map_zero f, exact hf.ne (ne r) }⟩ end ne_zero section add /-- `add_hom M N` is the type of functions `M → N` that preserve addition. When possible, instead of parametrizing results over `(f : add_hom M N)`, you should parametrize over `(F : Type*) [add_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `add_hom_class`. -/ structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] := (to_fun : M → N) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) /-- `add_hom_class F M N` states that `F` is a type of addition-preserving homomorphisms. You should declare an instance of this typeclass when you extend `add_hom`. -/ class add_hom_class (F : Type*) (M N : out_param $ Type*) [has_add M] [has_add N] extends fun_like F M (λ _, N) := (map_add : ∀ (f : F) (x y : M), f (x + y) = f x + f y) -- Instances and lemmas are defined below through `@[to_additive]`. end add section add_zero /-- `M →+ N` is the type of functions `M → N` that preserve the `add_zero_class` structure. `add_monoid_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →+ N)`, you should parametrize over `(F : Type*) [add_monoid_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `add_monoid_hom_class`. -/ @[ancestor zero_hom add_hom] structure add_monoid_hom (M : Type*) (N : Type*) [add_zero_class M] [add_zero_class N] extends zero_hom M N, add_hom M N attribute [nolint doc_blame] add_monoid_hom.to_add_hom attribute [nolint doc_blame] add_monoid_hom.to_zero_hom infixr ` →+ `:25 := add_monoid_hom /-- `add_monoid_hom_class F M N` states that `F` is a type of `add_zero_class`-preserving homomorphisms. You should also extend this typeclass when you extend `add_monoid_hom`. -/ @[ancestor add_hom_class zero_hom_class] class add_monoid_hom_class (F : Type*) (M N : out_param $ Type*) [add_zero_class M] [add_zero_class N] extends add_hom_class F M N, zero_hom_class F M N -- Instances and lemmas are defined below through `@[to_additive]`. end add_zero section one variables [has_one M] [has_one N] /-- `one_hom M N` is the type of functions `M → N` that preserve one. When possible, instead of parametrizing results over `(f : one_hom M N)`, you should parametrize over `(F : Type*) [one_hom_class F M N] (f : F)`. When you extend this structure, make sure to also extend `one_hom_class`. -/ @[to_additive] structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) /-- `one_hom_class F M N` states that `F` is a type of one-preserving homomorphisms. You should extend this typeclass when you extend `one_hom`. -/ @[to_additive] class one_hom_class (F : Type*) (M N : out_param $ Type*) [has_one M] [has_one N] extends fun_like F M (λ _, N) := (map_one : ∀ (f : F), f 1 = 1) @[to_additive] instance one_hom.one_hom_class : one_hom_class (one_hom M N) M N := { coe := one_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_one := one_hom.map_one' } @[simp, to_additive] lemma map_one [one_hom_class F M N] (f : F) : f 1 = 1 := one_hom_class.map_one f @[to_additive] lemma map_eq_one_iff [one_hom_class F M N] (f : F) (hf : function.injective f) {x : M} : f x = 1 ↔ x = 1 := hf.eq_iff' (map_one f) @[to_additive] lemma map_ne_one_iff {R S F : Type*} [has_one R] [has_one S] [one_hom_class F R S] (f : F) (hf : function.injective f) {x : R} : f x ≠ 1 ↔ x ≠ 1 := (map_eq_one_iff f hf).not @[to_additive] lemma ne_one_of_map {R S F : Type*} [has_one R] [has_one S] [one_hom_class F R S] {f : F} {x : R} (hx : f x ≠ 1) : x ≠ 1 := ne_of_apply_ne f $ ne_of_ne_of_eq hx (map_one f).symm @[to_additive] instance [one_hom_class F M N] : has_coe_t F (one_hom M N) := ⟨λ f, { to_fun := f, map_one' := map_one f }⟩ @[simp, to_additive] lemma one_hom.coe_coe [one_hom_class F M N] (f : F) : ((f : one_hom M N) : M → N) = f := rfl end one section mul variables [has_mul M] [has_mul N] /-- `M →ₙ* N` is the type of functions `M → N` that preserve multiplication. The `ₙ` in the notation stands for "non-unital" because it is intended to match the notation for `non_unital_alg_hom` and `non_unital_ring_hom`, so a `mul_hom` is a non-unital monoid hom. When possible, instead of parametrizing results over `(f : M →ₙ* N)`, you should parametrize over `(F : Type*) [mul_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `mul_hom_class`. -/ @[to_additive] structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] := (to_fun : M → N) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →ₙ* `:25 := mul_hom /-- `mul_hom_class F M N` states that `F` is a type of multiplication-preserving homomorphisms. You should declare an instance of this typeclass when you extend `mul_hom`. -/ @[to_additive] class mul_hom_class (F : Type*) (M N : out_param $ Type*) [has_mul M] [has_mul N] extends fun_like F M (λ _, N) := (map_mul : ∀ (f : F) (x y : M), f (x * y) = f x * f y) @[to_additive] instance mul_hom.mul_hom_class : mul_hom_class (M →ₙ* N) M N := { coe := mul_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := mul_hom.map_mul' } @[simp, to_additive] lemma map_mul [mul_hom_class F M N] (f : F) (x y : M) : f (x * y) = f x * f y := mul_hom_class.map_mul f x y @[to_additive] instance [mul_hom_class F M N] : has_coe_t F (M →ₙ* N) := ⟨λ f, { to_fun := f, map_mul' := map_mul f }⟩ @[simp, to_additive] lemma mul_hom.coe_coe [mul_hom_class F M N] (f : F) : ((f : mul_hom M N) : M → N) = f := rfl end mul section mul_one variables [mul_one_class M] [mul_one_class N] /-- `M →* N` is the type of functions `M → N` that preserve the `monoid` structure. `monoid_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →+ N)`, you should parametrize over `(F : Type*) [monoid_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `monoid_hom_class`. -/ @[ancestor one_hom mul_hom, to_additive] structure monoid_hom (M : Type*) (N : Type*) [mul_one_class M] [mul_one_class N] extends one_hom M N, M →ₙ* N attribute [nolint doc_blame] monoid_hom.to_mul_hom attribute [nolint doc_blame] monoid_hom.to_one_hom infixr ` →* `:25 := monoid_hom /-- `monoid_hom_class F M N` states that `F` is a type of `monoid`-preserving homomorphisms. You should also extend this typeclass when you extend `monoid_hom`. -/ @[ancestor mul_hom_class one_hom_class, to_additive "`add_monoid_hom_class F M N` states that `F` is a type of `add_monoid`-preserving homomorphisms. You should also extend this typeclass when you extend `add_monoid_hom`."] class monoid_hom_class (F : Type*) (M N : out_param $ Type*) [mul_one_class M] [mul_one_class N] extends mul_hom_class F M N, one_hom_class F M N @[to_additive] instance monoid_hom.monoid_hom_class : monoid_hom_class (M →* N) M N := { coe := monoid_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := monoid_hom.map_mul', map_one := monoid_hom.map_one' } @[to_additive] instance [monoid_hom_class F M N] : has_coe_t F (M →* N) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_mul' := map_mul f }⟩ @[simp, to_additive] lemma monoid_hom.coe_coe [monoid_hom_class F M N] (f : F) : ((f : M →* N) : M → N) = f := rfl @[to_additive] lemma map_mul_eq_one [monoid_hom_class F M N] (f : F) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← map_mul, h, map_one] @[to_additive] lemma map_div' [div_inv_monoid G] [div_inv_monoid H] [monoid_hom_class F G H] (f : F) (hf : ∀ a, f a⁻¹ = (f a)⁻¹) (a b : G) : f (a / b) = f a / f b := by rw [div_eq_mul_inv, div_eq_mul_inv, map_mul, hf] /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive "Additive group homomorphisms preserve negation."] lemma map_inv [group G] [division_monoid H] [monoid_hom_class F G H] (f : F) (a : G) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one_left $ map_mul_eq_one f $ inv_mul_self _ /-- Group homomorphisms preserve division. -/ @[simp, to_additive "Additive group homomorphisms preserve subtraction."] lemma map_mul_inv [group G] [division_monoid H] [monoid_hom_class F G H] (f : F) (a b : G) : f (a * b⁻¹) = f a * (f b)⁻¹ := by rw [map_mul, map_inv] /-- Group homomorphisms preserve division. -/ @[simp, to_additive "Additive group homomorphisms preserve subtraction."] lemma map_div [group G] [division_monoid H] [monoid_hom_class F G H] (f : F) : ∀ a b, f (a / b) = f a / f b := map_div' _ $ map_inv f -- to_additive puts the arguments in the wrong order, so generate an auxiliary lemma, then -- swap its arguments. @[to_additive map_nsmul.aux, simp] theorem map_pow [monoid G] [monoid H] [monoid_hom_class F G H] (f : F) (a : G) : ∀ (n : ℕ), f (a ^ n) = (f a) ^ n | 0 := by rw [pow_zero, pow_zero, map_one] | (n+1) := by rw [pow_succ, pow_succ, map_mul, map_pow] @[simp] theorem map_nsmul [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) (n : ℕ) (a : G) : f (n • a) = n • (f a) := map_nsmul.aux f a n attribute [to_additive_reorder 8, to_additive] map_pow @[to_additive] theorem map_zpow' [div_inv_monoid G] [div_inv_monoid H] [monoid_hom_class F G H] (f : F) (hf : ∀ (x : G), f (x⁻¹) = (f x)⁻¹) (a : G) : ∀ n : ℤ, f (a ^ n) = (f a) ^ n | (n : ℕ) := by rw [zpow_coe_nat, map_pow, zpow_coe_nat] | -[1+n] := by rw [zpow_neg_succ_of_nat, hf, map_pow, ← zpow_neg_succ_of_nat] -- to_additive puts the arguments in the wrong order, so generate an auxiliary lemma, then -- swap its arguments. /-- Group homomorphisms preserve integer power. -/ @[to_additive map_zsmul.aux, simp] theorem map_zpow [group G] [division_monoid H] [monoid_hom_class F G H] (f : F) (g : G) (n : ℤ) : f (g ^ n) = (f g) ^ n := map_zpow' f (map_inv f) g n /-- Additive group homomorphisms preserve integer scaling. -/ theorem map_zsmul [add_group G] [subtraction_monoid H] [add_monoid_hom_class F G H] (f : F) (n : ℤ) (g : G) : f (n • g) = n • f g := map_zsmul.aux f g n attribute [to_additive_reorder 8, to_additive] map_zpow end mul_one section mul_zero_one variables [mul_zero_one_class M] [mul_zero_one_class N] /-- `M →*₀ N` is the type of functions `M → N` that preserve the `monoid_with_zero` structure. `monoid_with_zero_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : M →*₀ N)`, you should parametrize over `(F : Type*) [monoid_with_zero_hom_class F M N] (f : F)`. When you extend this structure, make sure to extend `monoid_with_zero_hom_class`. -/ @[ancestor zero_hom monoid_hom] structure monoid_with_zero_hom (M : Type*) (N : Type*) [mul_zero_one_class M] [mul_zero_one_class N] extends zero_hom M N, monoid_hom M N attribute [nolint doc_blame] monoid_with_zero_hom.to_monoid_hom attribute [nolint doc_blame] monoid_with_zero_hom.to_zero_hom infixr ` →*₀ `:25 := monoid_with_zero_hom /-- `monoid_with_zero_hom_class F M N` states that `F` is a type of `monoid_with_zero`-preserving homomorphisms. You should also extend this typeclass when you extend `monoid_with_zero_hom`. -/ class monoid_with_zero_hom_class (F : Type*) (M N : out_param $ Type*) [mul_zero_one_class M] [mul_zero_one_class N] extends monoid_hom_class F M N, zero_hom_class F M N instance monoid_with_zero_hom.monoid_with_zero_hom_class : monoid_with_zero_hom_class (M →*₀ N) M N := { coe := monoid_with_zero_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_mul := monoid_with_zero_hom.map_mul', map_one := monoid_with_zero_hom.map_one', map_zero := monoid_with_zero_hom.map_zero' } instance [monoid_with_zero_hom_class F M N] : has_coe_t F (M →*₀ N) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_zero' := map_zero f, map_mul' := map_mul f }⟩ @[simp] lemma monoid_with_zero_hom.coe_coe [monoid_with_zero_hom_class F M N] (f : F) : ((f : M →*₀ N) : M → N) = f := rfl end mul_zero_one -- completely uninteresting lemmas about coercion to function, that all homs need section coes /-! Bundled morphisms can be down-cast to weaker bundlings -/ @[to_additive] instance monoid_hom.has_coe_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} : has_coe (M →* N) (one_hom M N) := ⟨monoid_hom.to_one_hom⟩ @[to_additive] instance monoid_hom.has_coe_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} : has_coe (M →* N) (M →ₙ* N) := ⟨monoid_hom.to_mul_hom⟩ instance monoid_with_zero_hom.has_coe_to_monoid_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe (M →*₀ N) (M →* N) := ⟨monoid_with_zero_hom.to_monoid_hom⟩ instance monoid_with_zero_hom.has_coe_to_zero_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe (M →*₀ N) (zero_hom M N) := ⟨monoid_with_zero_hom.to_zero_hom⟩ /-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because this is the way things were before the above coercions were introduced. Bundled morphisms defined elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/ @[simp, to_additive] lemma monoid_hom.coe_eq_to_one_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) : (f : one_hom M N) = f.to_one_hom := rfl @[simp, to_additive] lemma monoid_hom.coe_eq_to_mul_hom {mM : mul_one_class M} {mN : mul_one_class N} (f : M →* N) : (f : M →ₙ* N) = f.to_mul_hom := rfl @[simp] lemma monoid_with_zero_hom.coe_eq_to_monoid_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : M →*₀ N) : (f : M →* N) = f.to_monoid_hom := rfl @[simp] lemma monoid_with_zero_hom.coe_eq_to_zero_hom {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} (f : M →*₀ N) : (f : zero_hom M N) = f.to_zero_hom := rfl -- Fallback `has_coe_to_fun` instances to help the elaborator @[to_additive] instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) (λ _, M → N) := ⟨one_hom.to_fun⟩ @[to_additive] instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (M →ₙ* N) (λ _, M → N) := ⟨mul_hom.to_fun⟩ @[to_additive] instance {mM : mul_one_class M} {mN : mul_one_class N} : has_coe_to_fun (M →* N) (λ _, M → N) := ⟨monoid_hom.to_fun⟩ instance {mM : mul_zero_one_class M} {mN : mul_zero_one_class N} : has_coe_to_fun (M →*₀ N) (λ _, M → N) := ⟨monoid_with_zero_hom.to_fun⟩ -- these must come after the coe_to_fun definitions initialize_simps_projections zero_hom (to_fun → apply) initialize_simps_projections add_hom (to_fun → apply) initialize_simps_projections add_monoid_hom (to_fun → apply) initialize_simps_projections one_hom (to_fun → apply) initialize_simps_projections mul_hom (to_fun → apply) initialize_simps_projections monoid_hom (to_fun → apply) initialize_simps_projections monoid_with_zero_hom (to_fun → apply) @[simp, to_additive] lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl @[simp, to_additive] lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : M →ₙ* N) : f.to_fun = f := rfl @[simp, to_additive] lemma monoid_hom.to_fun_eq_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : f.to_fun = f := rfl @[simp] lemma monoid_with_zero_hom.to_fun_eq_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f.to_fun = f := rfl @[simp, to_additive] lemma one_hom.coe_mk [has_one M] [has_one N] (f : M → N) (h1) : (one_hom.mk f h1 : M → N) = f := rfl @[simp, to_additive] lemma mul_hom.coe_mk [has_mul M] [has_mul N] (f : M → N) (hmul) : (mul_hom.mk f hmul : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.coe_mk [mul_one_class M] [mul_one_class N] (f : M → N) (h1 hmul) : (monoid_hom.mk f h1 hmul : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.coe_mk [mul_zero_one_class M] [mul_zero_one_class N] (f : M → N) (h0 h1 hmul) : (monoid_with_zero_hom.mk f h0 h1 hmul : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.to_one_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : (f.to_one_hom : M → N) = f := rfl @[simp, to_additive] lemma monoid_hom.to_mul_hom_coe [mul_one_class M] [mul_one_class N] (f : M →* N) : (f.to_mul_hom : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.to_zero_hom_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (f.to_zero_hom : M → N) = f := rfl @[simp] lemma monoid_with_zero_hom.to_monoid_hom_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (f.to_monoid_hom : M → N) = f := rfl @[ext, to_additive] lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext, to_additive] lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : M →ₙ* N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext, to_additive] lemma monoid_hom.ext [mul_one_class M] [mul_one_class N] ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h @[ext] lemma monoid_with_zero_hom.ext [mul_zero_one_class M] [mul_zero_one_class N] ⦃f g : M →*₀ N⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h section deprecated /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem one_hom.congr_fun [has_one M] [has_one N] {f g : one_hom M N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem mul_hom.congr_fun [has_mul M] [has_mul N] {f g : M →ₙ* N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_fun` instead."] theorem monoid_hom.congr_fun [mul_one_class M] [mul_one_class N] {f g : M →* N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_fun` instead. -/ theorem monoid_with_zero_hom.congr_fun [mul_zero_one_class M] [mul_zero_one_class N] {f g : M →*₀ N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem one_hom.congr_arg [has_one M] [has_one N] (f : one_hom M N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem mul_hom.congr_arg [has_mul M] [has_mul N] (f : M →ₙ* N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ @[to_additive "Deprecated: use `fun_like.congr_arg` instead."] theorem monoid_hom.congr_arg [mul_one_class M] [mul_one_class N] (f : M →* N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.congr_arg` instead. -/ theorem monoid_with_zero_hom.congr_arg [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) {x y : M} (h : x = y) : f x = f y := fun_like.congr_arg f h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : M →ₙ* N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ @[to_additive "Deprecated: use `fun_like.coe_injective` instead."] lemma monoid_hom.coe_inj [mul_one_class M] [mul_one_class N] ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.coe_injective` instead. -/ lemma monoid_with_zero_hom.coe_inj [mul_zero_one_class M] [mul_zero_one_class N] ⦃f g : M →*₀ N⦄ (h : (f : M → N) = g) : f = g := fun_like.coe_injective h /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive "Deprecated: use `fun_like.ext_iff` instead."] lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive "Deprecated: use `fun_like.ext_iff` instead."] lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : M →ₙ* N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ @[to_additive "Deprecated: use `fun_like.ext_iff` instead."] lemma monoid_hom.ext_iff [mul_one_class M] [mul_one_class N] {f g : M →* N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff /-- Deprecated: use `fun_like.ext_iff` instead. -/ lemma monoid_with_zero_hom.ext_iff [mul_zero_one_class M] [mul_zero_one_class N] {f g : M →*₀ N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff end deprecated @[simp, to_additive] lemma one_hom.mk_coe [has_one M] [has_one N] (f : one_hom M N) (h1) : one_hom.mk f h1 = f := one_hom.ext $ λ _, rfl @[simp, to_additive] lemma mul_hom.mk_coe [has_mul M] [has_mul N] (f : M →ₙ* N) (hmul) : mul_hom.mk f hmul = f := mul_hom.ext $ λ _, rfl @[simp, to_additive] lemma monoid_hom.mk_coe [mul_one_class M] [mul_one_class N] (f : M →* N) (h1 hmul) : monoid_hom.mk f h1 hmul = f := monoid_hom.ext $ λ _, rfl @[simp] lemma monoid_with_zero_hom.mk_coe [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) (h0 h1 hmul) : monoid_with_zero_hom.mk f h0 h1 hmul = f := monoid_with_zero_hom.ext $ λ _, rfl end coes /-- Copy of a `one_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of a `zero_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def one_hom.copy {hM : has_one M} {hN : has_one N} (f : one_hom M N) (f' : M → N) (h : f' = f) : one_hom M N := { to_fun := f', map_one' := h.symm ▸ f.map_one' } @[simp, to_additive] lemma one_hom.coe_copy {hM : has_one M} {hN : has_one N} (f : one_hom M N) (f' : M → N) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl @[to_additive] lemma one_hom.coe_copy_eq {hM : has_one M} {hN : has_one N} (f : one_hom M N) (f' : M → N) (h : f' = f) : f.copy f' h = f := fun_like.ext' h /-- Copy of a `mul_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `add_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def mul_hom.copy {hM : has_mul M} {hN : has_mul N} (f : M →ₙ* N) (f' : M → N) (h : f' = f) : M →ₙ* N := { to_fun := f', map_mul' := h.symm ▸ f.map_mul' } @[simp, to_additive] lemma mul_hom.coe_copy {hM : has_mul M} {hN : has_mul N} (f : M →ₙ* N) (f' : M → N) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl @[to_additive] lemma mul_hom.coe_copy_eq {hM : has_mul M} {hN : has_mul N} (f : M →ₙ* N) (f' : M → N) (h : f' = f) : f.copy f' h = f := fun_like.ext' h /-- Copy of a `monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `add_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def monoid_hom.copy {hM : mul_one_class M} {hN : mul_one_class N} (f : M →* N) (f' : M → N) (h : f' = f) : M →* N := { ..f.to_one_hom.copy f' h, ..f.to_mul_hom.copy f' h } @[simp, to_additive] lemma monoid_hom.coe_copy {hM : mul_one_class M} {hN : mul_one_class N} (f : M →* N) (f' : M → N) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl @[to_additive] lemma monoid_hom.copy_eq {hM : mul_one_class M} {hN : mul_one_class N} (f : M →* N) (f' : M → N) (h : f' = f) : f.copy f' h = f := fun_like.ext' h /-- Copy of a `monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def monoid_with_zero_hom.copy {hM : mul_zero_one_class M} {hN : mul_zero_one_class N} (f : M →*₀ N) (f' : M → N) (h : f' = f) : M →* N := { ..f.to_zero_hom.copy f' h, ..f.to_monoid_hom.copy f' h } @[simp] lemma monoid_with_zero_hom.coe_copy {hM : mul_zero_one_class M} {hN : mul_zero_one_class N} (f : M →*₀ N) (f' : M → N) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma monoid_with_zero_hom.copy_eq {hM : mul_zero_one_class M} {hN : mul_zero_one_class N} (f : M →*₀ N) (f' : M → N) (h : f' = f) : f.copy f' h = f := fun_like.ext' h @[to_additive] protected lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one' /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[to_additive] protected lemma monoid_hom.map_one [mul_one_class M] [mul_one_class N] (f : M →* N) : f 1 = 1 := f.map_one' protected lemma monoid_with_zero_hom.map_one [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f 1 = 1 := f.map_one' /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ add_decl_doc add_monoid_hom.map_zero protected lemma monoid_with_zero_hom.map_zero [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f 0 = 0 := f.map_zero' @[to_additive] protected lemma mul_hom.map_mul [has_mul M] [has_mul N] (f : M →ₙ* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[to_additive] protected lemma monoid_hom.map_mul [mul_one_class M] [mul_one_class N] (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b protected lemma monoid_with_zero_hom.map_mul [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ add_decl_doc add_monoid_hom.map_add namespace monoid_hom variables {mM : mul_one_class M} {mN : mul_one_class N} [monoid_hom_class F M N] include mM mN /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : F) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, map_mul_eq_one f hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : F) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, map_mul_eq_one f hy⟩ end monoid_hom section division_comm_monoid variables [division_comm_monoid α] /-- Inversion on a commutative group, considered as a monoid homomorphism. -/ @[to_additive "Negation on a commutative additive group, considered as an additive monoid homomorphism."] def inv_monoid_hom : α →* α := { to_fun := has_inv.inv, map_one' := inv_one, map_mul' := mul_inv } @[simp] lemma coe_inv_monoid_hom : (inv_monoid_hom : α → α) = has_inv.inv := rfl @[simp] lemma inv_monoid_hom_apply (a : α) : inv_monoid_hom a = a⁻¹ := rfl end division_comm_monoid /-- The identity map from a type with 1 to itself. -/ @[to_additive, simps] def one_hom.id (M : Type*) [has_one M] : one_hom M M := { to_fun := λ x, x, map_one' := rfl, } /-- The identity map from a type with multiplication to itself. -/ @[to_additive, simps] def mul_hom.id (M : Type*) [has_mul M] : M →ₙ* M := { to_fun := λ x, x, map_mul' := λ _ _, rfl, } /-- The identity map from a monoid to itself. -/ @[to_additive, simps] def monoid_hom.id (M : Type*) [mul_one_class M] : M →* M := { to_fun := λ x, x, map_one' := rfl, map_mul' := λ _ _, rfl, } /-- The identity map from a monoid_with_zero to itself. -/ @[simps] def monoid_with_zero_hom.id (M : Type*) [mul_zero_one_class M] : M →*₀ M := { to_fun := λ x, x, map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, } /-- The identity map from an type with zero to itself. -/ add_decl_doc zero_hom.id /-- The identity map from an type with addition to itself. -/ add_decl_doc add_hom.id /-- The identity map from an additive monoid to itself. -/ add_decl_doc add_monoid_hom.id /-- Composition of `one_hom`s as a `one_hom`. -/ @[to_additive] def one_hom.comp [has_one M] [has_one N] [has_one P] (hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P := { to_fun := hnp ∘ hmn, map_one' := by simp, } /-- Composition of `mul_hom`s as a `mul_hom`. -/ @[to_additive] def mul_hom.comp [has_mul M] [has_mul N] [has_mul P] (hnp : N →ₙ* P) (hmn : M →ₙ* N) : M →ₙ* P := { to_fun := hnp ∘ hmn, map_mul' := by simp, } /-- Composition of monoid morphisms as a monoid morphism. -/ @[to_additive] def monoid_hom.comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, } /-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/ def monoid_with_zero_hom.comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (hnp : N →*₀ P) (hmn : M →*₀ N) : M →*₀ P := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_mul' := by simp, } /-- Composition of `zero_hom`s as a `zero_hom`. -/ add_decl_doc zero_hom.comp /-- Composition of `add_hom`s as a `add_hom`. -/ add_decl_doc add_hom.comp /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ add_decl_doc add_monoid_hom.comp @[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P] (g : N →ₙ* P) (f : M →ₙ* N) : ⇑(g.comp f) = g ∘ f := rfl @[simp, to_additive] lemma monoid_hom.coe_comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (g : N →* P) (f : M →* N) : ⇑(g.comp f) = g ∘ f := rfl @[simp] lemma monoid_with_zero_hom.coe_comp [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (g : N →*₀ P) (f : M →*₀ N) : ⇑(g.comp f) = g ∘ f := rfl @[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P] (g : one_hom N P) (f : one_hom M N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P] (g : N →ₙ* P) (f : M →ₙ* N) (x : M) : g.comp f x = g (f x) := rfl @[to_additive] lemma monoid_hom.comp_apply [mul_one_class M] [mul_one_class N] [mul_one_class P] (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl lemma monoid_with_zero_hom.comp_apply [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] (g : N →*₀ P) (f : M →*₀ N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive "Composition of additive monoid homomorphisms is associative."] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q] (f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q] (f : M →ₙ* N) (g : N →ₙ* P) (h : P →ₙ* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma monoid_hom.comp_assoc {Q : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] [mul_one_class Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl lemma monoid_with_zero_hom.comp_assoc {Q : Type*} [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] [mul_zero_one_class Q] (f : M →*₀ N) (g : N →*₀ P) (h : P →*₀ Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P] {g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, one_hom.ext $ hf.forall.2 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P] {g₁ g₂ : N →ₙ* P} {f : M →ₙ* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, mul_hom.ext $ hf.forall.2 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_right [mul_one_class M] [mul_one_class N] [mul_one_class P] {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ hf.forall.2 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ lemma monoid_with_zero_hom.cancel_right [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] {g₁ g₂ : N →*₀ P} {f : M →*₀ N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_with_zero_hom.ext $ hf.forall.2 (monoid_with_zero_hom.ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P] {g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma mul_hom.cancel_left [has_mul M] [has_mul N] [has_mul P] {g : N →ₙ* P} {f₁ f₂ : M →ₙ* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, mul_hom.ext $ λ x, hg $ by rw [← mul_hom.comp_apply, h, mul_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.cancel_left [mul_one_class M] [mul_one_class N] [mul_one_class P] {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply], λ h, h ▸ rfl⟩ lemma monoid_with_zero_hom.cancel_left [mul_zero_one_class M] [mul_zero_one_class N] [mul_zero_one_class P] {g : N →*₀ P} {f₁ f₂ : M →*₀ N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_with_zero_hom.ext $ λ x, hg $ by rw [ ← monoid_with_zero_hom.comp_apply, h, monoid_with_zero_hom.comp_apply], λ h, h ▸ rfl⟩ @[to_additive] lemma monoid_hom.to_one_hom_injective [mul_one_class M] [mul_one_class N] : function.injective (monoid_hom.to_one_hom : (M →* N) → one_hom M N) := λ f g h, monoid_hom.ext $ one_hom.ext_iff.mp h @[to_additive] lemma monoid_hom.to_mul_hom_injective [mul_one_class M] [mul_one_class N] : function.injective (monoid_hom.to_mul_hom : (M →* N) → M →ₙ* N) := λ f g h, monoid_hom.ext $ mul_hom.ext_iff.mp h lemma monoid_with_zero_hom.to_monoid_hom_injective [mul_zero_one_class M] [mul_zero_one_class N] : function.injective (monoid_with_zero_hom.to_monoid_hom : (M →*₀ N) → M →* N) := λ f g h, monoid_with_zero_hom.ext $ monoid_hom.ext_iff.mp h lemma monoid_with_zero_hom.to_zero_hom_injective [mul_zero_one_class M] [mul_zero_one_class N] : function.injective (monoid_with_zero_hom.to_zero_hom : (M →*₀ N) → zero_hom M N) := λ f g h, monoid_with_zero_hom.ext $ zero_hom.ext_iff.mp h @[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N] (f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N] (f : M →ₙ* N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.comp_id [mul_one_class M] [mul_one_class N] (f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl @[simp] lemma monoid_with_zero_hom.comp_id [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : f.comp (monoid_with_zero_hom.id M) = f := monoid_with_zero_hom.ext $ λ x, rfl @[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N] (f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl @[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N] (f : M →ₙ* N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl @[simp, to_additive] lemma monoid_hom.id_comp [mul_one_class M] [mul_one_class N] (f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl @[simp] lemma monoid_with_zero_hom.id_comp [mul_zero_one_class M] [mul_zero_one_class N] (f : M →*₀ N) : (monoid_with_zero_hom.id N).comp f = f := monoid_with_zero_hom.ext $ λ x, rfl @[to_additive add_monoid_hom.map_nsmul] protected theorem monoid_hom.map_pow [monoid M] [monoid N] (f : M →* N) (a : M) (n : ℕ) : f (a ^ n) = (f a) ^ n := map_pow f a n @[to_additive] protected theorem monoid_hom.map_zpow' [div_inv_monoid M] [div_inv_monoid N] (f : M →* N) (hf : ∀ x, f (x⁻¹) = (f x)⁻¹) (a : M) (n : ℤ) : f (a ^ n) = (f a) ^ n := map_zpow' f hf a n section End namespace monoid variables (M) [mul_one_class M] /-- The monoid of endomorphisms. -/ protected def End := M →* M namespace End instance : monoid (monoid.End M) := { mul := monoid_hom.comp, one := monoid_hom.id M, mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _, mul_one := monoid_hom.comp_id, one_mul := monoid_hom.id_comp } instance : inhabited (monoid.End M) := ⟨1⟩ instance : monoid_hom_class (monoid.End M) M M := monoid_hom.monoid_hom_class end End @[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl end monoid namespace add_monoid variables (A : Type*) [add_zero_class A] /-- The monoid of endomorphisms. -/ protected def End := A →+ A namespace End instance : monoid (add_monoid.End A) := { mul := add_monoid_hom.comp, one := add_monoid_hom.id A, mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _, mul_one := add_monoid_hom.comp_id, one_mul := add_monoid_hom.id_comp } instance : inhabited (add_monoid.End A) := ⟨1⟩ instance : add_monoid_hom_class (add_monoid.End A) A A := add_monoid_hom.add_monoid_hom_class end End @[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl end add_monoid end End /-- `1` is the homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩ /-- `1` is the multiplicative homomorphism sending all elements to `1`. -/ @[to_additive] instance [has_mul M] [mul_one_class N] : has_one (M →ₙ* N) := ⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩ /-- `1` is the monoid homomorphism sending all elements to `1`. -/ @[to_additive] instance [mul_one_class M] [mul_one_class N] : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩ /-- `0` is the homomorphism sending all elements to `0`. -/ add_decl_doc zero_hom.has_zero /-- `0` is the additive homomorphism sending all elements to `0`. -/ add_decl_doc add_hom.has_zero /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ add_decl_doc add_monoid_hom.has_zero @[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N] (x : M) : (1 : one_hom M N) x = 1 := rfl @[simp, to_additive] lemma monoid_hom.one_apply [mul_one_class M] [mul_one_class N] (x : M) : (1 : M →* N) x = 1 := rfl @[simp, to_additive] lemma one_hom.one_comp [has_one M] [has_one N] [has_one P] (f : one_hom M N) : (1 : one_hom N P).comp f = 1 := rfl @[simp, to_additive] lemma one_hom.comp_one [has_one M] [has_one N] [has_one P] (f : one_hom N P) : f.comp (1 : one_hom M N) = 1 := by { ext, simp only [one_hom.map_one, one_hom.coe_comp, function.comp_app, one_hom.one_apply] } @[to_additive] instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩ @[to_additive] instance [has_mul M] [mul_one_class N] : inhabited (M →ₙ* N) := ⟨1⟩ @[to_additive] instance [mul_one_class M] [mul_one_class N] : inhabited (M →* N) := ⟨1⟩ -- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0` instance [mul_zero_one_class M] : inhabited (M →*₀ M) := ⟨monoid_with_zero_hom.id M⟩ namespace mul_hom /-- Given two mul morphisms `f`, `g` to a commutative semigroup, `f * g` is the mul morphism sending `x` to `f x * g x`. -/ @[to_additive] instance [has_mul M] [comm_semigroup N] : has_mul (M →ₙ* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive morphisms `f`, `g` to an additive commutative semigroup, `f + g` is the additive morphism sending `x` to `f x + g x`. -/ add_decl_doc add_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : has_mul M} {mN : comm_semigroup N} (f g : M →ₙ* N) (x : M) : (f * g) x = f x * g x := rfl @[to_additive] lemma mul_comp [has_mul M] [has_mul N] [comm_semigroup P] (g₁ g₂ : N →ₙ* P) (f : M →ₙ* N) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul [has_mul M] [comm_semigroup N] [comm_semigroup P] (g : N →ₙ* P) (f₁ f₂ : M →ₙ* N) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] } end mul_hom namespace monoid_hom variables [mM : mul_one_class M] [mN : mul_one_class N] [mP : mul_one_class P] variables [group G] [comm_group H] /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ @[to_additive] instance {M N} {mM : mul_one_class M} [comm_monoid N] : has_mul (M →* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ add_decl_doc add_monoid_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : mul_one_class M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl @[simp, to_additive] lemma one_comp [mul_one_class M] [mul_one_class N] [mul_one_class P] (f : M →* N) : (1 : N →* P).comp f = 1 := rfl @[simp, to_additive] lemma comp_one [mul_one_class M] [mul_one_class N] [mul_one_class P] (f : N →* P) : f.comp (1 : M →* N) = 1 := by { ext, simp only [map_one, coe_comp, function.comp_app, one_apply] } @[to_additive] lemma mul_comp [mul_one_class M] [mul_one_class N] [comm_monoid P] (g₁ g₂ : N →* P) (f : M →* N) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul [mul_one_class M] [comm_monoid N] [comm_monoid P] (g : N →* P) (f₁ f₂ : M →* N) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] } /-- Group homomorphisms preserve inverse. -/ @[to_additive "Additive group homomorphisms preserve negation."] protected lemma map_inv [group α] [division_monoid β] (f : α →* β) (a : α) : f a⁻¹ = (f a)⁻¹ := map_inv f _ /-- Group homomorphisms preserve integer power. -/ @[to_additive "Additive group homomorphisms preserve integer scaling."] protected theorem map_zpow [group α] [division_monoid β] (f : α →* β) (g : α) (n : ℤ) : f (g ^ n) = (f g) ^ n := map_zpow f g n /-- Group homomorphisms preserve division. -/ @[to_additive "Additive group homomorphisms preserve subtraction."] protected theorem map_div [group α] [division_monoid β] (f : α →* β) (g h : α) : f (g / h) = f g / f h := map_div f g h /-- Group homomorphisms preserve division. -/ @[to_additive "Additive group homomorphisms preserve subtraction."] protected theorem map_mul_inv [group α] [division_monoid β] (f : α →* β) (g h : α) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := map_mul_inv f g h /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. For the iff statement on the triviality of the kernel, see `injective_iff_map_eq_one'`. -/ @[to_additive "A homomorphism from an additive group to an additive monoid is injective iff its kernel is trivial. For the iff statement on the triviality of the kernel, see `injective_iff_map_eq_zero'`."] lemma _root_.injective_iff_map_eq_one {G H} [group G] [mul_one_class H] [monoid_hom_class F G H] (f : F) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h x, (map_eq_one_iff f h).mp, λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [map_mul, hxy, ← map_mul, mul_inv_self, map_one]⟩ /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see `injective_iff_map_eq_one`. -/ @[to_additive "A homomorphism from an additive group to an additive monoid is injective iff its kernel is trivial, stated as an iff on the triviality of the kernel. For the implication, see `injective_iff_map_eq_zero`."] lemma _root_.injective_iff_map_eq_one' {G H} [group G] [mul_one_class H] [monoid_hom_class F G H] (f : F) : function.injective f ↔ (∀ a, f a = 1 ↔ a = 1) := (injective_iff_map_eq_one f).trans $ forall_congr $ λ a, ⟨λ h, ⟨h, λ H, H.symm ▸ map_one f⟩, iff.mp⟩ include mM /-- Makes a group homomorphism from a proof that the map preserves multiplication. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves addition.", simps {fully_applied := ff}] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_left_eq_self.1 $ by rw [←map_mul, mul_one] } omit mM /-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`. See also `monoid_hom.of_map_div` for a version using `λ x y, x / y`. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using `λ a b, a - b`."] def of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : G →* H := mk' f $ λ x y, calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, inv_one, ← map_div, inv_inv] ... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] } @[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : ⇑(of_map_mul_inv f map_div) = f := rfl /-- Define a morphism of additive groups given a map which respects ratios. -/ @[to_additive /-"Define a morphism of additive groups given a map which respects difference."-/] def of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) : G →* H := of_map_mul_inv f (by simpa only [div_eq_mul_inv] using hf) @[simp, to_additive] lemma coe_of_map_div {H : Type*} [group H] (f : G → H) (hf : ∀ x y, f (x / y) = f x / f y) : ⇑(of_map_div f hf) = f := rfl /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive] instance {M G} [mul_one_class M] [comm_group G] : has_inv (M →* G) := ⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩ /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ add_decl_doc add_monoid_hom.has_neg @[simp, to_additive] lemma inv_apply {M G} {mM : mul_one_class M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl @[simp, to_additive] lemma inv_comp {M N A} {mM : mul_one_class M} {gN : mul_one_class N} {gA : comm_group A} (φ : N →* A) (ψ : M →* N) : φ⁻¹.comp ψ = (φ.comp ψ)⁻¹ := by { ext, simp only [function.comp_app, inv_apply, coe_comp] } @[simp, to_additive] lemma comp_inv {M A B} {mM : mul_one_class M} {mA : comm_group A} {mB : comm_group B} (φ : A →* B) (ψ : M →* A) : φ.comp ψ⁻¹ = (φ.comp ψ)⁻¹ := by { ext, simp only [function.comp_app, inv_apply, map_inv, coe_comp] } /-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism sending `x` to `(f x) / (g x)`. -/ @[to_additive] instance {M G} [mul_one_class M] [comm_group G] : has_div (M →* G) := ⟨λ f g, mk' (λ x, f x / g x) $ λ a b, by simp [div_eq_mul_inv, mul_assoc, mul_left_comm, mul_comm]⟩ /-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g` is the homomorphism sending `x` to `(f x) - (g x)`. -/ add_decl_doc add_monoid_hom.has_sub @[simp, to_additive] lemma div_apply {M G} {mM : mul_one_class M} {gG : comm_group G} (f g : M →* G) (x : M) : (f / g) x = f x / g x := rfl end monoid_hom /-- Given two monoid with zero morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid with zero morphism sending `x` to `f x * g x`. -/ instance {M N} {hM : mul_zero_one_class M} [comm_monoid_with_zero N] : has_mul (M →*₀ N) := ⟨λ f g, { to_fun := λ a, f a * g a, map_zero' := by rw [map_zero, zero_mul], ..(f * g : M →* N) }⟩
a844e0961c26f55f72a11a7b8530a314e904b29b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/category/Module/biproducts.lean
b97cdc2bd3a49d08d0f78b4d989c0e97af782f1a
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,926
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.pi import category_theory.limits.shapes.biproducts import algebra.category.Module.limits import algebra.homology.short_exact.abelian /-! # The category of `R`-modules has finite biproducts -/ open category_theory open category_theory.limits open_locale big_operators universes w v u namespace Module variables {R : Type u} [ring R] -- As `Module R` is preadditive, and has all limits, it automatically has biproducts. instance : has_binary_biproducts (Module.{v} R) := has_binary_biproducts.of_has_binary_products instance : has_finite_biproducts (Module.{v} R) := has_finite_biproducts.of_has_finite_products -- We now construct explicit limit data, -- so we can compare the biproducts to the usual unbundled constructions. /-- Construct limit data for a binary product in `Module R`, using `Module.of R (M × N)`. -/ @[simps cone_X is_limit_lift] def binary_product_limit_cone (M N : Module.{v} R) : limits.limit_cone (pair M N) := { cone := { X := Module.of R (M × N), π := { app := λ j, discrete.cases_on j (λ j, walking_pair.cases_on j (linear_map.fst R M N) (linear_map.snd R M N)), naturality' := by rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟨⟩⟩⟩; refl, }}, is_limit := { lift := λ s, linear_map.prod (s.π.app ⟨walking_pair.left⟩) (s.π.app ⟨walking_pair.right⟩), fac' := by { rintros s (⟨⟩|⟨⟩); { ext x, simp, }, }, uniq' := λ s m w, begin ext; [rw ← w ⟨walking_pair.left⟩, rw ← w ⟨walking_pair.right⟩]; refl, end, } } @[simp] lemma binary_product_limit_cone_cone_π_app_left (M N : Module.{v} R) : (binary_product_limit_cone M N).cone.π.app ⟨walking_pair.left⟩ = linear_map.fst R M N := rfl @[simp] lemma binary_product_limit_cone_cone_π_app_right (M N : Module.{v} R) : (binary_product_limit_cone M N).cone.π.app ⟨walking_pair.right⟩ = linear_map.snd R M N := rfl /-- We verify that the biproduct in `Module R` is isomorphic to the cartesian product of the underlying types: -/ @[simps hom_apply] noncomputable def biprod_iso_prod (M N : Module.{v} R) : (M ⊞ N : Module.{v} R) ≅ Module.of R (M × N) := is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit M N) (binary_product_limit_cone M N).is_limit @[simp, elementwise] lemma biprod_iso_prod_inv_comp_fst (M N : Module.{v} R) : (biprod_iso_prod M N).inv ≫ biprod.fst = linear_map.fst R M N := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.left) @[simp, elementwise] lemma biprod_iso_prod_inv_comp_snd (M N : Module.{v} R) : (biprod_iso_prod M N).inv ≫ biprod.snd = linear_map.snd R M N := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.right) namespace has_limit variables {J : Type w} (f : J → Module.{max w v} R) /-- The map from an arbitrary cone over a indexed family of abelian groups to the cartesian product of those groups. -/ @[simps] def lift (s : fan f) : s.X ⟶ Module.of R (Π j, f j) := { to_fun := λ x j, s.π.app ⟨j⟩ x, map_add' := λ x y, by { ext, simp, }, map_smul' := λ r x, by { ext, simp, }, } /-- Construct limit data for a product in `Module R`, using `Module.of R (Π j, F.obj j)`. -/ @[simps] def product_limit_cone : limits.limit_cone (discrete.functor f) := { cone := { X := Module.of R (Π j, f j), π := discrete.nat_trans (λ j, (linear_map.proj j.as : (Π j, f j) →ₗ[R] f j.as)), }, is_limit := { lift := lift f, fac' := λ s j, by { cases j, ext, simp, }, uniq' := λ s m w, begin ext x j, dsimp only [has_limit.lift], simp only [linear_map.coe_mk], exact congr_arg (λ g : s.X ⟶ f j, (g : s.X → f j) x) (w ⟨j⟩), end, }, } end has_limit open has_limit variables {J : Type} (f : J → Module.{v} R) /-- We verify that the biproduct we've just defined is isomorphic to the `Module R` structure on the dependent function type -/ @[simps hom_apply] noncomputable def biproduct_iso_pi [fintype J] (f : J → Module.{v} R) : (⨁ f : Module.{v} R) ≅ Module.of R (Π j, f j) := is_limit.cone_point_unique_up_to_iso (biproduct.is_limit f) (product_limit_cone f).is_limit @[simp, elementwise] lemma biproduct_iso_pi_inv_comp_π [fintype J] (f : J → Module.{v} R) (j : J) : (biproduct_iso_pi f).inv ≫ biproduct.π f j = (linear_map.proj j : (Π j, f j) →ₗ[R] f j) := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk j) end Module section split_exact variables {R : Type u} {A M B : Type v} [ring R] [add_comm_group A] [module R A] [add_comm_group B] [module R B] [add_comm_group M] [module R M] variables {j : A →ₗ[R] M} {g : M →ₗ[R] B} open Module /--The isomorphism `A × B ≃ₗ[R] M` coming from a right split exact sequence `0 ⟶ A ⟶ M ⟶ B ⟶ 0` of modules.-/ noncomputable def lequiv_prod_of_right_split_exact {f : B →ₗ[R] M} (hj : function.injective j) (exac : j.range = g.ker) (h : g.comp f = linear_map.id) : (A × B) ≃ₗ[R] M := (({ right_split := ⟨as_hom f, h⟩, mono := (Module.mono_iff_injective $ as_hom j).mpr hj, exact := (exact_iff _ _).mpr exac } : right_split _ _).splitting.iso.trans $ biprod_iso_prod _ _).to_linear_equiv.symm /--The isomorphism `A × B ≃ₗ[R] M` coming from a left split exact sequence `0 ⟶ A ⟶ M ⟶ B ⟶ 0` of modules.-/ noncomputable def lequiv_prod_of_left_split_exact {f : M →ₗ[R] A} (hg : function.surjective g) (exac : j.range = g.ker) (h : f.comp j = linear_map.id) : (A × B) ≃ₗ[R] M := (({ left_split := ⟨as_hom f, h⟩, epi := (Module.epi_iff_surjective $ as_hom g).mpr hg, exact := (exact_iff _ _).mpr exac } : left_split _ _).splitting.iso.trans $ biprod_iso_prod _ _).to_linear_equiv.symm end split_exact
49b78170382748bb9a71efc031d9bf98049dac48
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.11.26.lean
1f568f5916e83f19d899f5e58adc7770a7d61f5e
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
10,428
lean
/- There are direct parallels between computational and logical types. The unit data type corresponds to the propositional/logical type, true: each has one value/proof. The empty data type has no constructors and so has no values. It is an uninhabited data type. It corresponds directly to the proposition, false: a logical type with no constructors and thus no proofs. That is just what makes it false! -/ #check unit #print unit #check empty #print empty #check true #print true #print false /- The true proposition is trivially provable. And that is what makes it always true. The introduction rule is called true introduction or, in Lean, true.intro. -/ theorem trueIsTrue : true := true.intro /- There is no proof of false, and thus there is no introduction rule for false! -/ theorem falseIsTrue : false := _ -- stuck /- There is however an elimination rule for false. The intuition is that if you ever get to a place where you've deduced a proof of false, then you must have made an invalid assumption along the way, so it makes no sense to reason any further, and the current goal, whatever it is, can simply be ignored. Note that arguments to functions are assumed values! The following example show that if you assume you are given a proof of false, then even a crazy goal can be "discharged", here the goal of showing 0 = 1. -/ def falseImpliesCrazy (f : false) : 0 = 1 := false.elim f /- The preceding function definition is equivalent to the following proof of the smae implication. -/ example : false → 0 = 1 := λ (f : false), false.elim f /- We can now generalize to a universal law of predicate logic: that for any proposition, P, false → P. This is the rule called ex falso quod libet: from false anything follows. -/ example : ∀ (P : Prop), false → P := λ (P : Prop), λ (f : false), false.elim f /- We can not introduce and understand the concept of logical negation. If P is an proposition, then not P, or ¬ P for shorthand, is the negation of P. It asserts that P is false. What that means in turn is that there can be no proof of P. We will now see how to prove that P is false. This leads us to the "proof strategy" of "proof by negation." -/ /- To show that P is false, show that assuming that P is true enables one to derive a proof of false, i.e., it leads to a contradiction. Given that a proof cannot be, the assumption that there is a proof of P must have been incorrect. Therefore there is no proof of P, P is false, and we can now state correctly that ¬ P is true. -/ #print not /- KEY IDEA: ¬ P is defined to mean P → false. So whenever you see ¬ P, remember that it literally means P → false. If you are asked to prove ¬ P, proceed by trying to prove P → false. You'd do this by assuming P and showing that that leads to a contradiction and thus a proof of false. Again, this is the strategy of proof by negation. It's just the definition of ¬. -/ /- To facilitate the following examples, we will now assume that P is some arbitrary proposition. -/ axiom P : Prop /- Now ¬ P is also a proposition. -/ #check ¬ P /- And it is defined to mean P → false. -/ #reduce ¬ P /- Proof by negation! Assume P, show that that enables one to deduce a proof of false. -/ example : ¬ P := λ (p : P), _ /- Contradiction. Key idea: a proof of P → false can be *applied* to a proof of P to derive a proof of false. From there, as the next example shows, one can use false elimination to complete any proof. -/ example : P → ¬ P → false := λ (p :P), λ (np : ¬ P), (np p) example : P → ¬ P → false := begin assume (p : P), assume (np : P → false), exact (np p), end /- We want to prove that if P is true then if ¬ P is also true then 0 = 1 is true. Assume P is true and that ¬ P is also true and show that false is true. Apply ¬ P to P to get false. QED. -/ example : P → ¬ P → 0 = 1 := begin assume (p : P), assume (np : ¬ P), exact false.elim (np p), end /- *** The or ∨ Connective *** -/ /- We assume now that Q is a proposition and that we have a proof of it, q. -/ axiom Q : Prop axiom q : Q /- There are two introduction rules for or. The first, or.inl takes a proof of P and returns a proof of P ∨ Q. The second, inr, takes a proof of Q and returns a proof of P ∨ Q. The following example illustrates the use of inr, as inl cannot be used in this case (because we don't have a proof of P). -/ example : P ∨ Q := or.inr q example : 0 = 1 ∨ 2 = 2 := or.inr (eq.refl 2) example : (P ∧ Q) ∨ Q := or.inr q -- or.intro_right (0 = 1) rfl /- In classical but not in constructive logic, P ∨ ¬ P is true for any proposition P. We have to add this as an axiom to Lean if we want to reason "classically" when using this proof assistant. -/ /- Reminder: What does ¬ P mean? -/ -- CONSTRUCTIVE LOGIC example : P ∨ ¬ P := begin _ end -- CLASSICAL LOGIC axiom em : ∀ (P : Prop), P ∨ ¬ P #check em Q example : ∀ (P : Prop), ¬ (¬ P) → P := begin assume (P : Prop), assume (nnp : ¬ ¬ P), cases (em P), exact h, have f : false := (nnp h), exact false.elim f, end example : ∀ (P : Prop), ¬ (¬ P) → P := λ (P : Prop), λ (nnp : ¬ ¬ P), match (em P) with | or.inl p := p | or.inr np := false.elim (nnp np) end /- Proof by contradiction. Want to show P. Show that ¬ P → false. That is, show ¬ ¬ P. Use theorem that ¬ ¬ P → P, which requires the law of the excluded middle. -/ /- Being a proof of a universal generalization, we can *apply* em to any proposition, P, to obtain a proof of P ∨ ¬ P. -/ example : P ∨ ¬ P := em P example : Q ∨ ¬ Q := em Q #check em Q /- What we do to use** such a proof, or any proof of a disjunction, P ∨ Q, is to reason by case analysis. The goal will be to show that (P ∨ Q) → R. The challenge is that P ∨ Q can be true because P is or because Q is. So to show that R follows logically from (P ∨ Q), we need to show that it follows *in either case*. That is, we'd need to show that P → R and Q → R. If both cases are true, then R must be true no matter why P ∨ Q is true (either because P is or because R is). -/ axioms (R : Prop) (p : P) (pr: P → R) (qr: Q → R) example : (P ∨ Q) → R := λ (pq : P ∨ Q), -- case analysis on pq!!! match pq with | or.inl pfP := pr p | or.inr pfQ := qr q end example : (P ∨ Q) → R := begin assume pq, cases pq with pfP pfQ, apply pr pfP, apply qr pfQ, end /- Proof by negation. To prove ¬ P, assume P and show that that assumption can be used to produce a contradiction. -/ example : ¬ false := λ (f : false), f -- do this with a tactic script example : ∀ (P : Prop), ¬ (P ∧ ¬ P) := λ (P : Prop), λ (h : P ∧ ¬ P), (h.right h.left) -- do this with a tactic script /- Existential quantification! -/ #print exists example : ∃ (n : ℕ), n * n = 81 := exists.intro 9 rfl example : ∃ (n : ℕ), n * n = 81 := begin apply exists.intro _ _, exact 9, exact rfl, end -- let's make up another exercise axiom Ball : Type axiom isGreen : Ball → Prop axiom isBlue : Ball → Prop example : (∃ (b : Ball), isGreen b ∧ isBlue b) → ∃ (b : Ball), isGreen b := begin assume h, cases h with w pf, apply exists.intro w _, exact pf.left, end axiom Person : Type axiom Likes : Person → Person → Prop example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (x : Person), ∃ (y : Person), Likes x y ) := λ h, λ p, match h with | (exists.intro w pf) := exists.intro w (pf p) end example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (x : Person), ∃ (y : Person), Likes x y ) := begin assume h, assume p, cases h with w pf, exact exists.intro w (pf p) end def even : nat → Prop | n := n % 2 = 0 example : exists (n : nat), even n := _ example : exists (n : nat), even n := begin apply exists.intro 2 _, unfold even, exact eq.refl 0, end example : ∀ (n : ℕ), n = 0 ∨ n ≠ 0 := λ n, match n with | nat.zero := or.inl (eq.refl 0) | (nat.succ n') := or.inr (λ h, match h with end) end axiom Person : Type axiom Likes : Person → Person → Prop example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q) := begin assume (h : (∃ (p : Person), ∀ (q : Person), Likes q p)), assume (p : Person), cases h with w pf, apply exists.intro w (pf p), end example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q) := λ (h : (∃ (p : Person), ∀ (q : Person), Likes q p)), λ (p : Person), match h with | exists.intro w pf := exists.intro w (pf p) end -- cases is implemented by pattern matching! -- By destructuring h and giving names to its parts. -- I.e., h must be of the form (exists.intro w pf). -- Giving names to the parts enables us now to -- construct the proof of the conclusion by -- using exists.intro applied to w, and to a -- proof about w built by applying pf to w. -- Short version! example : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q) := λ h p, match h with | exists.intro w pf := exists.intro w (pf p) end example : ∀ (b : bool), bor b tt = tt := begin assume b, cases b with T F, apply eq.refl tt, apply eq.refl tt, end example : ∀ (n : ℕ), n = 0 ∨ n ≠ 0 := begin assume (n : ℕ), cases n, apply or.inl (eq.refl 0), apply or.inr _, assume h, cases h, end example : ∀ (n : ℕ), n = 0 ∨ n ≠ 0 := λ n, match n with | nat.zero := or.inl (eq.refl 0) | (nat.succ n') := or.inr ( λ h, match h with end ) end axiom Rel : Person → Person → Prop example: symmetric Rel → ∀ (p1 p2 : Person), Rel p1 p2 → Rel p2 p1 := begin assume h, intros p1 p2, assume r, unfold symmetric at h, exact (h r), end example : (¬ ∃ (p : Person), ∀ (q : Person), ¬ Likes p q) → (∀ (p : Person), ∃ (q : Person), Likes p q) := begin assume h, intro p, apply exists.intro p _, end ∧ ∨ ¬ → ↔ ∀
9fb93ef8b9bc5a586518c423bbf87f74613f505d
35677d2df3f081738fa6b08138e03ee36bc33cad
/test/monotonicity.lean
da77d7d3d08f168ba73be61adb8fb595bcc64bd6
[ "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
8,214
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity tactic.norm_num import algebra.ordered_ring import data.list.defs open list tactic tactic.interactive example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := by ac_mono example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, apply le_refl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, apply le_refl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [decidable_linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end
5dae6453e95ed78b40b3b6ca19934dd90a6f93f6
618003631150032a5676f229d13a079ac875ff77
/src/analysis/calculus/times_cont_diff.lean
6e219d05cdab982952aa9a6bee57710f2cfde3dd
[ "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
81,119
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.fderiv /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `times_cont_diff 𝕜 n f` and `times_cont_diff_on 𝕜 n f s` saying that the function is `C^n`, respectively in the whole space or on the set `s`. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `times_cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `formal_multilinear_series 𝕜 E F`: a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `times_cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `times_cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `times_cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `times_cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. Also, there are locality problems in time: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and time in our definition of `times_cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_semimodule add_comm_group.to_add_comm_monoid open set fin open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group] def formal_multilinear_series (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (F : Type*) [normed_group F] [normed_space 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ local attribute [reducible] formal_multilinear_series instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : ∀ n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, apply_instance end end module namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F) (q n) /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr, funext i, cases i with i hi, exact h2 i hi hi } end formal_multilinear_series variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa continuous_linear_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, have : (m : with_top ℕ) = ((0 : ℕ) : with_bot ℕ) := le_antisymm hm bot_le, rw with_top.coe_eq_coe at this, rw this, have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, continuous_linear_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ⊤ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m (le_refl _) } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr, ext i, have : i = 0 := subsingleton.elim i 0, rw this, refl end lemma has_ftaylor_series_up_to_on.differentiable_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) (le_refl _)⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s, rw continuous_linear_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv 𝕜 (λ i : fin m.succ, E) F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa continuous_linear_equiv.comp_continuous_on_iff at this } } } end variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives within `s` up to order `n`, which are continuous. There is a subtlety on sets where derivatives are not unique, that choices of derivatives around different points might not match. To ensure that being `C^n` is a local property, we therefore require it locally around each point. There is another subtlety that one might be able to find nice derivatives up to `n` for any finite `n`, but that they don't match so that one can not find them up to infinity. To get a good notion for `n = ∞`, we only require that for any finite `n` we may find such matching derivatives. -/ definition times_cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma times_cont_diff_on_nat {n : ℕ} : times_cont_diff_on 𝕜 n f s ↔ ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := begin refine ⟨λ H, H n (le_refl _), λ H m hm x hx, _⟩, rcases H x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp.of_le hm⟩ end lemma times_cont_diff_on_top : times_cont_diff_on 𝕜 ⊤ f s ↔ ∀ (n : ℕ), times_cont_diff_on 𝕜 n f s := begin split, { assume H n m hm x hx, rcases H m le_top x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ }, { assume H m hm x hx, rcases H m m (le_refl _) x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, p, hp⟩ } end lemma times_cont_diff_on.continuous_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) : continuous_on f s := begin apply continuous_on_of_locally_continuous_on (λ x hx, _), rcases h 0 bot_le x hx with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, refine ⟨t, t_open, xt, _⟩, rw inter_comm at tu, exact (H.mono tu).continuous_on end lemma times_cont_diff_on.congr {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s := begin assume m hm x hx, rcases h m hm x hx with ⟨u, hu, p, H⟩, refine ⟨u ∩ s, filter.inter_mem_sets hu self_mem_nhds_within, p, _⟩, exact (H.mono (inter_subset_left u s)).congr (λ x hx, h₁ x hx.2) end lemma times_cont_diff_on_congr {n : with_top ℕ} (h₁ : ∀ x ∈ s, f₁ x = f x) : times_cont_diff_on 𝕜 n f₁ s ↔ times_cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma times_cont_diff_on.mono {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : times_cont_diff_on 𝕜 n f t := begin assume m hm x hx, rcases h m hm x (hst hx) with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_mono x hst hu, p, H⟩ end lemma times_cont_diff_on.congr_mono {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : times_cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ lemma times_cont_diff_on.of_le {m n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : times_cont_diff_on 𝕜 m f s := begin assume k hk x hx, rcases h k (le_trans hk hmn) x hx with ⟨u, hu, p, H⟩, exact ⟨u, hu, p, H⟩ end /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma times_cont_diff_on.differentiable_on {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := begin apply differentiable_on_of_locally_differentiable_on (λ x hx, _), rcases h 1 hn x hx with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, exact ⟨t, t_open, xt, (H.mono tu).differentiable_on (le_refl _)⟩ end /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma times_cont_diff_on_of_locally_times_cont_diff_on {n : with_top ℕ} (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ times_cont_diff_on 𝕜 n f (s ∩ u)) : times_cont_diff_on 𝕜 n f s := begin assume m hm x hx, rcases h x hx with ⟨u, u_open, xu, Hu⟩, rcases Hu m hm x ⟨hx, xu⟩ with ⟨v, hv, p, H⟩, rw ← nhds_within_restrict s xu u_open at hv, exact ⟨v, hv, p, H⟩, end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem times_cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ nhds_within x s, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (times_cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases h n.succ (le_refl _) x hx with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume m hm z hz, exact ⟨u, self_mem_nhds_within, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩ }, { assume h, rw times_cont_diff_on_nat, assume x hx, rcases h x hx with ⟨u, hu, f', f'_eq_deriv, Hf'⟩, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, rcases Hf' n (le_refl _) x xu with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, filter.inter_mem_sets (nhds_within_le_of_mem hu hv) hu, λ x, (p' x).unshift (f x), _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ (z : E), (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw continuous_linear_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, continuous_linear_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin (n + 1)), E) F), have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw continuous_linear_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (mem_nhds_sets hu hx.2) ((unique_diff_within_at_inter (mem_nhds_sets hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ nhds_within x s) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ nhds x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma times_cont_diff_on_zero : times_cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume m hm x hx, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨H, λ x hx, by simp [ftaylor_series_within]⟩ end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on {n : with_top ℕ} (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on.ftaylor_series_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases h m.succ (with_top.add_one_le_of_lt hm) x hx with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (mem_nhds_sets o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h m hm x hx with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (mem_nhds_sets o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (le_refl _) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m (le_refl _)).congr (λ y hy, (A y hy).symm) } end lemma times_cont_diff_on_of_continuous_on_differentiable_on {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : times_cont_diff_on 𝕜 n f s := begin assume m hm x hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk x hx, convert (Hdiff k (lt_of_lt_of_le hk hm) x hx).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma times_cont_diff_on_of_differentiable_on {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : times_cont_diff_on 𝕜 n f s := times_cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma times_cont_diff_on.continuous_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma times_cont_diff_on.differentiable_on_iterated_fderiv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma times_cont_diff_on_iff_continuous_on_differentiable_on {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact times_cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume H, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), _⟩, apply times_cont_diff_on_of_locally_times_cont_diff_on, assume x hx, rcases times_cont_diff_on_succ_iff_has_fderiv_within_at.1 H x hx with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, apply (hf'.mono ho).congr (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (mem_nhds_sets o_open hy.2) (hs y hy.1) at A }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at, rintros ⟨hdiff, h⟩ x hx, exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ x hx, (hdiff x hx).has_fderiv_within_at, h⟩ } end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 ⊤ f s ↔ differentiable_on 𝕜 f s ∧ times_cont_diff_on 𝕜 ⊤ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply times_cont_diff_on_top.2 (λ n, ((times_cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine times_cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ⊤ := le_top, apply ((times_cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end lemma times_cont_diff_on.fderiv_within {m n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ⊤ + 1 ≤ n at hmn, have : n = ⊤, by simpa using hmn, rw this at hf, exact ((times_cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma times_cont_diff_on.continuous_on_fderiv_within {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((times_cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff_on.continuous_on_fderiv_within_apply {n : with_top ℕ} (h : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (set.prod s univ) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (set.prod s univ), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff {n : with_top ℕ} : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le {m n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable {n : with_top ℕ} (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_bot.coe_add] variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition times_cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem times_cont_diff_on_univ {n : with_top ℕ} : times_cont_diff_on 𝕜 n f univ ↔ times_cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ m hm x hx, exact ⟨univ, self_mem_nhds_within, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma times_cont_diff_top : times_cont_diff 𝕜 ⊤ f ↔ ∀ (n : ℕ), times_cont_diff 𝕜 n f := by simp [times_cont_diff_on_univ.symm, times_cont_diff_on_top] lemma times_cont_diff.times_cont_diff_on {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : times_cont_diff_on 𝕜 n f s := (times_cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma times_cont_diff_zero : times_cont_diff 𝕜 0 f ↔ continuous f := begin rw [← times_cont_diff_on_univ, continuous_iff_continuous_on_univ], exact times_cont_diff_on_zero end lemma times_cont_diff.of_le {m n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hmn : m ≤ n) : times_cont_diff 𝕜 m f := times_cont_diff_on_univ.1 $ (times_cont_diff_on_univ.2 h).of_le hmn lemma times_cont_diff.continuous {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) : continuous f := times_cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma times_cont_diff.differentiable {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (times_cont_diff_on_univ.2 h).differentiable_on hn variable (𝕜) /-! ### Iterated derivative -/ /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem times_cont_diff_on_iff_ftaylor_series {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← times_cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, times_cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma times_cont_diff_iff_continuous_differentiable {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [times_cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, times_cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma times_cont_diff_of_differentiable_iterated_fderiv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^n`. -/ theorem times_cont_diff_succ_iff_fderiv {n : ℕ} : times_cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, times_cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_bot.coe_add, -add_comm] /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative is `C^∞`. -/ theorem times_cont_diff_top_iff_fderiv : times_cont_diff 𝕜 ⊤ f ↔ differentiable 𝕜 f ∧ times_cont_diff 𝕜 ⊤ (λ y, fderiv 𝕜 f y) := begin simp [times_cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw times_cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma times_cont_diff.continuous_fderiv {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((times_cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma times_cont_diff.continuous_fderiv_apply {n : with_top ℕ} (h : times_cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma times_cont_diff_zero_fun {n : with_top ℕ} : times_cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply times_cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma times_cont_diff_const {n : with_top ℕ} {c : F} : times_cont_diff 𝕜 n (λx : E, c) := begin suffices h : times_cont_diff 𝕜 ⊤ (λx : E, c), by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact times_cont_diff_zero_fun end lemma times_cont_diff_on_const {n : with_top ℕ} {c : F} {s : set E} : times_cont_diff_on 𝕜 n (λx : E, c) s := times_cont_diff_const.times_cont_diff_on /-! ### Linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.times_cont_diff {n : with_top ℕ} (hf : is_bounded_linear_map 𝕜 f) : times_cont_diff 𝕜 n f := begin suffices h : times_cont_diff 𝕜 ⊤ f, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp [hf.fderiv], exact times_cont_diff_const end lemma continuous_linear_map.times_cont_diff {n : with_top ℕ} (f : E →L[𝕜] F) : times_cont_diff 𝕜 n f := f.is_bounded_linear_map.times_cont_diff /-- The first projection in a product is `C^∞`. -/ lemma times_cont_diff_fst {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.fst /-- The second projection in a product is `C^∞`. -/ lemma times_cont_diff_snd {n : with_top ℕ} : times_cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.times_cont_diff is_bounded_linear_map.snd /-- The identity is `C^∞`. -/ lemma times_cont_diff_id {n : with_top ℕ} : times_cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.times_cont_diff /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.times_cont_diff {n : with_top ℕ} (hb : is_bounded_bilinear_map 𝕜 b) : times_cont_diff 𝕜 n b := begin suffices h : times_cont_diff 𝕜 ⊤ b, by exact h.of_le le_top, rw times_cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.times_cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin split, { assume x hx, simp [(hf.zero_eq x hx).symm] }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, have := hf.fderiv_within m hm x hx, convert has_fderiv_at.comp_has_fderiv_within_at x (hA.has_fderiv_at) this }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (E [×m]→L[𝕜] G) := λ f, g.comp_continuous_multilinear_map f, have hA : is_bounded_linear_map 𝕜 A := is_bounded_bilinear_map_comp_multilinear.is_bounded_linear_map_right _, exact hA.continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.continuous_linear_map_comp {n : with_top ℕ} (g : F →L[𝕜] G) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin assume m hm x hx, rcases hf m hm x hx with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma times_cont_diff.continuous_linear_map_comp {n : with_top ℕ} {f : E → F} (g : F →L[𝕜] G) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, g (f x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.continuous_linear_map_comp _ (times_cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_times_cont_diff_on_iff {n : with_top ℕ} (e : F ≃L[𝕜] G) : times_cont_diff_on 𝕜 n (e ∘ f) s ↔ times_cont_diff_on 𝕜 n f s := begin split, { assume H, have : f = e.symm ∘ (e ∘ f), by { ext y, simp only [function.comp_app], rw e.symm_apply_apply (f y) }, rw this, exact H.continuous_linear_map_comp _ }, { assume H, exact H.continuous_linear_map_comp _ } end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map 𝕜 E g) (g ⁻¹' s) := begin split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ h, h.comp_continuous_linear_map 𝕜 E g, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_continuous_multilinear_map_comp_linear g, convert (hA.has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, let A : (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ h, h.comp_continuous_linear_map 𝕜 E g, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_continuous_multilinear_map_comp_linear g, exact hA.continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma times_cont_diff_on.comp_continuous_linear_map {n : with_top ℕ} (hf : times_cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := begin assume m hm x hx, rcases hf m hm (g x) hx with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { exact nhds_within_mono (g x) (image_preimage_subset g s) hu } end /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma times_cont_diff.comp_continuous_linear_map {n : with_top ℕ} {f : E → F} {g : G →L[𝕜] E} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (f ∘ g) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp_continuous_linear_map (times_cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.times_cont_diff_on_comp_iff {n : with_top ℕ} (e : G ≃L[𝕜] E) : times_cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ times_cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map _⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map _ end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod {n : with_top ℕ} (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, convert hA.has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, let A : (E [×m]→L[𝕜] F) × (E [×m]→L[𝕜] G) → (E [×m]→L[𝕜] (F × G)) := λ p, p.1.prod p.2, have hA : is_bounded_linear_map 𝕜 A := is_bounded_linear_map_prod_multilinear, exact hA.continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.prod {n : with_top ℕ} {s : set E} {f : E → F} {g : E → G} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx:E, (f x, g x)) s := begin assume m hm x hx, rcases hf m hm x hx with ⟨u, hu, p, hp⟩, rcases hg m hm x hx with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem_sets hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions is `C^n`. -/ lemma times_cont_diff.prod {n : with_top ℕ} {f : E → F} {g : E → G} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx:E, (f x, g x)) := times_cont_diff_on_univ.1 $ times_cont_diff_on.prod (times_cont_diff_on_univ.2 hf) (times_cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `times_cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma times_cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {n : with_top ℕ} {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezeI, induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu, { rw times_cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw times_cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (times_cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ nhds_within x s, { apply filter.inter_mem_sets self_mem_nhds_within, apply filter.inter_mem_sets hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { exact nhds_within_mono _ (image_subset_iff.2 st) hv } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show times_cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : times_cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : times_cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : times_cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := times_cont_diff_on.prod B A, have D : times_cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.times_cont_diff.times_cont_diff_on, exact IH D C (subset_univ _) } }, { rw times_cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma times_cont_diff_on.comp {n : with_top ℕ} {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : times_cont_diff_on 𝕜 n g t) (hf : times_cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : times_cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. The instances are not found automatically by Lean, so we declare them by hand. TODO: fix. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) E _ _ _ _ _ _ _, letI : normed_space 𝕜 Eu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) E _ _ _ _ _ _ _, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) F _ _ _ _ _ _ _, letI : normed_space 𝕜 Fu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) F _ _ _ _ _ _ _, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := @continuous_multilinear_map.to_normed_group 𝕜 (fin 0) (λ (i : fin 0), E × F × G) G _ _ _ _ _ _ _, letI : normed_space 𝕜 Gu := @continuous_multilinear_map.to_normed_space 𝕜 (fin 0) (λ (i : fin 0), E × F × G) G _ _ _ _ _ _ _, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : times_cont_diff_on 𝕜 n fu (isoE ⁻¹' s) := by rwa [isoE.times_cont_diff_on_comp_iff, isoF.symm.comp_times_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : times_cont_diff_on 𝕜 n gu (isoF ⁻¹' t) := by rwa [isoF.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff], have main : times_cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply times_cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.times_cont_diff_on_comp_iff, isoG.symm.comp_times_cont_diff_on_iff] at main end /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma times_cont_diff.comp_times_cont_diff_on {n : with_top ℕ} {s : set E} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (g ∘ f) s := (times_cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma times_cont_diff.comp {n : with_top ℕ} {g : F → G} {f : E → F} (hg : times_cont_diff 𝕜 n g) (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (g ∘ f) := times_cont_diff_on_univ.1 $ times_cont_diff_on.comp (times_cont_diff_on_univ.2 hg) (times_cont_diff_on_univ.2 hf) (subset_univ _) /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : times_cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (set.prod s (univ : set E)) := begin have A : times_cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.times_cont_diff, exact is_bounded_bilinear_map_apply }, have B : times_cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (set.prod s univ), { apply times_cont_diff_on.prod _ _, { have I : times_cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : times_cont_diff_on 𝕜 m (λ (x : E × E), x.1) (set.prod s univ) := times_cont_diff_fst.times_cont_diff_on, exact times_cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply times_cont_diff.times_cont_diff_on _ , apply is_bounded_linear_map.snd.times_cont_diff } }, exact A.comp_times_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma times_cont_diff.times_cont_diff_fderiv_apply {n m : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : times_cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← times_cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact times_cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-- The sum of two `C^n`functions on a domain is `C^n`. -/ lemma times_cont_diff_on.add {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x + g x) s := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp_times_cont_diff_on (hf.prod hg) end /-- The sum of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.add {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x + g x) := begin have : times_cont_diff 𝕜 n (λp : F × F, p.1 + p.2), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.add is_bounded_linear_map.fst is_bounded_linear_map.snd }, exact this.comp (hf.prod hg) end /-- The negative of a `C^n`function on a domain is `C^n`. -/ lemma times_cont_diff_on.neg {n : with_top ℕ} {s : set E} {f : E → F} (hf : times_cont_diff_on 𝕜 n f s) : times_cont_diff_on 𝕜 n (λx, -f x) s := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp_times_cont_diff_on hf end /-- The negative of a `C^n`function is `C^n`. -/ lemma times_cont_diff.neg {n : with_top ℕ} {f : E → F} (hf : times_cont_diff 𝕜 n f) : times_cont_diff 𝕜 n (λx, -f x) := begin have : times_cont_diff 𝕜 n (λp : F, -p), { apply is_bounded_linear_map.times_cont_diff, exact is_bounded_linear_map.neg is_bounded_linear_map.id }, exact this.comp hf end /-- The difference of two `C^n`functions on a domain is `C^n`. -/ lemma times_cont_diff_on.sub {n : with_top ℕ} {s : set E} {f g : E → F} (hf : times_cont_diff_on 𝕜 n f s) (hg : times_cont_diff_on 𝕜 n g s) : times_cont_diff_on 𝕜 n (λx, f x - g x) s := hf.add (hg.neg) /-- The difference of two `C^n`functions is `C^n`. -/ lemma times_cont_diff.sub {n : with_top ℕ} {f g : E → F} (hf : times_cont_diff 𝕜 n f) (hg : times_cont_diff 𝕜 n g) : times_cont_diff 𝕜 n (λx, f x - g x) := hf.add hg.neg
82ab97660b8559125ac2b9bb12cc18c4165ab07b
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/equiv/denumerable.lean
cfa8ad0d23f662d43a62da68ba7e69ea66b8fd71
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
8,961
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Denumerable (countably infinite) types, as a typeclass extending encodable. This is used to provide explicit encode/decode functions from nat, where the functions are known inverses of each other. -/ import data.equiv.encodable data.sigma data.fintype data.list.min_max open nat /-- A denumerable type is one which is (constructively) bijective with ℕ. Although we already have a name for this property, namely `α ≃ ℕ`, we are here interested in using it as a typeclass. -/ class denumerable (α : Type*) extends encodable α := (decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n) namespace denumerable section variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable @[simp] theorem decode_is_some (α) [denumerable α] (n : ℕ) : (decode α n).is_some := option.is_some_iff_exists.2 $ (decode_inv α n).imp $ λ a, Exists.fst def of_nat (α) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp] theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) : decode α n = some (of_nat α n) := option.eq_some_of_is_some _ @[simp] theorem of_nat_of_decode {n b} (h : decode α n = some b) : of_nat α n = b := option.some.inj $ (decode_eq_of_nat _ _).symm.trans h @[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n := let ⟨a, h, e⟩ := decode_inv α n in by rwa [of_nat_of_decode h] @[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a := of_nat_of_decode (encodek _) def eqv (α) [denumerable α] : α ≃ ℕ := ⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩ def mk' {α} (e : α ≃ ℕ) : denumerable α := { encode := e, decode := some ∘ e.symm, encodek := λ a, congr_arg some (e.symm_apply_apply _), decode_inv := λ n, ⟨_, rfl, e.apply_symm_apply _⟩ } def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β := { decode_inv := λ n, by simp, ..encodable.of_equiv _ e } @[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α) (n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) := by apply of_nat_of_decode; show option.map _ _ = _; simp def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : denumerable nat := ⟨λ n, ⟨_, rfl, rfl⟩⟩ @[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl instance option : denumerable (option α) := ⟨λ n, by cases n; simp⟩ instance sum : denumerable (α ⊕ β) := ⟨λ n, begin suffices : ∃ a ∈ @decode_sum α β _ _ n, encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]}, simp [decode_sum]; cases bodd n; simp [decode_sum, bit, encode_sum] end⟩ section sigma variables {γ : α → Type*} [∀ a, denumerable (γ a)] instance sigma : denumerable (sigma γ) := ⟨λ n, by simp [decode_sigma]; exact ⟨_, _, ⟨rfl, heq.rfl⟩, by simp⟩⟩ @[simp] theorem sigma_of_nat_val (n : ℕ) : of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ := option.some.inj $ by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl end sigma instance prod : denumerable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem prod_of_nat_val (n : ℕ) : of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) := by simp; refl @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair := by funext; simp instance int : denumerable ℤ := denumerable.mk' equiv.int_equiv_nat instance pnat : denumerable ℕ+ := denumerable.mk' equiv.pnat_equiv_nat instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift instance plift : denumerable (plift α) := of_equiv _ equiv.plift def pair : α × α ≃ α := equiv₂ _ _ end end denumerable namespace nat.subtype open function encodable lattice variables {s : set ℕ} [decidable_pred s] [infinite s] lemma exists_succ (x : s) : ∃ n, x.1 + n + 1 ∈ s := classical.by_contradiction $ λ h, have ∀ (a : ℕ) (ha : a ∈ s), a < x.val.succ, from λ a ha, lt_of_not_ge (λ hax, h ⟨a - (x.1 + 1), by rwa [add_right_comm, nat.add_sub_cancel' hax]⟩), infinite.not_fintype ⟨(((multiset.range x.1.succ).filter (∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), subtype.mk y hy) (by simp [-multiset.range_succ])).to_finset, by simpa [subtype.ext, multiset.mem_filter, -multiset.range_succ]⟩ def succ (x : s) : s := have h : ∃ m, x.1 + m + 1 ∈ s, from exists_succ x, ⟨x.1 + nat.find h + 1, nat.find_spec h⟩ lemma succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, let ⟨k, hk⟩ := nat.exists_eq_add_of_lt h in have nat.find hx ≤ k, from nat.find_min' _ (hk ▸ x.2), show y.1 + nat.find hx + 1 ≤ x.1, by rw hk; exact add_le_add_right (add_le_add_left this _) _ lemma le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _, show x.1 ≤ y.1 + nat.find hx + 1, from le_of_not_gt $ λ hxy, have y.1 + nat.find hx + 1 ≤ y.1 := h ⟨_, nat.find_spec hx⟩ hxy, not_lt_of_le this $ calc y.1 ≤ y.1 + nat.find hx : le_add_of_nonneg_right (nat.zero_le _) ... < y.1 + nat.find hx + 1 : nat.lt_succ_self _ lemma lt_succ_self (x : s) : x < succ x := calc x.1 ≤ x.1 + _ : le_add_right (le_refl _) ... < succ x : nat.lt_succ_self (x.1 + _) lemma lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨λ h, le_of_not_gt (λ h', not_le_of_gt h (succ_le_of_lt h')), λ h, lt_of_le_of_lt h (lt_succ_self _)⟩ def of_nat (s : set ℕ) [decidable_pred s] [infinite s] : ℕ → s | 0 := ⊥ | (n+1) := succ (of_nat n) lemma of_nat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, of_nat s n = ⟨x, hx⟩ | x := λ hx, let t : list s := ((list.range x).filter (λ y, y ∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), ⟨y, hy⟩) (by simp) in have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩, by simp [list.mem_filter, subtype.ext, t]; intros; refl, have wf : ∀ m : s, list.maximum t = m → m.1 < x, from λ m hmax, by simpa [hmt] using list.maximum_mem hmax, begin cases hmax : list.maximum t with m, { exact ⟨0, le_antisymm (@bot_le s _ _) (le_of_not_gt (λ h, list.not_mem_nil (⊥ : s) $ by rw [← list.maximum_eq_none.1 hmax, hmt]; exact h))⟩ }, { cases of_nat_surjective_aux m.2 with a ha, exact ⟨a + 1, le_antisymm (by rw of_nat; exact succ_le_of_lt (by rw ha; exact wf _ hmax)) $ by rw of_nat; exact le_succ_of_forall_lt_le (λ z hz, by rw ha; cases m; exact list.le_maximum_of_mem (hmt.2 hz) hmax)⟩ } end using_well_founded {dec_tac := `[tauto]} lemma of_nat_surjective : surjective (of_nat s) := λ ⟨x, hx⟩, of_nat_surjective_aux hx private def to_fun_aux (x : s) : ℕ := (list.range x).countp s private lemma to_fun_aux_eq (x : s) : to_fun_aux x = ((finset.range x).filter s).card := by rw [to_fun_aux, list.countp_eq_length_filter]; refl open finset private lemma right_inverse_aux : ∀ n, to_fun_aux (of_nat s n) = n | 0 := begin rw [to_fun_aux_eq, card_eq_zero, eq_empty_iff_forall_not_mem], assume n, rw [mem_filter, of_nat, mem_range], assume h, exact not_lt_of_le bot_le (show (⟨n, h.2⟩ : s) < ⊥, from h.1) end | (n+1) := have ih : to_fun_aux (of_nat s n) = n, from right_inverse_aux n, have h₁ : (of_nat s n : ℕ) ∉ (range (of_nat s n)).filter s, by simp, have h₂ : (range (succ (of_nat s n))).filter s = insert (of_nat s n) ((range (of_nat s n)).filter s), begin simp only [finset.ext, mem_insert, mem_range, mem_filter], assume m, exact ⟨λ h, by simp only [h.2, and_true]; exact or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), λ h, h.elim (λ h, h.symm ▸ ⟨lt_succ_self _, subtype.property _⟩) (λ h, ⟨lt_of_le_of_lt (le_of_lt h.1) (lt_succ_self _), h.2⟩)⟩ end, begin clear_aux_decl, simp only [to_fun_aux_eq, of_nat, range_succ] at *, conv {to_rhs, rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] }, end def denumerable (s : set ℕ) [decidable_pred s] [infinite s] : denumerable s := denumerable.of_equiv ℕ { to_fun := to_fun_aux, inv_fun := of_nat s, left_inv := left_inverse_of_surjective_of_right_inverse of_nat_surjective right_inverse_aux, right_inv := right_inverse_aux } end nat.subtype namespace denumerable open encodable def of_encodable_of_infinite (α : Type*) [encodable α] [infinite α] : denumerable α := begin letI := @decidable_range_encode α _; letI : infinite (set.range (@encode α _)) := infinite.of_injective _ (equiv.set.range _ encode_injective).injective, letI := nat.subtype.denumerable (set.range (@encode α _)), exact denumerable.of_equiv (set.range (@encode α _)) (equiv_range_encode α) end end denumerable
0509b11edbe797911e1bc9d6ebc436edd17f2f7e
c777c32c8e484e195053731103c5e52af26a25d1
/src/geometry/euclidean/angle/unoriented/right_angle.lean
75beb298c607474d402d1597dc8b3ad1b5ec3809
[ "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,814
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 analysis.special_functions.trigonometric.arctan import geometry.euclidean.angle.unoriented.affine /-! # Right-angled triangles This file proves basic geometrical results about distances and angles in (possibly degenerate) right-angled triangles in real inner product spaces and Euclidean affine spaces. ## Implementation notes Results in this file are generally given in a form with only those non-degeneracy conditions needed for the particular result, rather than requiring affine independence of the points of a triangle unnecessarily. ## References * https://en.wikipedia.org/wiki/Pythagorean_theorem -/ noncomputable theory open_locale big_operators open_locale euclidean_geometry open_locale real open_locale real_inner_product_space namespace inner_product_geometry variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] /-- Pythagorean theorem, if-and-only-if vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := begin rw norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := begin rw norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, subtracting vectors, vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- An angle in a right-angled triangle expressed using `arccos`. -/ lemma angle_add_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x + y) = real.arccos (‖x‖ / ‖x + y‖) := begin rw [angle, inner_add_right, h, add_zero, real_inner_self_eq_norm_mul_norm], by_cases hx : ‖x‖ = 0, { simp [hx] }, rw [div_mul_eq_div_div, mul_self_div_self] end /-- An angle in a right-angled triangle expressed using `arcsin`. -/ lemma angle_add_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : angle x (x + y) = real.arcsin (‖y‖ / ‖x + y‖) := begin have hxy : ‖x + y‖ ^ 2 ≠ 0, { rw [pow_two, norm_add_sq_eq_norm_sq_add_norm_sq_real h, ne_comm], refine ne_of_lt _, rcases h0 with h0 | h0, { exact left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _) }, { exact left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) } }, rw [angle_add_eq_arccos_of_inner_eq_zero h, real.arccos_eq_arcsin (div_nonneg (norm_nonneg _) (norm_nonneg _)), div_pow, one_sub_div hxy], nth_rewrite 0 [pow_two], rw [norm_add_sq_eq_norm_sq_add_norm_sq_real h, pow_two, add_sub_cancel', ←pow_two, ←div_pow, real.sqrt_sq (div_nonneg (norm_nonneg _) (norm_nonneg _))] end /-- An angle in a right-angled triangle expressed using `arctan`. -/ lemma angle_add_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x + y) = real.arctan (‖y‖ / ‖x‖) := begin rw [angle_add_eq_arcsin_of_inner_eq_zero h (or.inl h0), real.arctan_eq_arcsin, ←div_mul_eq_div_div, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h], nth_rewrite 2 [←real.sqrt_sq (norm_nonneg x)], rw [←real.sqrt_mul (sq_nonneg _), div_pow, pow_two, pow_two, mul_add, mul_one, mul_div, mul_comm (‖x‖ * ‖x‖), ←mul_div, div_self (mul_self_pos.2 (norm_ne_zero_iff.2 h0)).ne', mul_one] end /-- An angle in a non-degenerate right-angled triangle is positive. -/ lemma angle_add_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : 0 < angle x (x + y) := begin rw [angle_add_eq_arccos_of_inner_eq_zero h, real.arccos_pos, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h], by_cases hx : x = 0, { simp [hx] }, rw [div_lt_one (real.sqrt_pos.2 (left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 hx)) (mul_self_nonneg _))), real.lt_sqrt (norm_nonneg _), pow_two], simpa [hx] using h0 end /-- An angle in a right-angled triangle is at most `π / 2`. -/ lemma angle_add_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x + y) ≤ π / 2 := begin rw [angle_add_eq_arccos_of_inner_eq_zero h, real.arccos_le_pi_div_two], exact div_nonneg (norm_nonneg _) (norm_nonneg _) end /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/ lemma angle_add_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x + y) < π / 2 := begin rw [angle_add_eq_arccos_of_inner_eq_zero h, real.arccos_lt_pi_div_two, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h], exact div_pos (norm_pos_iff.2 h0) (real.sqrt_pos.2 (left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _))) end /-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/ lemma cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.cos (angle x (x + y)) = ‖x‖ / ‖x + y‖ := begin rw [angle_add_eq_arccos_of_inner_eq_zero h, real.cos_arccos (le_trans (by norm_num) (div_nonneg (norm_nonneg _) (norm_nonneg _))) (div_le_one_of_le _ (norm_nonneg _))], rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _), norm_add_sq_eq_norm_sq_add_norm_sq_real h], exact le_add_of_nonneg_right (mul_self_nonneg _) end /-- The sine of an angle in a right-angled triangle as a ratio of sides. -/ lemma sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : real.sin (angle x (x + y)) = ‖y‖ / ‖x + y‖ := begin rw [angle_add_eq_arcsin_of_inner_eq_zero h h0, real.sin_arcsin (le_trans (by norm_num) (div_nonneg (norm_nonneg _) (norm_nonneg _))) (div_le_one_of_le _ (norm_nonneg _))], rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _), norm_add_sq_eq_norm_sq_add_norm_sq_real h], exact le_add_of_nonneg_left (mul_self_nonneg _) end /-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/ lemma tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.tan (angle x (x + y)) = ‖y‖ / ‖x‖ := begin by_cases h0 : x = 0, { simp [h0] }, rw [angle_add_eq_arctan_of_inner_eq_zero h h0, real.tan_arctan] end /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side. -/ lemma cos_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.cos (angle x (x + y)) * ‖x + y‖ = ‖x‖ := begin rw cos_angle_add_of_inner_eq_zero h, by_cases hxy : ‖x + y‖ = 0, { have h' := norm_add_sq_eq_norm_sq_add_norm_sq_real h, rw [hxy, zero_mul, eq_comm, add_eq_zero_iff' (mul_self_nonneg ‖x‖) (mul_self_nonneg ‖y‖), mul_self_eq_zero] at h', simp [h'.1] }, { exact div_mul_cancel _ hxy } end /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side. -/ lemma sin_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.sin (angle x (x + y)) * ‖x + y‖ = ‖y‖ := begin by_cases h0 : x = 0 ∧ y = 0, { simp [h0] }, rw not_and_distrib at h0, rw [sin_angle_add_of_inner_eq_zero h h0, div_mul_cancel], rw [←mul_self_ne_zero, norm_add_sq_eq_norm_sq_add_norm_sq_real h], refine (ne_of_lt _).symm, rcases h0 with h0 | h0, { exact left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _) }, { exact left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) } end /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side. -/ lemma tan_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : real.tan (angle x (x + y)) * ‖x‖ = ‖y‖ := begin rw [tan_angle_add_of_inner_eq_zero h], rcases h0 with h0 | h0; simp [h0] end /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse. -/ lemma norm_div_cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : ‖x‖ / real.cos (angle x (x + y)) = ‖x + y‖ := begin rw cos_angle_add_of_inner_eq_zero h, rcases h0 with h0 | h0, { rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] }, { simp [h0] } end /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse. -/ lemma norm_div_sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / real.sin (angle x (x + y)) = ‖x + y‖ := begin rcases h0 with h0 | h0, { simp [h0] }, rw [sin_angle_add_of_inner_eq_zero h (or.inr h0), div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] end /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side. -/ lemma norm_div_tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / real.tan (angle x (x + y)) = ‖x‖ := begin rw tan_angle_add_of_inner_eq_zero h, rcases h0 with h0 | h0, { simp [h0] }, { rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] } end /-- An angle in a right-angled triangle expressed using `arccos`, version subtracting vectors. -/ lemma angle_sub_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x - y) = real.arccos (‖x‖ / ‖x - y‖) := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, angle_add_eq_arccos_of_inner_eq_zero h] end /-- An angle in a right-angled triangle expressed using `arcsin`, version subtracting vectors. -/ lemma angle_sub_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : angle x (x - y) = real.arcsin (‖y‖ / ‖x - y‖) := begin rw [←neg_eq_zero, ←inner_neg_right] at h, nth_rewrite 1 ←neg_ne_zero at h0, rw [sub_eq_add_neg, angle_add_eq_arcsin_of_inner_eq_zero h h0, norm_neg] end /-- An angle in a right-angled triangle expressed using `arctan`, version subtracting vectors. -/ lemma angle_sub_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x - y) = real.arctan (‖y‖ / ‖x‖) := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, angle_add_eq_arctan_of_inner_eq_zero h h0, norm_neg] end /-- An angle in a non-degenerate right-angled triangle is positive, version subtracting vectors. -/ lemma angle_sub_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : 0 < angle x (x - y) := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw ←neg_ne_zero at h0, rw sub_eq_add_neg, exact angle_add_pos_of_inner_eq_zero h h0 end /-- An angle in a right-angled triangle is at most `π / 2`, version subtracting vectors. -/ lemma angle_sub_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x - y) ≤ π / 2 := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw sub_eq_add_neg, exact angle_add_le_pi_div_two_of_inner_eq_zero h end /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`, version subtracting vectors. -/ lemma angle_sub_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x - y) < π / 2 := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw sub_eq_add_neg, exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0 end /-- The cosine of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ lemma cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.cos (angle x (x - y)) = ‖x‖ / ‖x - y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, cos_angle_add_of_inner_eq_zero h] end /-- The sine of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ lemma sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : real.sin (angle x (x - y)) = ‖y‖ / ‖x - y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, nth_rewrite 1 ←neg_ne_zero at h0, rw [sub_eq_add_neg, sin_angle_add_of_inner_eq_zero h h0, norm_neg] end /-- The tangent of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ lemma tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.tan (angle x (x - y)) = ‖y‖ / ‖x‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, tan_angle_add_of_inner_eq_zero h, norm_neg] end /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side, version subtracting vectors. -/ lemma cos_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.cos (angle x (x - y)) * ‖x - y‖ = ‖x‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, cos_angle_add_mul_norm_of_inner_eq_zero h] end /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side, version subtracting vectors. -/ lemma sin_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : real.sin (angle x (x - y)) * ‖x - y‖ = ‖y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw [sub_eq_add_neg, sin_angle_add_mul_norm_of_inner_eq_zero h, norm_neg] end /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side, version subtracting vectors. -/ lemma tan_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : real.tan (angle x (x - y)) * ‖x‖ = ‖y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw ←neg_eq_zero at h0, rw [sub_eq_add_neg, tan_angle_add_mul_norm_of_inner_eq_zero h h0, norm_neg] end /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse, version subtracting vectors. -/ lemma norm_div_cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : ‖x‖ / real.cos (angle x (x - y)) = ‖x - y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw ←neg_eq_zero at h0, rw [sub_eq_add_neg, norm_div_cos_angle_add_of_inner_eq_zero h h0] end /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse, version subtracting vectors. -/ lemma norm_div_sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / real.sin (angle x (x - y)) = ‖x - y‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw ←neg_ne_zero at h0, rw [sub_eq_add_neg, ←norm_neg, norm_div_sin_angle_add_of_inner_eq_zero h h0] end /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side, version subtracting vectors. -/ lemma norm_div_tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / real.tan (angle x (x - y)) = ‖x‖ := begin rw [←neg_eq_zero, ←inner_neg_right] at h, rw ←neg_ne_zero at h0, rw [sub_eq_add_neg, ←norm_neg, norm_div_tan_angle_add_of_inner_eq_zero h h0] end end inner_product_geometry namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- **Pythagorean theorem**, if-and-only-if angle-at-point form. -/ lemma dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 ↔ ∠ p1 p2 p3 = π / 2 := by erw [dist_comm p3 p2, dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p2 p3, ←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two, vsub_sub_vsub_cancel_right p1, ←neg_vsub_eq_vsub_rev p2 p3, norm_neg] /-- An angle in a right-angled triangle expressed using `arccos`. -/ lemma angle_eq_arccos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : ∠ p₂ p₃ p₁ = real.arccos (dist p₃ p₂ / dist p₁ p₃) := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arccos_of_inner_eq_zero h] end /-- An angle in a right-angled triangle expressed using `arcsin`. -/ lemma angle_eq_arcsin_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = real.arcsin (dist p₁ p₂ / dist p₁ p₃) := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [←@vsub_ne_zero V, @ne_comm _ p₃, ←@vsub_ne_zero V _ _ _ p₂, or_comm] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arcsin_of_inner_eq_zero h h0] end /-- An angle in a right-angled triangle expressed using `arctan`. -/ lemma angle_eq_arctan_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = real.arctan (dist p₁ p₂ / dist p₃ p₂) := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [ne_comm, ←@vsub_ne_zero V] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arctan_of_inner_eq_zero h h0] end /-- An angle in a non-degenerate right-angled triangle is positive. -/ lemma angle_pos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : 0 < ∠ p₂ p₃ p₁ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [←@vsub_ne_zero V, eq_comm, ←@vsub_eq_zero_iff_eq V, or_comm] at h0, rw [angle, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm], exact angle_add_pos_of_inner_eq_zero h h0 end /-- An angle in a right-angled triangle is at most `π / 2`. -/ lemma angle_le_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : ∠ p₂ p₃ p₁ ≤ π / 2 := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm], exact angle_add_le_pi_div_two_of_inner_eq_zero h end /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/ lemma angle_lt_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ < π / 2 := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [ne_comm, ←@vsub_ne_zero V] at h0, rw [angle, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm], exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0 end /-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/ lemma cos_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : real.cos (∠ p₂ p₃ p₁) = dist p₃ p₂ / dist p₁ p₃ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, cos_angle_add_of_inner_eq_zero h] end /-- The sine of an angle in a right-angled triangle as a ratio of sides. -/ lemma sin_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : real.sin (∠ p₂ p₃ p₁) = dist p₁ p₂ / dist p₁ p₃ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [←@vsub_ne_zero V, @ne_comm _ p₃, ←@vsub_ne_zero V _ _ _ p₂, or_comm] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, sin_angle_add_of_inner_eq_zero h h0] end /-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/ lemma tan_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : real.tan (∠ p₂ p₃ p₁) = dist p₁ p₂ / dist p₃ p₂ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, tan_angle_add_of_inner_eq_zero h] end /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side. -/ lemma cos_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : real.cos (∠ p₂ p₃ p₁) * dist p₁ p₃ = dist p₃ p₂ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, cos_angle_add_mul_norm_of_inner_eq_zero h] end /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side. -/ lemma sin_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : real.sin (∠ p₂ p₃ p₁) * dist p₁ p₃ = dist p₁ p₂ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, sin_angle_add_mul_norm_of_inner_eq_zero h] end /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side. -/ lemma tan_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ = p₂ ∨ p₃ ≠ p₂) : real.tan (∠ p₂ p₃ p₁) * dist p₃ p₂ = dist p₁ p₂ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [ne_comm, ←@vsub_ne_zero V, ←@vsub_eq_zero_iff_eq V, or_comm] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, tan_angle_add_mul_norm_of_inner_eq_zero h h0] end /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse. -/ lemma dist_div_cos_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ = p₂ ∨ p₃ ≠ p₂) : dist p₃ p₂ / real.cos (∠ p₂ p₃ p₁) = dist p₁ p₃ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [ne_comm, ←@vsub_ne_zero V, ←@vsub_eq_zero_iff_eq V, or_comm] at h0, rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_cos_angle_add_of_inner_eq_zero h h0] end /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse. -/ lemma dist_div_sin_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : dist p₁ p₂ / real.sin (∠ p₂ p₃ p₁) = dist p₁ p₃ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [eq_comm, ←@vsub_ne_zero V, ←@vsub_eq_zero_iff_eq V, or_comm] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_sin_angle_add_of_inner_eq_zero h h0] end /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side. -/ lemma dist_div_tan_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : dist p₁ p₂ / real.tan (∠ p₂ p₃ p₁) = dist p₃ p₂ := begin rw [angle, ←inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ←neg_eq_zero, ←inner_neg_left, neg_vsub_eq_vsub_rev] at h, rw [eq_comm, ←@vsub_ne_zero V, ←@vsub_eq_zero_iff_eq V, or_comm] at h0, rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ←vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_tan_angle_add_of_inner_eq_zero h h0] end end euclidean_geometry
882f3420af844576da6e494d64fa7d56f5b47bc4
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/matrix/block.lean
459bb5a21b7f7f2e96b6e0a30af0d015ef5d805e
[ "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
9,843
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.matrix.determinant import tactic.fin_cases /-! # Block matrices and their determinant This file defines a predicate `matrix.block_triangular_matrix` saying a matrix is block triangular, and proves the value of the determinant for various matrices built out of blocks. ## Main definitions * `matrix.block_triangular_matrix` expresses that a `o` by `o` matrix is block triangular, if the rows and columns are ordered according to some order `b : o → ℕ` ## Main results * `det_of_block_triangular_matrix`: the determinant of a block triangular matrix is equal to the product of the determinants of all the blocks * `det_of_upper_triangular` and `det_of_lower_triangular`: the determinant of a triangular matrix is the product of the entries along the diagonal ## Tags matrix, diagonal, det, block triangular -/ open_locale big_operators universes v variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] namespace matrix lemma det_to_block (M : matrix m m R) (p : m → Prop) [decidable_pred p] : M.det = (matrix.from_blocks (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) p) (to_block M (λ j, ¬p j) (λ j, ¬p j))).det := begin rw ← matrix.det_reindex_self (equiv.sum_compl p).symm M, rw [det_apply', det_apply'], congr, ext σ, congr, ext, generalize hy : σ x = y, cases x; cases y; simp only [matrix.reindex_apply, to_block_apply, equiv.symm_symm, equiv.sum_compl_apply_inr, equiv.sum_compl_apply_inl, from_blocks_apply₁₁, from_blocks_apply₁₂, from_blocks_apply₂₁, from_blocks_apply₂₂, matrix.minor_apply], end lemma det_to_square_block (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma det_to_square_block' (M : matrix m m R) (b : m → ℕ) (k : ℕ) : (to_square_block' M b k).det = (to_square_block_prop M (λ i, b i = k)).det := by simp lemma two_block_triangular_det (M : matrix m m R) (p : m → Prop) [decidable_pred p] (h : ∀ i (h1 : ¬p i) j (h2 : p j), M i j = 0) : M.det = (to_square_block_prop M p).det * (to_square_block_prop M (λ i, ¬p i)).det := begin rw det_to_block M p, convert det_from_blocks_zero₂₁ (to_block M p p) (to_block M p (λ j, ¬p j)) (to_block M (λ j, ¬p j) (λ j, ¬p j)), ext, exact h ↑i i.2 ↑j j.2 end lemma equiv_block_det (M : matrix m m R) {p q : m → Prop} [decidable_pred p] [decidable_pred q] (e : ∀x, q x ↔ p x) : (to_square_block_prop M p).det = (to_square_block_prop M q).det := by convert matrix.det_reindex_self (equiv.subtype_equiv_right e) (to_square_block_prop M q) lemma to_square_block_det'' (M : matrix m m R) {n : nat} (b : m → fin n) (k : fin n) : (to_square_block M b k).det = (to_square_block' M (λ i, ↑(b i)) ↑k).det := begin rw [to_square_block_def', to_square_block_def], apply equiv_block_det, intro x, apply (fin.ext_iff _ _).symm end /-- Let `b` map rows and columns of a square matrix `M` to `n` blocks. Then `block_triangular_matrix' M n b` says the matrix is block triangular. -/ def block_triangular_matrix' {o : Type*} (M : matrix o o R) {n : ℕ} (b : o → fin n) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular' {m n : Type*} (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix' (from_blocks A B 0 D) (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) := begin intros k1 k2 hk12, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, (0 : fin 2)) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, set mk1 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k1 with hmk1, set mk2 := (sum.elim (λ i, (0 : fin 2)) (λ j, 1)) k2 with hmk2, fin_cases mk1 using h; fin_cases mk2 using h_1; rw [h, h_1] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (by norm_num) }, { rw hmk1 at h, obtain ⟨i, hi⟩ := h1 k1 h, rw hmk2 at h_1, obtain ⟨j, hj⟩ := h0 k2 h_1, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end /-- Let `b` map rows and columns of a square matrix `M` to blocks indexed by `ℕ`s. Then `block_triangular_matrix M n b` says the matrix is block triangular. -/ def block_triangular_matrix {o : Type*} (M : matrix o o R) (b : o → ℕ) : Prop := ∀ i j, b j < b i → M i j = 0 lemma upper_two_block_triangular {m n : Type*} (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : block_triangular_matrix (from_blocks A B 0 D) (sum.elim (λ i, 0) (λ j, 1)) := begin intros k1 k2 hk12, have h01 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 ∨ sum.elim (λ i, 0) (λ j, 1) k = 1, { simp }, have h0 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 0 → ∃ i, k = sum.inl i, { simp }, have h1 : ∀ (k : m ⊕ n), sum.elim (λ i, 0) (λ j, 1) k = 1 → ∃ j, k = sum.inr j, { simp }, cases (h01 k1) with hk1 hk1; cases (h01 k2) with hk2 hk2; rw [hk1, hk2] at hk12, { exact absurd hk12 (nat.not_lt_zero 0) }, { exact absurd hk12 (nat.not_lt_zero 1) }, { obtain ⟨i, hi⟩ := h1 k1 hk1, obtain ⟨j, hj⟩ := h0 k2 hk2, rw [hi, hj], simp }, { exact absurd hk12 (irrefl 1) } end lemma det_of_block_triangular_matrix (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : ∀ (n : ℕ) (hn : ∀ i, b i < n), M.det = ∏ k in finset.range n, (to_square_block' M b k).det := begin intros n hn, unfreezingI { induction n with n hi generalizing m M b }, { rw finset.prod_range_zero, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, exact ⟨λ i, nat.not_lt_zero (b i) (hn i)⟩ }, { rw [finset.prod_range_succ_comm], have h2 : (M.to_square_block_prop (λ (i : m), b i = n.succ)).det = (M.to_square_block' b n.succ).det, { dunfold to_square_block', dunfold to_square_block_prop, refl }, rw two_block_triangular_det M (λ i, ¬(b i = n)), { rw mul_comm, apply congr (congr_arg has_mul.mul _), { let m' := {a // ¬b a = n }, let b' := (λ (i : m'), b ↑i), have h' : block_triangular_matrix (M.to_square_block_prop (λ (i : m), ¬b i = n)) b', { intros i j, apply h ↑i ↑j }, have hni : ∀ (i : {a // ¬b a = n}), b' i < n, { exact λ i, (ne.le_iff_lt i.property).mp (nat.lt_succ_iff.mp (hn ↑i)) }, have h1 := hi (M.to_square_block_prop (λ (i : m), ¬b i = n)) b' h' hni, rw ←fin.prod_univ_eq_prod_range at h1 ⊢, convert h1, ext k, simp only [to_square_block_def', to_square_block_def], let he : {a // b' a = ↑k} ≃ {a // b a = ↑k}, { have hc : ∀ (i : m), (λ a, b a = ↑k) i → (λ a, ¬b a = n) i, { intros i hbi, rw hbi, exact ne_of_lt (fin.is_lt k) }, exact equiv.subtype_subtype_equiv_subtype hc }, exact matrix.det_reindex_self he (λ (i j : {a // b' a = ↑k}), M ↑i ↑j) }, { rw det_to_square_block' M b n, have hh : ∀ a, b a = n ↔ ¬(λ (i : m), ¬b i = n) a, { intro i, simp only [not_not] }, exact equiv_block_det M hh }}, { intros i hi j hj, apply (h i), simp only [not_not] at hi, rw hi, exact (ne.le_iff_lt hj).mp (nat.lt_succ_iff.mp (hn j)) }} end lemma det_of_block_triangular_matrix'' (M : matrix m m R) (b : m → ℕ) (h : block_triangular_matrix M b) : M.det = ∏ k in finset.image b finset.univ, (to_square_block' M b k).det := begin let n : ℕ := (Sup (finset.image b finset.univ : set ℕ)).succ, have hn : ∀ i, b i < n, { have hbi : ∀ i, b i ∈ finset.image b finset.univ, { simp }, intro i, dsimp only [n], apply nat.lt_succ_iff.mpr, exact le_cSup (finset.bdd_above _) (hbi i) }, rw det_of_block_triangular_matrix M b h n hn, refine (finset.prod_subset _ _).symm, { intros a ha, apply finset.mem_range.mpr, obtain ⟨i, ⟨hi, hbi⟩⟩ := finset.mem_image.mp ha, rw ←hbi, exact hn i }, { intros k hk hbk, apply det_eq_one_of_card_eq_zero, apply fintype.card_eq_zero_iff.mpr, constructor, simp only [subtype.forall], intros a hba, apply hbk, apply finset.mem_image.mpr, use a, exact ⟨finset.mem_univ a, hba⟩ } end lemma det_of_block_triangular_matrix' (M : matrix m m R) {n : ℕ} (b : m → fin n) (h : block_triangular_matrix' M b) : M.det = ∏ (k : fin n), (to_square_block M b k).det := begin let b2 : m → ℕ := λ i, ↑(b i), simp_rw to_square_block_det'', rw fin.prod_univ_eq_prod_range (λ (k : ℕ), (M.to_square_block' b2 k).det) n, apply det_of_block_triangular_matrix, { intros i j hij, exact h i j (fin.coe_fin_lt.mp hij) }, { intro i, exact fin.is_lt (b i) } end lemma det_of_upper_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), j < i → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin convert det_of_block_triangular_matrix' M id h, ext i, have h2 : ∀ (j : {a // id a = i}), j = ⟨i, rfl⟩ := λ (j : {a // id a = i}), subtype.ext j.property, haveI : unique {a // id a = i} := ⟨⟨⟨i, rfl⟩⟩, h2⟩, simp [h2 default] end lemma det_of_lower_triangular {n : ℕ} (M : matrix (fin n) (fin n) R) (h : ∀ (i j : fin n), i < j → M i j = 0) : M.det = ∏ i : (fin n), M i i := begin rw ← det_transpose, exact det_of_upper_triangular _ (λ (i j : fin n) (hji : j < i), h j i hji) end end matrix
33af4f0ef1784c248937d762e13eeeb2fd4b04da
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/SizeOf.lean
9c59cf6c17b538c34fd978cd492d1604fc6da986
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
4,054
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ prelude import Init.Tactics set_option linter.missingDocs true -- keep it documented /-! # SizeOf -/ /-- `SizeOf` is a typeclass automatically derived for every inductive type, which equips the type with a "size" function to `Nat`. The default instance defines each constructor to be `1` plus the sum of the sizes of all the constructor fields. This is used for proofs by well-founded induction, since every field of the constructor has a smaller size than the constructor itself, and in many cases this will suffice to do the proof that a recursive function is only called on smaller values. If the default proof strategy fails, it is recommended to supply a custom size measure using the `termination_by` argument on the function definition. -/ class SizeOf (α : Sort u) where /-- The "size" of an element, a natural number which decreases on fields of each inductive type. -/ sizeOf : α → Nat export SizeOf (sizeOf) /-! Declare `SizeOf` instances and theorems for types declared before `SizeOf`. From now on, the inductive compiler will automatically generate `SizeOf` instances and theorems. -/ /-- Every type `α` has a default `SizeOf` instance that just returns `0` for every element of `α`. -/ protected def default.sizeOf (α : Sort u) : α → Nat | _ => 0 instance (priority := low) (α : Sort u) : SizeOf α where sizeOf := default.sizeOf α @[simp] theorem sizeOf_default (n : α) : sizeOf n = 0 := rfl instance : SizeOf Nat where sizeOf n := n @[simp] theorem sizeOf_nat (n : Nat) : sizeOf n = n := rfl instance [SizeOf α] : SizeOf (Unit → α) where sizeOf f := sizeOf (f ()) @[simp] theorem sizeOf_thunk [SizeOf α] (f : Unit → α) : sizeOf f = sizeOf (f ()) := rfl deriving instance SizeOf for PUnit deriving instance SizeOf for Prod deriving instance SizeOf for PProd deriving instance SizeOf for MProd deriving instance SizeOf for Bool deriving instance SizeOf for Subtype deriving instance SizeOf for PLift deriving instance SizeOf for ULift deriving instance SizeOf for Decidable deriving instance SizeOf for Fin deriving instance SizeOf for UInt8 deriving instance SizeOf for UInt16 deriving instance SizeOf for UInt32 deriving instance SizeOf for UInt64 deriving instance SizeOf for USize deriving instance SizeOf for Char deriving instance SizeOf for Option deriving instance SizeOf for List deriving instance SizeOf for String deriving instance SizeOf for String.Pos deriving instance SizeOf for Substring deriving instance SizeOf for Array deriving instance SizeOf for Except deriving instance SizeOf for EStateM.Result @[simp] theorem Unit.sizeOf (u : Unit) : sizeOf u = 1 := rfl @[simp] theorem Bool.sizeOf_eq_one (b : Bool) : sizeOf b = 1 := by cases b <;> rfl namespace Lean /-- We manually define the `Lean.Name` instance because we use an opaque function for computing the hashcode field. -/ protected noncomputable def Name.sizeOf : Name → Nat | anonymous => 1 | str p s => 1 + Name.sizeOf p + sizeOf s | num p n => 1 + Name.sizeOf p + sizeOf n noncomputable instance : SizeOf Name where sizeOf n := n.sizeOf @[simp] theorem Name.anonymous.sizeOf_spec : sizeOf anonymous = 1 := rfl @[simp] theorem Name.str.sizeOf_spec (p : Name) (s : String) : sizeOf (str p s) = 1 + sizeOf p + sizeOf s := rfl @[simp] theorem Name.num.sizeOf_spec (p : Name) (n : Nat) : sizeOf (num p n) = 1 + sizeOf p + sizeOf n := rfl deriving instance SizeOf for SourceInfo deriving instance SizeOf for Syntax deriving instance SizeOf for TSyntax deriving instance SizeOf for Syntax.SepArray deriving instance SizeOf for Syntax.TSepArray deriving instance SizeOf for ParserDescr deriving instance SizeOf for MacroScopesView deriving instance SizeOf for Macro.Context deriving instance SizeOf for Macro.Exception deriving instance SizeOf for Macro.State deriving instance SizeOf for Macro.Methods end Lean
2b43c201e54b78e9085e77cadf1049069241dd4e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/t2.lean
a47f1120de1a9c096ed49a0ebe6d7119267a57b0
[ "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
182
lean
universe l universe u print raw Type print raw Type.{1} print raw Type.{2} print raw Type.{l+1} print raw Type.{max l u 1} print raw Type.{imax l+1 u 1} print raw Type.{imax l+1 l u}
2e94a5b5dcfb877eee6d508aee087702bcf1b64c
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/algebra/ordered_field.lean
db19149f287b8afd07c049944e1a83fa9d756a49
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
16,788
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura -/ prelude import init.algebra.ordered_ring .field set_option old_structure_cmd true universe u class linear_ordered_field (α : Type u) extends linear_ordered_ring α, field α section linear_ordered_field variables {α : Type u} [linear_ordered_field α] lemma mul_zero_lt_mul_inv_of_pos {a : α} (h : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt h))) ... = a * (1 / a) : by rw inv_eq_one_div lemma mul_zero_lt_mul_inv_of_neg {a : α} (h : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt h)) ... = a * (1 / a) : by rw inv_eq_one_div lemma one_div_pos_of_pos {a : α} (h : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos h) (le_of_lt h) lemma pos_of_one_div_pos {a : α} (h : 0 < 1 / a) : 0 < a := one_div_one_div a ▸ one_div_pos_of_pos h lemma one_div_neg_of_neg {a : α} (h : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg h) (le_of_lt h) lemma neg_of_one_div_neg {a : α} (h : 1 / a < 0) : a < 0 := one_div_one_div a ▸ one_div_neg_of_neg h lemma le_mul_of_ge_one_right {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_ge_one_left {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b := by rw mul_comm; exact le_mul_of_ge_one_right hb h lemma lt_mul_of_gt_one_right {a b : α} (hb : b > 0) (h : a > 1) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, mul_lt_mul_of_pos_left h hb lemma one_le_div_of_le (a : α) {b : α} (hb : b > 0) (h : b ≤ a) : 1 ≤ a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt hbinv) ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma le_of_one_le_div (a : α) {b : α} (hb : b > 0) (h : 1 ≤ a / b) : b ≤ a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt hb) h ... = a : by rw [mul_div_cancel' _ hb'] lemma one_lt_div_of_lt (a : α) {b : α} (hb : b > 0) (h : b < a) : 1 < a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... < a * (1 / b) : mul_lt_mul_of_pos_right h hbinv ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma lt_of_one_lt_div (a : α) {b : α} (hb : b > 0) (h : 1 < a / b) : b < a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b < b * (a / b) : lt_mul_of_gt_one_right hb h ... = a : by rw [mul_div_cancel' _ hb'] -- the following lemmas amount to four iffs, for <, ≤, ≥, >. lemma mul_le_of_le_div {a b c : α} (hc : 0 < c) (h : a ≤ b / c) : a * c ≤ b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_le_mul_of_nonneg_right h (le_of_lt hc) lemma le_div_of_mul_le {a b c : α} (hc : 0 < c) (h : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_lt_div {a b c : α} (hc : 0 < c) (h : a < b / c) : a * c < b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_lt_mul_of_pos_right h hc lemma lt_div_of_mul_lt {a b c : α} (hc : 0 < c) (h : a * c < b) : a < b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_le_of_div_le_of_neg {a b c : α} (hc : c < 0) (h : b / c ≤ a) : a * c ≤ b := div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h (le_of_lt hc) lemma div_le_of_mul_le_of_neg {a b c : α} (hc : c < 0) (h : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_gt_div_of_neg {a b c : α} (hc : c < 0) (h : a > b / c) : a * c < b := div_mul_cancel b (ne_of_lt hc) ▸ mul_lt_mul_of_neg_right h hc lemma div_lt_of_mul_lt_of_pos {a b c : α} (hc : c > 0) (h : b < a * c) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_gt hc) ... > b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_lt_of_mul_gt_of_neg {a b c : α} (hc : c < 0) (h : a * c < b) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_le_of_le_mul {a b c : α} (hb : b > 0) (h : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hb)) ... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b ... = c : by rw [mul_div_cancel_left _ (ne.symm (ne_of_lt hb))] lemma le_mul_of_div_le {a b c : α} (hc : c > 0) (h : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : by rw (div_mul_cancel _ (ne.symm (ne_of_lt hc))) ... ≤ b * c : mul_le_mul_of_nonneg_right h (le_of_lt hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now lemma mul_sub_mul_div_mul_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have h1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right h _ ... = 0 : by rw sub_self, calc 0 > a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma mul_sub_mul_div_mul_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have h1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right h _ ... = 0 : by rw sub_self, calc 0 ≥ a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma div_lt_div_of_mul_sub_mul_div_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) < 0) : a / c < b / d := have (a * d - c * b) / (c * d) < 0, by rwa [mul_comm c b], have a / c - b / d < 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d < 0 + b / d, from add_lt_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_le_div_of_mul_sub_mul_div_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := have (a * d - c * b) / (c * d) ≤ 0, by rwa [mul_comm c b], have a / c - b / d ≤ 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_pos_of_pos_of_pos {a b : α} : 0 < a → 0 < b → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonneg_of_nonneg_of_pos {a b : α} : 0 ≤ a → 0 < b → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_neg_of_pos {a b : α} : a < 0 → 0 < b → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonpos_of_nonpos_of_pos {a b : α} : a ≤ 0 → 0 < b → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_pos_of_neg {a b : α} : 0 < a → b < 0 → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonpos_of_nonneg_of_neg {a b : α} : 0 ≤ a → b < 0 → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_pos_of_neg_of_neg {a b : α} : a < 0 → b < 0 → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonneg_of_nonpos_of_neg {a b : α} : a ≤ 0 → b < 0 → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_lt_div_of_lt_of_pos {a b c : α} (h : a < b) (hc : 0 < c) : a / c < b / c := begin intros, rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) end lemma div_le_div_of_le_of_pos {a b c : α} (h : a ≤ b) (hc : 0 < c) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) end lemma div_lt_div_of_lt_of_neg {a b c : α} (h : b < a) (hc : c < 0) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) end lemma div_le_div_of_le_of_neg {a b c : α} (h : b ≤ a) (hc : c < 0) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) end lemma add_halves (a : α) : a / 2 + a / 2 = a := by { rw [div_add_div_same, ← two_mul, mul_div_cancel_left], exact two_ne_zero } lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma add_midpoint {a b : α} (h : a < b) : a + (b - a) / 2 < b := begin rw [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg], apply add_lt_of_lt_sub_right, rw [sub_self_div_two, sub_self_div_two], apply div_lt_div_of_lt_of_pos h two_pos end lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := eq.symm (iff.mpr (eq_div_iff_mul_eq _ _ (ne_of_gt (add_pos (@zero_lt_one α _) zero_lt_one))) (begin unfold bit0, rw [left_distrib, mul_one] end)) lemma mul_le_mul_of_mul_div_le {a b c d : α} (h : a * (b / c) ≤ d) (hc : c > 0) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rw [mul_comm b], apply le_mul_of_div_le hc h end lemma div_two_lt_of_pos {a : α} (h : a > 0) : a / 2 < a := suffices a / (1 + 1) < a, begin unfold bit0, assumption end, have ha : a / 2 > 0, from div_pos_of_pos_of_pos h (add_pos zero_lt_one zero_lt_one), calc a / 2 < a / 2 + a / 2 : lt_add_of_pos_left _ ha ... = a : add_halves a lemma div_mul_le_div_mul_of_div_le_div_pos {a b c d e : α} (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin have h₁ := div_mul_eq_div_mul_one_div a b e, have h₂ := div_mul_eq_div_mul_one_div c d e, rw [h₁, h₂], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end lemma exists_add_lt_and_pos_of_lt {a b : α} (h : b < a) : ∃ c : α, b + c < a ∧ c > 0 := begin apply exists.intro ((a - b) / (1 + 1)), split, {have h2 : a + a > (b + b) + (a - b), calc a + a > b + a : add_lt_add_right h _ ... = b + a + b - b : by rw add_sub_cancel ... = b + b + a - b : by simp [add_comm, add_left_comm] ... = (b + b) + (a - b) : by rw add_sub, have h3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, exact div_lt_div_of_lt_of_pos h2 two_pos, rw [one_add_one_eq_two, sub_eq_add_neg], rw [add_self_div_two, ← div_add_div_same, add_self_div_two, sub_eq_add_neg] at h3, exact h3}, exact div_pos_of_pos_of_pos (sub_pos_of_lt h) two_pos end lemma ge_of_forall_ge_sub {a b : α} (h : ∀ ε : α, ε > 0 → a ≥ b - ε) : a ≥ b := begin apply le_of_not_gt, intro hb, cases exists_add_lt_and_pos_of_lt hb with c hc, have hc' := h c (and.right hc), apply (not_le_of_gt (and.left hc)) (le_add_of_sub_right_le hc') end lemma one_div_lt_one_div_of_lt {a b : α} (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := begin apply lt_div_of_mul_lt ha, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_lt_of_pos (lt_trans ha h), rwa [one_mul] end lemma one_div_le_one_div_of_le {a b : α} (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt ha h) (λ h, by rw [h]) lemma one_div_lt_one_div_of_lt_of_neg {a b : α} (hb : b < 0) (h : a < b) : 1 / b < 1 / a := begin apply div_lt_of_mul_gt_of_neg hb, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_gt_of_neg (lt_trans h hb), rwa [one_mul] end lemma one_div_le_one_div_of_le_of_neg {a b : α} (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt_of_neg hb h) (λ h, by rw [h]) lemma le_of_one_div_le_one_div {a b : α} (h : 0 < a) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt h hn lemma le_of_one_div_le_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt_of_neg h hn lemma lt_of_one_div_lt_one_div {a b : α} (h : 0 < a) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le h hn lemma lt_of_one_div_lt_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le_of_neg h hn lemma one_div_le_of_one_div_le_of_pos {a b : α} (ha : a > 0) (h : 1 / a ≤ b) : 1 / b ≤ a := begin rw [← one_div_one_div a], apply one_div_le_one_div_of_le _ h, apply one_div_pos_of_pos ha end lemma one_div_le_of_one_div_le_of_neg {a b : α} (hb : b < 0) (h : 1 / a ≤ b) : 1 / b ≤ a := le_of_not_gt $ λ hl, begin have : a < 0, from lt_trans hl (one_div_neg_of_neg hb), rw ← one_div_one_div a at hl, exact not_lt_of_ge h (lt_of_one_div_lt_one_div_of_neg hb hl) end lemma one_lt_one_div {a : α} (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := suffices 1 / 1 < 1 / a, by rwa one_div_one at this, one_div_lt_one_div_of_lt h1 h2 lemma one_le_one_div {a : α} (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := suffices 1 / 1 ≤ 1 / a, by rwa one_div_one at this, one_div_le_one_div_of_le h1 h2 lemma one_div_lt_neg_one {a : α} (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_lt_of_neg h1 h2 lemma one_div_le_neg_one {a : α} (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_le_of_neg h1 h2 lemma div_lt_div_of_pos_of_lt_of_pos {a b c : α} (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := begin apply lt_of_sub_neg, rw [div_eq_mul_one_div, div_eq_mul_one_div c b, ← mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact hc, apply sub_neg_of_lt, apply one_div_lt_one_div_of_lt; assumption, end lemma div_mul_le_div_mul_of_div_le_div_pos' {a b c d e : α} (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end end linear_ordered_field class discrete_linear_ordered_field (α : Type u) extends linear_ordered_field α, decidable_linear_ordered_comm_ring α
13b4348dc40725f6fdf54195cb7a29effd2ee396
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/monoid_algebra/basic.lean
d89dc1f18778f850426aeef764b1b1faf5cbfa1c
[ "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
57,263
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, Yury G. Kudryashov, Scott Morrison -/ import algebra.big_operators.finsupp import linear_algebra.finsupp import algebra.non_unital_alg_hom /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any conditions at all. In this case the construction yields a not-necessarily-unital, not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such algebras to magmas, and we prove this as `monoid_algebra.lift_magma`. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) /-! ### Multiplicative monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k instance : has_coe_to_fun (monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace monoid_algebra variables {k G} section has_mul variables [semiring k] [has_mul G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], .. finsupp.add_comm_monoid } end has_mul section semigroup variables [semiring k] [semigroup G] instance : non_unital_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. monoid_algebra.non_unital_non_assoc_semiring} end semigroup section has_one variables [semiring k] [has_one G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl end has_one section mul_one_class variables [semiring k] [mul_one_class G] instance : non_assoc_semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], ..monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : G →* R`, returns the additive homomorphism from `monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : G →* R) : monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g a := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : G →* R) : lift_nc (f : k →+ R) g 1 = 1 := by simp [one_def] lemma lift_nc_mul (f : k →+* R) (g : G →* R) (a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := begin conv_rhs { rw [← sum_single a, ← sum_single b] }, simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul, finsupp.mul_sum], refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)), simp [mul_assoc, (h_comm hy).left_comm] end end mul_one_class /-! #### Semiring structure -/ section semiring variables [semiring k] [monoid G] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. monoid_algebra.non_unital_semiring, .. monoid_algebra.non_assoc_semiring } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (monoid_algebra k G) := finsupp.add_group instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (monoid_algebra k G) := finsupp.has_scalar instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (monoid_algebra k G) := finsupp.distrib_mul_action G k instance [semiring R] [semiring k] [module R k] : module R (monoid_algebra k G) := finsupp.module G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (monoid_algebra k G) := finsupp.has_faithful_scalar instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (monoid_algebra k G) := finsupp.smul_comm_class G k instance comap_distrib_mul_action_self [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self end derived_instances section misc_theorems variables [semiring k] local attribute [reducible] monoid_algebra lemma mul_apply [has_mul G] (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end lemma support_mul [has_mul G] (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset @[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow [monoid G] {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := by { simp only [pow_zero], refl } | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂] {x y : monoid_algebra β α} (f : mul_hom α α₂) : (map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) = (map_domain f x * map_domain f y : monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_mul], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end variables (k G) /-- The embedding of a magma into its magma algebra. -/ @[simps] def of_magma [has_mul G] : mul_hom G (monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- The embedding of a unital magma into its magma algebra. -/ @[simps] def of [mul_one_class G] : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } end lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma support_mul_single [right_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r).support = f.support.map (mul_right_embedding x) := begin ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_right_embedding_apply], by_cases H : ∃ a, a * x = y, { rcases H with ⟨a, rfl⟩, rw [mul_single_apply_aux f (λ _, mul_left_inj x)], simp [hr] }, { push_neg at H, simp [mul_apply, H] } end lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr' with g s, split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := begin suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) = (add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g), from add_monoid_hom.congr_fun this φ, ext a b, simp [mul_assoc] end end misc_theorems /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [semiring R] [semiring k] [distrib_mul_action R k] [has_mul G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul, if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply, smul_zero], end⟩ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index', implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply, mul_zero, smul_zero], end⟩ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) := ⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := non_unital_alg_hom.to_distrib_mul_action_hom_injective $ finsupp.distrib_mul_action_hom_ext' $ λ a, distrib_mul_action_hom.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := non_unital_alg_hom_ext k $ mul_hom.congr_fun h /-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom G A ≃ non_unital_alg_hom k (monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, a.sum (λ m t, t • f m), map_smul' := λ t' a, begin rw [finsupp.smul_sum, sum_smul_index'], { simp_rw smul_assoc, }, { intros m, exact zero_smul k (f m), }, end, map_mul' := λ a₁ a₂, begin let g : G → k → A := λ m t, t • f m, have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), }, have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, }, simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def, sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)], end, .. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) }, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra local attribute [reducible] monoid_algebra lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- `finsupp.single 1` as a `ring_hom` -/ @[simps] def single_one_ring_hom [semiring k] [monoid G] : k →+* monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul], ..finsupp.single_add_hom 1} /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b, by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom, g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of] /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom) (h_of : (f : monoid_algebra k G →* R).comp (of k G) = (g : monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..single_one_ring_hom.comp (algebra_map k A) } /-- `finsupp.single 1` as a `alg_hom` -/ @[simps] def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : A →ₐ[k] monoid_algebra A G := { commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom} @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = algebra_map k (monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a := by simp lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G) (hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G 1) (hM 1) }, { convert hsmul r (of k G g) (hM g), simp only [mul_one, smul_single', of_apply] }, end end algebra section lift variables {k G} [comm_semiring k] [monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : monoid_algebra k G →* A).comp (of k G) = (φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] }, right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } } variables {k G A} lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } end lift section local attribute [reducible] monoid_algebra variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : V →ₗ[k] V := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, smul_algebra_smul_comm _ _ _ } @[simp] lemma group_smul.linear_map_apply [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [monoid G] [comm_semiring k] {V W : Type u₃} [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : V →ₗ[k] W) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, dsimp at *, simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul], erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r, f.map_smul, h g v, of_apply], all_goals { apply_instance } } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end section universe ui variable {ι : Type ui} local attribute [reducible] monoid_algebra lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] end section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] local attribute [reducible] monoid_algebra @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end section span variables [semiring k] [mul_one_class G] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_span_support (f : monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span section opposite open finsupp opposite variables [semiring k] /-- The opposite of an `monoid_algebra R I` equivalent as a ring to the `monoid_algebra Rᵒᵖ Iᵒᵖ` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] : (monoid_algebra k G)ᵒᵖ ≃+* monoid_algebra kᵒᵖ Gᵒᵖ := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i₁ r₁ i₂ r₂ : 6, simp end, ..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵒᵖ)).trans $ finsupp.dom_congr equiv_to_opposite } @[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) : monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵒᵖ) (x : Gᵒᵖ) : monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) := by simp end opposite end monoid_algebra /-! ### Additive monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k instance : has_coe_to_fun (add_monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace add_monoid_algebra variables {k G} section has_mul variables [semiring k] [has_add G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], nsmul := λ n f, n • f, nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] }, nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] }, .. finsupp.add_comm_monoid } end has_mul section has_one variables [semiring k] [has_zero G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl end has_one section semigroup variables [semiring k] [add_semigroup G] instance : non_unital_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. add_monoid_algebra.non_unital_non_assoc_semiring } end semigroup section mul_one_class variables [semiring k] [add_zero_class G] instance : non_assoc_semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], .. add_monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : multiplicative G →* R`, returns the additive homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `add_monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : multiplicative G →* R) : add_monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g (multiplicative.of_add a) := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : multiplicative G →* R) : lift_nc (f : k →+ R) g 1 = 1 := @monoid_algebra.lift_nc_one k (multiplicative G) _ _ _ _ f g lemma lift_nc_mul (f : k →+* R) (g : multiplicative G →* R) (a b : add_monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := @monoid_algebra.lift_nc_mul k (multiplicative G) _ _ _ _ f g a b @h_comm end mul_one_class /-! #### Semiring structure -/ section semiring instance {R : Type*} [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (add_monoid_algebra k G) := finsupp.has_scalar variables [semiring k] [add_monoid G] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. add_monoid_algebra.non_unital_semiring, .. add_monoid_algebra.non_assoc_semiring, } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _, .. add_monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (add_monoid_algebra k G) := finsupp.add_group instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, sub := has_sub.sub, sub_eq_add_neg := finsupp.add_group.sub_eq_add_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (add_monoid_algebra k G) := finsupp.distrib_mul_action G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (add_monoid_algebra k G) := finsupp.has_faithful_scalar instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) := finsupp.module G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (add_monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (add_monoid_algebra k G) := finsupp.smul_comm_class G k /-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)` because we've never discussed actions of additive groups. -/ end derived_instances section misc_theorems variables [semiring k] lemma mul_apply [has_add G] (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := @monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := @monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs lemma support_mul [has_add G] (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) := @monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _ -- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this. -- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type, -- instead of relying on `finsupp.single`. lemma single_pow [add_monoid G] {a : G} {b : k} : ∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n) | 0 := by { simp only [pow_zero, zero_nsmul], refl } | (n+1) := by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul] /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂] {x y : add_monoid_algebra β α} (f : add_hom α α₂) : (map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (map_domain f x * map_domain f y : add_monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_add], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end section variables (k G) /-- The embedding of an additive magma into its additive magma algebra. -/ @[simps] def of_magma [has_add G] : mul_hom (multiplicative G) (add_monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- Embedding of a magma with zero into its magma algebra. -/ def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } /-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/ def of' : G → add_monoid_algebra k G := λ a, single a 1 end @[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 := rfl @[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := @monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f : add_monoid_algebra k G) y = r * f z := @monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f : add_monoid_algebra k G) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] lemma mul_single_apply [add_group G] (f : add_monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y - x) * r := (sub_eq_add_neg y x).symm ▸ @monoid_algebra.mul_single_apply k (multiplicative G) _ _ _ _ _ _ lemma single_mul_apply [add_group G] (r : k) (x : G) (f : add_monoid_algebra k G) (y : G) : (single x r * f : add_monoid_algebra k G) y = r * f (- x + y) := @monoid_algebra.single_mul_apply k (multiplicative G) _ _ _ _ _ _ lemma support_mul_single [add_right_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r : add_monoid_algebra k G).support = f.support.map (add_right_embedding x) := @monoid_algebra.support_mul_single k (multiplicative G) _ _ _ _ hr _ lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := @monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ variables {k G} lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G) (hM : ∀ g, p (of k G (multiplicative.of_add g))) (hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) }, { convert hsmul r (of k G (multiplicative.of_add g)) (hM g), simp only [mul_one, to_add_of_add, smul_single', of_apply] }, end end misc_theorems section span variables [semiring k] /-- An element of `add_monoid_algebra R M` is in the submodule generated by its support. -/ lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support, using unbundled inclusion. -/ lemma mem_span_support' (f : add_monoid_algebra k G) : f ∈ submodule.span k (of' k G '' (f.support : set G)) := by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end add_monoid_algebra /-! #### Conversions between `add_monoid_algebra` and `monoid_algebra` We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` because historically this caused problems; since the changes that have made `nsmul` definitional, this would be possible, but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`. -/ /-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative` -/ protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) := { to_fun := equiv_map_domain multiplicative.of_add, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [multiplicative.of_add], convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)), end, ..finsupp.dom_congr multiplicative.of_add } /-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/ protected def monoid_algebra.to_additive [semiring k] [has_mul G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) := { to_fun := equiv_map_domain additive.of_mul, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [additive.of_mul], convert monoid_algebra.map_domain_mul (mul_hom.id G), end, ..finsupp.dom_congr additive.of_mul } namespace add_monoid_algebra variables {k G} /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [semiring R] [semiring k] [distrib_mul_action R k] [has_add G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _ _ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _ _ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _ _ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k (add_monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)), .. (monoid_algebra.lift_magma k f : _)}, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), .. (monoid_algebra.lift_magma k : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k _ A) } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra variables {R : Type*} local attribute [reducible] add_monoid_algebra /-- `finsupp.single 0` as a `ring_hom` -/ @[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add], ..finsupp.single_add_hom 0} /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := @monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom) (h_of : (f : add_monoid_algebra k G →* R).comp (of k G) = (g : add_monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) section opposite open finsupp opposite variables [semiring k] /-- The opposite of an `add_monoid_algebra R I` is ring equivalent to the `add_monoid_algebra Rᵒᵖ I` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] : (add_monoid_algebra k G)ᵒᵖ ≃+* add_monoid_algebra kᵒᵖ G := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i r i' r' : 6, dsimp, simp only [map_range_single, single_mul_single, ←op_mul, add_comm] end, ..opposite.op_add_equiv.symm.trans (finsupp.map_range.add_equiv (opposite.op_add_equiv : k ≃+ kᵒᵖ))} @[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) : add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵒᵖ) (x : Gᵒᵖ) : add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) := by simp end opposite /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..single_zero_ring_hom.comp (algebra_map R k) } /-- `finsupp.single 0` as a `alg_hom` -/ @[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : k →ₐ[R] add_monoid_algebra k G := { commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom} @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl end algebra section lift variables {k G} [comm_semiring k] [add_monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) = (φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F}, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ } variables {k G A} lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : multiplicative G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) : (lift k G A).symm F x = F (single x.to_add 1) := rfl lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : multiplicative G →* A) (a b) : lift k G A F (single a b) = b • F (multiplicative.of_add a) := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ end lift section local attribute [reducible] add_monoid_algebra universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end end add_monoid_algebra variables {R : Type*} [comm_semiring R] (k G) /-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative`. -/ def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] : add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) := { commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative], ..add_monoid_algebra.to_multiplicative k G } /-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive`. -/ def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] : monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) := { commutes' := λ r, by simp [monoid_algebra.to_additive], ..monoid_algebra.to_additive k G }
e5994865750bb5743b9e01eec5f153835b8b608e
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/set/lattice.lean
4e13c42e41259aa2e5b51e88a02da4e4734a9dd3
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
27,255
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import logic.basic data.set.basic data.equiv.basic import order.complete_boolean_algebra category.basic import tactic.finish data.sigma.basic order.galois_connection open function tactic set lattice auto universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} namespace set instance lattice_set : complete_lattice (set α) := { lattice.complete_lattice . le := (⊆), le_refl := subset.refl, le_trans := assume a b c, subset.trans, le_antisymm := assume a b, subset.antisymm, lt := λ x y, x ⊆ y ∧ ¬ y ⊆ x, lt_iff_le_not_le := λ x y, iff.refl _, sup := (∪), le_sup_left := subset_union_left, le_sup_right := subset_union_right, sup_le := assume a b c, union_subset, inf := (∩), inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, le_inf := assume a b c, subset_inter, top := {a | true }, le_top := assume s a h, trivial, bot := ∅, bot_le := assume s a, false.elim, Sup := λs, {a | ∃ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in } instance : distrib_lattice (set α) := { le_sup_inf := λ s t u x, or_and_distrib_left.2, ..set.lattice_set } lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff def kern_image (f : α → β) (s : set α) : set β := {y | ∀x, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx x rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {α : Sort u} {s : α → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t):= ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {α : Sort u} {x : β} {s : α → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a theorem subset_Inter {t : set β} {s : α → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le theorem Union_const [inhabited ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem Inter_const [inhabited ι] (s : set β) : (⋂ i:ι, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : - (⋃ i, s i) = (⋂ i, - s i) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : -(⋂ i, s i) = (⋃ i, - s i) := ext (λ x, by simp [classical.not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = - (⋂ i, - s i) := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = - (⋃ i, -s i) := by simp [compl_compl] theorem inter_Union_left (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem inter_Union_right (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union_left [inhabited ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem union_Union_right [inhabited ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter_left [inhabited ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem inter_Inter_right [inhabited ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter_left (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [classical.forall_or_distrib_left] theorem diff_Union_right (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := inter_Union_right _ _ theorem diff_Union_left [inhabited ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter_left]; refl theorem diff_Inter_left (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union_left]; refl /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x, x ∈ s ∧ y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := show t ≤ (⨅ x ∈ s, u x), -- TODO: should not be necessary when sets' order is based on lattices from le_infi $ assume x, le_infi (h x) theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_eq_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) = (⋃ x : s, t x.1) := set.ext $ by simp theorem bInter_eq_Inter (s : set α) (t : α → set β) : (⋂ x ∈ s, t x) = (⋂ x : s, t x.1) := set.ext $ by simp @[simp] theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset @[simp] theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by rw insert_of_has_insert; simp [inter_comm] @[simp] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset @[simp] theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by rw insert_of_has_insert; simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : - (⋃ i ∈ s, t i) = (⋂ i ∈ s, - t i) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : -(⋂ i ∈ s, t i) = (⋃ i ∈ s, - t i) := ext (λ x, by simp [classical.not_forall]) /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ @[simp] theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := (sUnion_insert _ _).trans $ by rw [union_comm, sUnion_singleton] theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := (sInter_insert _ _).trans $ by rw [inter_comm, sInter_singleton] @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image theorem compl_sUnion (S : set (set α)) : - ⋃₀ S = ⋂₀ (compl '' S) := set.ext $ assume x, ⟨assume : ¬ (∃s∈S, x ∈ s), assume s h, match s, h with ._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩ end, assume : ∀s, s ∈ compl '' S → x ∈ s, assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩ -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = - ⋂₀ (compl '' S) := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : - ⋂₀ S = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = -(⋃₀ (compl '' S)) := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem Union_eq_sUnion_range (s : α → set β) : (⋃ i, s i) = ⋃₀ (range s) := by rw [← image_univ, sUnion_image]; simp theorem Inter_eq_sInter_range {α I : Type} (s : I → set α) : (⋂ i, s i) = ⋂₀ (range s) := by rw [← image_univ, sInter_image]; simp theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i.1) := set.ext $ λ x, by simp lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i.1) := set.ext $ λ x, by simp lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { neg := compl, sub := (\), inf_neg_eq_bot := assume s, ext $ assume x, ⟨assume ⟨h, nh⟩, nh h, false.elim⟩, sup_neg_eq_top := assume s, ext $ assume x, ⟨assume h, trivial, assume _, classical.em $ x ∈ s⟩, le_sup_inf := distrib_lattice.le_sup_inf, sub_eq := assume x y, rfl, infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], ..set.lattice_set } @[simp] theorem sub_eq_diff (s t : set α) : s - t = s \ t := rfl section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] end image section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : preimage f (⋃i ∈ s, t i) = (⋃i ∈ s, preimage f (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : preimage f (⋃₀ s) = (⋃t ∈ s, preimage f t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp end preimage section seq def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.refl _ lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : set.prod s t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp] end seq theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) := assume a b h, prod_mono (hf h) (hg h) instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad section pi lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) := by ext; simp [pi] end pi end set /- disjoint sets -/ section disjoint variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] theorem disjoint.symm {a b : α} : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint_mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint_mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint_mono h (le_refl _) theorem disjoint_mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint_mono (le_refl _) h end disjoint theorem set.disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) section open set set_option eqn_compiler.zeta true noncomputable def set.bUnion_eq_sigma_of_disjoint {α β} {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := let f : (Σi:s, t i.val) → (⋃i∈s, t i) := λ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨b, mem_bUnion ha hb⟩ in have injective f, from assume ⟨⟨a₁, ha₁⟩, ⟨b₁, hb₁⟩⟩ ⟨⟨a₂, ha₂⟩, ⟨b₂, hb₂⟩⟩ eq, have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨hb₁, b_eq.symm ▸ hb₂⟩, h _ ha₁ _ ha₂ ne this, sigma.eq (subtype.eq a_eq) (subtype.eq $ by subst b_eq; subst a_eq), have surjective f, from assume ⟨b, hb⟩, have ∃a∈s, b ∈ t a, by simpa using hb, let ⟨a, ha, hb⟩ := this in ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩, (equiv.of_bijective ⟨‹injective f›, ‹surjective f›⟩).symm end
88d1af0568031f0ebf85c917d7c9c4e0a966e074
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/matrix/to_linear_equiv.lean
9f9647fa3f0e358b9a0337e6994433221bb90de8
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,339
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.matrix.nonsingular_inverse import linear_algebra.matrix.to_lin import ring_theory.localization /-! # Matrices and linear equivalences This file gives the map `matrix.to_linear_equiv` from matrices with invertible determinant, to linear equivs. ## Main definitions * `matrix.to_linear_equiv`: a matrix with an invertible determinant forms a linear equiv ## Main results * `matrix.exists_mul_vec_eq_zero_iff`: `M` maps some `v ≠ 0` to zero iff `det M = 0` ## Tags matrix, linear_equiv, determinant, inverse -/ namespace matrix open linear_map variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {n : Type*} [fintype n] section to_linear_equiv' variables [decidable_eq n] /-- An invertible matrix yields a linear equivalence from the free module to itself. See `matrix.to_linear_equiv` for the same map on arbitrary modules. -/ noncomputable def to_linear_equiv' (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) := have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h, { inv_fun := P⁻¹.to_lin', left_inv := λ v, show (P⁻¹.to_lin'.comp P.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.nonsing_inv_mul h', matrix.to_lin'_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin'.comp P⁻¹.to_lin') v = v, by rw [← matrix.to_lin'_mul, P.mul_nonsing_inv h', matrix.to_lin'_one, linear_map.id_apply], ..P.to_lin' } @[simp] lemma to_linear_equiv'_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv' h) : module.End R (n → R)) = P.to_lin' := rfl @[simp] lemma to_linear_equiv'_symm_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv' h).symm : module.End R (n → R)) = P⁻¹.to_lin' := rfl end to_linear_equiv' section to_linear_equiv variables (b : basis n R M) include b /-- Given `hA : is_unit A.det` and `b : basis R b`, `A.to_linear_equiv b hA` is the `linear_equiv` arising from `to_lin b b A`. See `matrix.to_linear_equiv'` for this result on `n → R`. -/ @[simps apply] noncomputable def to_linear_equiv [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : M ≃ₗ[R] M := begin refine { to_fun := to_lin b b A, inv_fun := to_lin b b A⁻¹, left_inv := λ x, _, right_inv := λ x, _, .. to_lin b b A }; rw ← linear_map.comp_apply; simp only [← matrix.to_lin_mul b b b, matrix.nonsing_inv_mul _ hA, matrix.mul_nonsing_inv _ hA, to_lin_one, linear_map.id_apply] end lemma ker_to_lin_eq_bot [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).ker = ⊥ := ker_eq_bot.mpr (to_linear_equiv b A hA).injective lemma range_to_lin_eq_top [decidable_eq n] (A : matrix n n R) (hA : is_unit A.det) : (to_lin b b A).range = ⊤ := range_eq_top.mpr (to_linear_equiv b A hA).surjective end to_linear_equiv section nondegenerate open_locale matrix /-- This holds for all integral domains (see `matrix.exists_mul_vec_eq_zero_iff`), not just fields, but it's easier to prove it for the field of fractions first. -/ lemma exists_mul_vec_eq_zero_iff_aux {K : Type*} [decidable_eq n] [field K] {M : matrix n n K} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := begin split, { rintros ⟨v, hv, mul_eq⟩, contrapose! hv, exact eq_zero_of_mul_vec_eq_zero hv mul_eq }, { contrapose!, intros h, have : function.injective M.to_lin', { simpa only [← linear_map.ker_eq_bot, ker_to_lin'_eq_bot_iff, not_imp_not] using h }, have : M ⬝ linear_map.to_matrix' ((linear_equiv.of_injective_endo M.to_lin' this).symm : (n → K) →ₗ[K] (n → K)) = 1, { refine matrix.to_lin'.injective (linear_map.ext $ λ v, _), rw [matrix.to_lin'_mul, matrix.to_lin'_one, matrix.to_lin'_to_matrix', linear_map.comp_apply], exact (linear_equiv.of_injective_endo M.to_lin' this).apply_symm_apply v }, exact matrix.det_ne_zero_of_right_inverse this } end lemma exists_mul_vec_eq_zero_iff' {A : Type*} (K : Type*) [decidable_eq n] [comm_ring A] [is_domain A] [field K] [algebra A K] [is_fraction_ring A K] {M : matrix n n A} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := begin have : (∃ (v ≠ 0), mul_vec ((algebra_map A K).map_matrix M) v = 0) ↔ _ := exists_mul_vec_eq_zero_iff_aux, rw [← ring_hom.map_det, is_fraction_ring.to_map_eq_zero_iff] at this, refine iff.trans _ this, split; rintro ⟨v, hv, mul_eq⟩, { refine ⟨λ i, algebra_map _ _ (v i), mt (λ h, funext $ λ i, _) hv, _⟩, { exact is_fraction_ring.to_map_eq_zero_iff.mp (congr_fun h i) }, { ext i, refine (ring_hom.map_mul_vec _ _ _ i).symm.trans _, rw [mul_eq, pi.zero_apply, ring_hom.map_zero, pi.zero_apply] } }, { letI := classical.dec_eq K, obtain ⟨⟨b, hb⟩, ba_eq⟩ := is_localization.exist_integer_multiples_of_finset (non_zero_divisors A) (finset.univ.image v), choose f hf using ba_eq, refine ⟨λ i, f _ (finset.mem_image.mpr ⟨i, finset.mem_univ i, rfl⟩), mt (λ h, funext $ λ i, _) hv, _⟩, { have := congr_arg (algebra_map A K) (congr_fun h i), rw [hf, subtype.coe_mk, pi.zero_apply, ring_hom.map_zero, algebra.smul_def, mul_eq_zero, is_fraction_ring.to_map_eq_zero_iff] at this, exact this.resolve_left (mem_non_zero_divisors_iff_ne_zero.mp hb), }, { ext i, refine is_fraction_ring.injective A K _, calc algebra_map A K (M.mul_vec (λ (i : n), f (v i) _) i) = ((algebra_map A K).map_matrix M).mul_vec (algebra_map _ K b • v) i : _ ... = 0 : _ ... = algebra_map A K 0 : (ring_hom.map_zero _).symm, { simp_rw [ring_hom.map_mul_vec, mul_vec, dot_product, function.comp_app, hf, subtype.coe_mk, ring_hom.map_matrix_apply, pi.smul_apply, smul_eq_mul, algebra.smul_def] }, { rw [mul_vec_smul, mul_eq, pi.smul_apply, pi.zero_apply, smul_zero] } } }, end lemma exists_mul_vec_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : (∃ (v ≠ 0), M.mul_vec v = 0) ↔ M.det = 0 := exists_mul_vec_eq_zero_iff' (fraction_ring A) lemma exists_vec_mul_eq_zero_iff {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : (∃ (v ≠ 0), M.vec_mul v = 0) ↔ M.det = 0 := by simpa only [← M.det_transpose, ← mul_vec_transpose] using exists_mul_vec_eq_zero_iff theorem nondegenerate_iff_det_ne_zero {A : Type*} [decidable_eq n] [comm_ring A] [is_domain A] {M : matrix n n A} : nondegenerate M ↔ M.det ≠ 0 := begin refine iff.trans _ (not_iff_not.mpr exists_vec_mul_eq_zero_iff), simp only [not_exists], split, { intros hM v hv hMv, obtain ⟨w, hwMv⟩ := hM.exists_not_ortho_of_ne_zero hv, simpa only [dot_product_mul_vec, hMv, zero_dot_product] using hwMv }, { intros h v hv, refine not_imp_not.mp (h v) (funext $ λ i, _), simpa only [dot_product_mul_vec, dot_product_single, mul_one] using hv (pi.single i 1) } end alias nondegenerate_iff_det_ne_zero ↔ matrix.nondegenerate.det_ne_zero matrix.nondegenerate.of_det_ne_zero end nondegenerate end matrix
720d676044383427ad1ed60413669f877284fa2e
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/algebra/infinite_sum.lean
e17d86982714e93feb3015982da3b898237046ea
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
67,650
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import algebra.big_operators.nat_antidiagonal import logic.encodable.lattice import topology.algebra.mul_action import topology.algebra.order.monotone_convergence import topology.instances.real /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators nnreal variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma has_sum_empty [is_empty β] : has_sum f 0 := by convert has_sum_zero lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma summable_congr (hfg : ∀b, f b = g b) : summable f ↔ summable g := iff_of_eq (congr_arg summable $ funext hfg) lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) : summable g := (summable_congr hfg).mp hf lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] lemma summable_subtype_iff_indicator {s : set β} : summable (f ∘ coe : s → α) ↔ summable (s.indicator f) := exists_congr (λ _, has_sum_subtype_iff_indicator) @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ map_sum g _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable protected lemma summable.map_iff_of_left_inverse [add_comm_monoid γ] [topological_space γ] {G G'} [add_monoid_hom_class G α γ] [add_monoid_hom_class G' γ α] (g : G) (g' : G') (hg : continuous g) (hg' : continuous g') (hinv : function.left_inverse g' g) : summable (g ∘ f) ↔ summable f := ⟨λ h, begin have := h.map _ hg', rwa [←function.comp.assoc, hinv.id] at this, end, λ h, h.map _ hg⟩ /-- A special case of `summable.map_iff_of_left_inverse` for convenience -/ protected lemma summable.map_iff_of_equiv [add_comm_monoid γ] [topological_space γ] {G} [add_equiv_class G α γ] (g : G) (hg : continuous g) (hg' : continuous (add_equiv_class.inv g : γ → α)) : summable (g ∘ f) ↔ summable f := summable.map_iff_of_left_inverse g (g : α ≃+ γ).symm hg hg' (add_equiv_class.left_inv g) /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma function.surjective.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := hes.exists.trans $ exists_congr $ @he section mul_opposite open mul_opposite lemma has_sum.op (hf : has_sum f a) : has_sum (λ a, op (f a)) (op a) := (hf.map (@op_add_equiv α _) continuous_op : _) lemma summable.op (hf : summable f) : summable (op ∘ f) := hf.has_sum.op.summable lemma has_sum.unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} (hf : has_sum f a) : has_sum (λ a, unop (f a)) (unop a) := (hf.map (@op_add_equiv α _).symm continuous_unop : _) lemma summable.unop {f : β → αᵐᵒᵖ} (hf : summable f) : summable (unop ∘ f) := hf.has_sum.unop.summable @[simp] lemma has_sum_op : has_sum (λ a, op (f a)) (op a) ↔ has_sum f a := ⟨has_sum.unop, has_sum.op⟩ @[simp] lemma has_sum_unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} : has_sum (λ a, unop (f a)) (unop a) ↔ has_sum f a := ⟨has_sum.op, has_sum.unop⟩ @[simp] lemma summable_op : summable (λ a, op (f a)) ↔ summable f := ⟨summable.unop, summable.op⟩ @[simp] lemma summable_unop {f : β → αᵐᵒᵖ} : summable (λ a, unop (f a)) ↔ summable f := ⟨summable.op, summable.unop⟩ end mul_opposite section has_continuous_star variables [star_add_monoid α] [has_continuous_star α] lemma has_sum.star (h : has_sum f a) : has_sum (λ b, star (f b)) (star a) := by simpa only using h.map (star_add_equiv : α ≃+ α) continuous_star lemma summable.star (hf : summable f) : summable (λ b, star (f b)) := hf.has_sum.star.summable lemma summable.of_star (hf : summable (λ b, star (f b))) : summable f := by simpa only [star_star] using hf.star @[simp] lemma summable_star_iff : summable (λ b, star (f b)) ↔ summable f := ⟨summable.of_star, summable.star⟩ @[simp] lemma summable_star_iff' : summable (star f) ↔ summable f := summable_star_iff end has_continuous_star variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective₀ (@two_ne_zero ℕ _ _), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [t3_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [t3_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] lemma tsum_congr_subtype (f : β → α) {s t : set β} (h : s = t) : ∑' (x : s), f x = ∑' (x : t), f x := by rw h variables [t2_space α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : ∑'b:β, (0:α) = 0 := has_sum_zero.tsum_eq @[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true := by { rw [tsum_fintype, finset.sum_eq_add]; simp } @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq lemma tsum_tsum_eq_single (f : β → γ → α) (b : β) (c : γ) (hfb : ∀ b' ≠ b, f b' c = 0) (hfc : ∀ (b' : β) (c' : γ), c' ≠ c → f b' c' = 0) : ∑' b' c', f b' c' = f b c := calc ∑' b' c', f b' c' = ∑' b', f b' c : tsum_congr $ λ b', tsum_eq_single _ (hfc b') ... = f b c : tsum_eq_single _ hfb @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma function.surjective.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (hes.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := surjective_id.tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : ∑' x:s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator lemma tsum_op : ∑' x, mul_opposite.op (f x) = mul_opposite.op (∑' x, f x) := begin by_cases h : summable f, { exact h.has_sum.op.tsum_eq, }, { have ho := summable_op.not.mpr h, rw [tsum_eq_zero_of_not_summable h, tsum_eq_zero_of_not_summable ho, mul_opposite.op_zero] }, end lemma tsum_unop {f : β → αᵐᵒᵖ} : ∑' x, mul_opposite.unop (f x) = mul_opposite.unop (∑' x, f x) := mul_opposite.op_injective tsum_op.symm section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [t3_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [t3_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [t3_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section has_continuous_star variables [star_add_monoid α] [has_continuous_star α] lemma tsum_star : star (∑' b, f b) = ∑' b, star (f b) := begin by_cases hf : summable f, { exact hf.has_sum.star.tsum_eq.symm, }, { rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_star hf), star_zero] }, end end has_continuous_star section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some, { intros n h, cases decode₂ γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode₂.1 (option.get_mem (H n hn)), rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] }, { exact option.get_of_mem _ (encodek₂ _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode₂ γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) := tsum_supr_decode₂ m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { rw [← supr_decode₂, ← tsum_supr_decode₂ _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section prod variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ} (hf : has_sum f a) (hg : has_sum g b) : has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ := by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg] end prod section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp only [has_sum, tendsto_pi_nhds, sum_apply] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp only [summable, pi.has_sum, skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp only [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) : summable f := by simpa only [sub_add_cancel] using hfg.add hg lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) : summable f ↔ summable g := ⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩ lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw [h, update_same], simp only [eq_self_iff_true, if_true, sub_add_cancel] }, simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff], end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff lemma has_sum_ite_eq_extract [decidable_eq β] (hf : has_sum f a) (b : β) : has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) := begin convert hf.update b 0 using 1, { ext n, rw function.update_apply, }, { rw [sub_add_eq_add_sub, zero_add], }, end section tsum variables [t2_space α] lemma tsum_neg : ∑'b, - f b = - ∑'b, f b := begin by_cases hf : summable f, { exact hf.has_sum.neg.tsum_eq, }, { simp [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_neg hf)] }, end lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm /-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index. Lemma `tsum_ite_eq_extract` writes `Σ f n` as the sum of `f b` plus the series of the remaining terms. -/ lemma tsum_ite_eq_extract [decidable_eq β] (hf : summable f) (b : β) : ∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) := begin rw (has_sum_ite_eq_extract hf.has_sum b).tsum_eq, exact (add_sub_cancel'_right _ _).symm, end end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).surjective.summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa only [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end /-- If `f₀, f₁, f₂, ...` and `g₀, g₁, g₂, ...` are both convergent then so is the `ℤ`-indexed sequence: `..., g₂, g₁, g₀, f₀, f₁, f₂, ...`. -/ lemma has_sum.int_rec {b : α} {f g : ℕ → α} (hf : has_sum f a) (hg : has_sum g b) : @has_sum α _ _ _ (@int.rec (λ _, α) f g : ℤ → α) (a + b) := begin -- note this proof works for any two-case inductive have h₁ : injective (coe : ℕ → ℤ) := @int.of_nat.inj, have h₂ : injective int.neg_succ_of_nat := @int.neg_succ_of_nat.inj, have : is_compl (set.range (coe : ℕ → ℤ)) (set.range int.neg_succ_of_nat), { split, { rintros _ ⟨⟨i, rfl⟩, ⟨j, ⟨⟩⟩⟩ }, { rintros (i | j) h, exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] } }, exact has_sum.add_is_compl this (h₁.has_sum_range_iff.mpr hf) (h₂.has_sum_range_iff.mpr hg), end lemma has_sum.nonneg_add_neg {b : α} {f : ℤ → α} (hnonneg : has_sum (λ n : ℕ, f n) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + b) := begin simp_rw ← int.neg_succ_of_nat_coe at hneg, convert hnonneg.int_rec hneg using 1, ext (i | j); refl, end lemma has_sum.pos_add_zero_add_neg {b : α} {f : ℤ → α} (hpos : has_sum (λ n:ℕ, f(n + 1)) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + f 0 + b) := begin have : ∀ g : ℕ → α, has_sum (λ k, g (k + 1)) a → has_sum g (a + g 0), { intros g hg, simpa using (has_sum_nat_add_iff _).mp hg }, exact (this (λ n, f n) hpos).nonneg_add_neg hneg, end end subtype end topological_group section topological_semiring variables [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma summable.tsum_mul_left (a) (hf : summable f) : ∑'b, a * f b = a * ∑'b, f b := (hf.has_sum.mul_left _).tsum_eq lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq lemma commute.tsum_right (a) (h : ∀ b, commute a (f b)) : commute a (∑' b, f b) := if hf : summable f then (hf.tsum_mul_left a).symm.trans ((congr_arg _ $ funext h).trans (hf.tsum_mul_right a)) else (tsum_eq_zero_of_not_summable hf).symm ▸ commute.zero_right _ lemma commute.tsum_left (a) (h : ∀ b, commute (f b) a) : commute (∑' b, f b) a := (commute.tsum_right _ $ λ b, (h b).symm).symm end tsum end topological_semiring section const_smul variables {R : Type*} [monoid R] [topological_space α] [add_comm_monoid α] [distrib_mul_action R α] [has_continuous_const_smul R α] {f : β → α} lemma has_sum.const_smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (distrib_mul_action.to_add_monoid_hom α r) (continuous_const_smul r) lemma summable.const_smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.const_smul.summable lemma tsum_const_smul [t2_space α] {r : R} (hf : summable f) : ∑' z, r • f z = r • ∑' z, f z := hf.has_sum.const_smul.tsum_eq end const_smul section smul_const variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [module R α] [has_continuous_smul R α] {f : β → R} lemma has_sum.smul_const {a : α} {r : R} (hf : has_sum f r) : has_sum (λ z, f z • a) (r • a) := hf.map ((smul_add_hom R α).flip a) (continuous_id.smul continuous_const) lemma summable.smul_const {a : α} (hf : summable f) : summable (λ z, f z • a) := hf.has_sum.smul_const.summable lemma tsum_smul_const [t2_space α] {a : α} (hf : summable f) : ∑' z, f z • a = (∑' z, f z) • a := hf.has_sum.smul_const.tsum_eq end smul_const section division_ring variables [division_ring α] [topological_space α] [topological_ring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.div_const (h : has_sum f a) (b : α) : has_sum (λ x, f x / b) (a / b) := by simp only [div_eq_mul_inv, h.mul_right b⁻¹] lemma summable.div_const (h : summable f) (b : α) : summable (λ x, f x / b) := (h.has_sum.div_const b).summable lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left₀ h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right₀ h] using H.mul_right a⁻¹⟩ lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x := if hf : summable f then hf.tsum_mul_left a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero] lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a := if hf : summable f then hf.tsum_mul_right a else if ha : a = 0 then by simp [ha] else by rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul] end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : a ≤ a₂ := le_of_tendsto' hf h lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s : finset β, a₂ ≤ ∑ b in s, f b) : a₂ ≤ a := ge_of_tendsto' hf h lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma is_lub_has_sum (h : ∀ b, 0 ≤ f b) (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set_of_nonneg h) hf lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ ∑' b, f b := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : ∑'b, f b ≤ ∑'b, g b := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := has_sum_le_of_sum_le hf.has_sum h lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s : finset β, ∑ b in s, f b ≤ a₂) : ∑' b, f b ≤ a₂ := begin by_cases hf : summable f, { exact tsum_le_of_sum_le hf h }, { rw tsum_eq_zero_of_not_summable hf, exact ha₂ } end lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ ∑'b, g b := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : ∑'b, f b ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section ordered_topological_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : β → α} {a₁ a₂ : α} lemma has_sum_lt {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {i : β} (h : ∀ (b : β), f b ≤ g b) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg lemma tsum_pos (hsum : summable g) (hg : ∀ b, 0 ≤ g b) (i : β) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum } lemma has_sum_zero_iff_of_nonneg (hf : ∀ i, 0 ≤ f i) : has_sum f 0 ↔ f = 0 := begin split, { intros hf', ext i, by_contra hi', have hi : 0 < f i := lt_of_le_of_ne (hf i) (ne.symm hi'), simpa using has_sum_lt hf hi has_sum_zero hf' }, { rintros rfl, exact has_sum_zero }, end end ordered_topological_group section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range (λ s : finset β, ∑ b in s, f b)) a := is_lub_of_tendsto_at_top (finset.sum_mono_set f) hf end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] /-- The **Cauchy criterion** for infinite sums, also known as the **Cauchy convergence test** -/ lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end local attribute [instance] topological_add_group.t3_space /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero [t1_space α] (f : β → α) : tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin by_cases H : summable f, { assume e he, rcases nhds_is_closed he with ⟨o, ho, oe, o_closed⟩, simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le], obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o := cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho, refine ⟨s, λ a sa, oe _⟩, have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H, apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)), have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s, { apply disjoint_left.2 (λ i hi his, _), rcases mem_image.1 hi with ⟨i', hi', rfl⟩, exact i'.2 (sa his), }, convert hs _ this using 1, rw sum_image, assume i hi j hj hij, exact subtype.ext hij }, { convert tendsto_const_nhds, ext s, apply tsum_eq_zero_of_not_summable, rwa finset.summable_compl_iff } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [t1_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [t1_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [t1_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor lemma has_sum.sum_nat_of_sum_int [t2_space α] {f : ℤ → α} (hf : has_sum f a) : has_sum (λ n:ℕ, f(n + 1) + f(-n.succ)) (a - f 0) := begin obtain ⟨b₁, h₁⟩ : summable (λ n : ℕ, f(n + 1)) := hf.summable.comp_injective (λ x₁ x₂, by simp), obtain ⟨b₂, h₂⟩ : summable (λ n : ℕ, f(-n.succ)) := hf.summable.comp_injective (λ x₁ x₂, by simp), convert h₁.add h₂, rw hf.unique (h₁.pos_add_zero_add_neg h₂), abel, end end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (disjoint_singleton_left.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } lemma summable.tendsto_top_of_pos {α : Type*} [linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α} (hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top := begin rw [show f = f⁻¹⁻¹, by { ext, simp }], apply filter.tendsto.inv_tendsto_zero, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (summable.tendsto_at_top_zero hf), rw eventually_iff_exists_mem, refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩, rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos], exact hf' _, end end topological_group section linear_order /-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper bound for the finite sums is a criterion for summability. This criterion is useful when applied in a linearly ordered monoid which is also a complete or conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check the existence of a least upper bound. -/ lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (h : ∀ b, 0 ≤ f b) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid β] [topological_space β] [order_topology β] {f : α → β} (b : β) (hf : is_lub (set.range (λ s, ∑ a in s, f a)) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set f) hf lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, |f x|) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, |f x|) ↔ summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs lemma finite_of_summable_const [linear_ordered_add_comm_group β] [archimedean β] [topological_space β] [order_closed_topology β] {b : β} (hb : 0 < b) (hf : summable (λ a : α, b)) : set.finite (set.univ : set α) := begin have H : ∀ s : finset α, s.card • b ≤ ∑' a : α, b, { intros s, simpa using sum_le_has_sum s (λ a ha, hb.le) hf.has_sum }, obtain ⟨n, hn⟩ := archimedean.arch (∑' a : α, b) hb, have : ∀ s : finset α, s.card ≤ n, { intros s, simpa [nsmul_le_nsmul_iff hb] using (H s).trans hn }, haveI : fintype α := fintype_of_finset_card_le n this, exact set.finite_univ end end linear_order section cauchy_seq open filter /-- If the extended distance between consecutive points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [pseudo_emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, add_tsub_cancel_left] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consecutive points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ |∑ x in Ico N n, d x| : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_rfl) h lemma dist_le_tsum_of_dist_le_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_rfl) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [pseudo_metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq /-! ## Multipliying two infinite sums In this section, we prove various results about `(∑' x : β, f x) * (∑' y : γ, g y)`. Note that we always assume that the family `λ x : β × γ, f x.1 * g x.2` is summable, since there is no way to deduce this from the summmabilities of `f` and `g` in general, but if you are working in a normed space, you may want to use the analogous lemmas in `analysis/normed_space/basic` (e.g `tsum_mul_tsum_of_summable_norm`). We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to `β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal`). ### Arbitrary index types -/ section tsum_mul_tsum variables [topological_space α] [t3_space α] [non_unital_non_assoc_semiring α] [topological_semiring α] {f : β → α} {g : γ → α} {s t u : α} lemma has_sum.mul_eq (hf : has_sum f s) (hg : has_sum g t) (hfg : has_sum (λ (x : β × γ), f x.1 * g x.2) u) : s * t = u := have key₁ : has_sum (λ b, f b * t) (s * t), from hf.mul_right t, have this : ∀ b : β, has_sum (λ c : γ, f b * g c) (f b * t), from λ b, hg.mul_left (f b), have key₂ : has_sum (λ b, f b * t) u, from has_sum.prod_fiberwise hfg this, key₁.unique key₂ lemma has_sum.mul (hf : has_sum f s) (hg : has_sum g t) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : has_sum (λ (x : β × γ), f x.1 * g x.2) (s * t) := let ⟨u, hu⟩ := hfg in (hf.mul_eq hg hu).symm ▸ hu /-- Product of two infinites sums indexed by arbitrary types. See also `tsum_mul_tsum_of_summable_norm` if `f` and `g` are abolutely summable. -/ lemma tsum_mul_tsum (hf : summable f) (hg : summable g) (hfg : summable (λ (x : β × γ), f x.1 * g x.2)) : (∑' x, f x) * (∑' y, g y) = (∑' z : β × γ, f z.1 * g z.2) := hf.has_sum.mul_eq hg.has_sum hfg.has_sum end tsum_mul_tsum section cauchy_product /-! ### `ℕ`-indexed families (Cauchy product) We prove two versions of the Cauchy product formula. The first one is `tsum_mul_tsum_eq_tsum_sum_range`, where the `n`-th term is a sum over `finset.range (n+1)` involving `nat` substraction. In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal`, where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the `finset` `finset.nat.antidiagonal n` -/ variables {f : ℕ → α} {g : ℕ → α} open finset variables [topological_space α] [non_unital_non_assoc_semiring α] /- The family `(k, l) : ℕ × ℕ ↦ f k * g l` is summable if and only if the family `(n, k, l) : Σ (n : ℕ), nat.antidiagonal n ↦ f k * g l` is summable. -/ lemma summable_mul_prod_iff_summable_mul_sigma_antidiagonal {f g : ℕ → α} : summable (λ x : ℕ × ℕ, f x.1 * g x.2) ↔ summable (λ x : (Σ (n : ℕ), nat.antidiagonal n), f (x.2 : ℕ × ℕ).1 * g (x.2 : ℕ × ℕ).2) := nat.sigma_antidiagonal_equiv_prod.summable_iff.symm variables [t3_space α] [topological_semiring α] lemma summable_sum_mul_antidiagonal_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin rw summable_mul_prod_iff_summable_mul_sigma_antidiagonal at h, conv {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, exact h.sigma' (λ n, (has_sum_fintype _).summable), end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.nat.antidiagonal`. See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ kl in nat.antidiagonal n, f kl.1 * g kl.2) := begin conv_rhs {congr, funext, rw [← finset.sum_finset_coe, ← tsum_fintype]}, rw [tsum_mul_tsum hf hg hfg, ← nat.sigma_antidiagonal_equiv_prod.tsum_eq (_ : ℕ × ℕ → α)], exact tsum_sigma' (λ n, (has_sum_fintype _).summable) (summable_mul_prod_iff_summable_mul_sigma_antidiagonal.mp hfg) end lemma summable_sum_mul_range_of_summable_mul {f g : ℕ → α} (h : summable (λ x : ℕ × ℕ, f x.1 * g x.2)) : summable (λ n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact summable_sum_mul_antidiagonal_of_summable_mul h end /-- The Cauchy product formula for the product of two infinites sums indexed by `ℕ`, expressed by summing on `finset.range`. See also `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm` if `f` and `g` are absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_range (hf : summable f) (hg : summable g) (hfg : summable (λ (x : ℕ × ℕ), f x.1 * g x.2)) : (∑' n, f n) * (∑' n, g n) = (∑' n, ∑ k in range (n+1), f k * g (n - k)) := begin simp_rw ← nat.sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact tsum_mul_tsum_eq_tsum_sum_antidiagonal hf hg hfg end end cauchy_product